import { g as getAugmentedNamespace, a as getDefaultExportFromCjs } from "./libaifw-E-T7C_Rk.js";
function _mergeNamespaces(d, n) {
  for (var o = 0; o < n.length; o++) {
    const u = n[o];
    if (typeof u != "string" && !Array.isArray(u)) {
      for (const l in u)
        if (l !== "default" && !(l in d)) {
          const h = Object.getOwnPropertyDescriptor(u, l);
          h && Object.defineProperty(d, l, h.get ? h : {
            enumerable: !0,
            get: () => u[l]
          });
        }
    }
  }
  return Object.freeze(Object.defineProperty(d, Symbol.toStringTag, { value: "Module" }));
}
function dispatchCallback(d, n) {
  d && d(n);
}
function reverseDictionary(d) {
  return Object.fromEntries(Object.entries(d).map(([n, o]) => [o, n]));
}
function escapeRegExp(d) {
  return d.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const Callable = (
  /** @type {any} */
  class {
    /**
    * Creates a new instance of the Callable class.
    */
    constructor() {
      let d = function(...n) {
        return d._call(...n);
      };
      return Object.setPrototypeOf(d, new.target.prototype);
    }
    /**
     * This method should be implemented in subclasses to provide the
     * functionality of the callable object.
     *
     * @param {any[]} args
     * @throws {Error} If the subclass does not implement the `_call` method.
     */
    _call(...d) {
      throw Error("Must implement _call method in subclass");
    }
  }
);
function isTypedArray(d) {
  return d?.prototype?.__proto__?.constructor?.name === "TypedArray";
}
function isIntegralNumber(d) {
  return Number.isInteger(d) || typeof d == "bigint";
}
function exists(d) {
  return d != null;
}
function mergeArrays(...d) {
  return Array.prototype.concat.apply([], d);
}
const sharp = {}, ONNX_NODE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: sharp
}, Symbol.toStringTag, { value: "Module" }));
var ortWeb_min$1 = { exports: {} };
const backends = {}, backendsSortedByPriority = [], registerBackend = (d, n, o) => {
  if (n && typeof n.init == "function" && typeof n.createSessionHandler == "function") {
    const u = backends[d];
    if (u === void 0)
      backends[d] = { backend: n, priority: o };
    else {
      if (u.priority > o)
        return;
      if (u.priority === o && u.backend !== n)
        throw new Error(`cannot register backend "${d}" using priority ${o}`);
    }
    if (o >= 0) {
      const l = backendsSortedByPriority.indexOf(d);
      l !== -1 && backendsSortedByPriority.splice(l, 1);
      for (let h = 0; h < backendsSortedByPriority.length; h++)
        if (backends[backendsSortedByPriority[h]].priority <= o) {
          backendsSortedByPriority.splice(h, 0, d);
          return;
        }
      backendsSortedByPriority.push(d);
    }
    return;
  }
  throw new TypeError("not a valid backend");
}, resolveBackend = async (d) => {
  const n = d.length === 0 ? backendsSortedByPriority : d, o = [];
  for (const u of n) {
    const l = backends[u];
    if (l) {
      if (l.initialized)
        return l.backend;
      if (l.aborted)
        continue;
      const h = !!l.initPromise;
      try {
        return h || (l.initPromise = l.backend.init()), await l.initPromise, l.initialized = !0, l.backend;
      } catch (a) {
        h || o.push({ name: u, err: a }), l.aborted = !0;
      } finally {
        delete l.initPromise;
      }
    }
  }
  throw new Error(`no available backend found. ERR: ${o.map((u) => `[${u.name}] ${u.err}`).join(", ")}`);
};
class EnvImpl {
  constructor() {
    this.wasm = {}, this.webgl = {}, this.logLevelInternal = "warning";
  }
  // TODO standadize the getter and setter convention in env for other fields.
  set logLevel(n) {
    if (n !== void 0) {
      if (typeof n != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(n) === -1)
        throw new Error(`Unsupported logging level: ${n}`);
      this.logLevelInternal = n;
    }
  }
  get logLevel() {
    return this.logLevelInternal;
  }
}
const env$2 = new EnvImpl(), isBigInt64ArrayAvailable = typeof BigInt64Array < "u" && typeof BigInt64Array.from == "function", isBigUint64ArrayAvailable = typeof BigUint64Array < "u" && typeof BigUint64Array.from == "function", NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = /* @__PURE__ */ new Map([
  ["float32", Float32Array],
  ["uint8", Uint8Array],
  ["int8", Int8Array],
  ["uint16", Uint16Array],
  ["int16", Int16Array],
  ["int32", Int32Array],
  ["bool", Uint8Array],
  ["float64", Float64Array],
  ["uint32", Uint32Array]
]), NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = /* @__PURE__ */ new Map([
  [Float32Array, "float32"],
  [Uint8Array, "uint8"],
  [Int8Array, "int8"],
  [Uint16Array, "uint16"],
  [Int16Array, "int16"],
  [Int32Array, "int32"],
  [Float64Array, "float64"],
  [Uint32Array, "uint32"]
]);
isBigInt64ArrayAvailable && (NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64", BigInt64Array), NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, "int64"));
isBigUint64ArrayAvailable && (NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64", BigUint64Array), NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, "uint64"));
const calculateSize = (d) => {
  let n = 1;
  for (let o = 0; o < d.length; o++) {
    const u = d[o];
    if (typeof u != "number" || !Number.isSafeInteger(u))
      throw new TypeError(`dims[${o}] must be an integer, got: ${u}`);
    if (u < 0)
      throw new RangeError(`dims[${o}] must be a non-negative integer, got: ${u}`);
    n *= u;
  }
  return n;
};
let Tensor$2 = class st {
  constructor(n, o, u) {
    let l, h, a;
    if (typeof n == "string")
      if (l = n, a = u, n === "string") {
        if (!Array.isArray(o))
          throw new TypeError("A string tensor's data must be a string array.");
        h = o;
      } else {
        const g = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(n);
        if (g === void 0)
          throw new TypeError(`Unsupported tensor type: ${n}.`);
        if (Array.isArray(o))
          h = g.from(o);
        else if (o instanceof g)
          h = o;
        else
          throw new TypeError(`A ${l} tensor's data must be type of ${g}`);
      }
    else if (a = o, Array.isArray(n)) {
      if (n.length === 0)
        throw new TypeError("Tensor type cannot be inferred from an empty array.");
      const g = typeof n[0];
      if (g === "string")
        l = "string", h = n;
      else if (g === "boolean")
        l = "bool", h = Uint8Array.from(n);
      else
        throw new TypeError(`Invalid element type of data array: ${g}.`);
    } else {
      const g = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(n.constructor);
      if (g === void 0)
        throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);
      l = g, h = n;
    }
    if (a === void 0)
      a = [h.length];
    else if (!Array.isArray(a))
      throw new TypeError("A tensor's dims must be a number array");
    const f = calculateSize(a);
    if (f !== h.length)
      throw new Error(`Tensor's size(${f}) does not match data length(${h.length}).`);
    this.dims = a, this.type = l, this.data = h, this.size = f;
  }
  // #endregion
  /**
   * Create a new tensor object from image object
   *
   * @param buffer - Extracted image buffer data - assuming RGBA format
   * @param imageFormat - input image configuration - required configurations height, width, format
   * @param tensorFormat - output tensor configuration - Default is RGB format
   */
  static bufferToTensor(n, o) {
    if (n === void 0)
      throw new Error("Image buffer must be defined");
    if (o.height === void 0 || o.width === void 0)
      throw new Error("Image height and width must be defined");
    const { height: u, width: l } = o, h = o.norm;
    let a, f;
    h === void 0 || h.mean === void 0 ? a = 255 : a = h.mean, h === void 0 || h.bias === void 0 ? f = 0 : f = h.bias;
    const g = o.bitmapFormat !== void 0 ? o.bitmapFormat : "RGBA", c = o.tensorFormat !== void 0 && o.tensorFormat !== void 0 ? o.tensorFormat : "RGB", s = u * l, t = c === "RGBA" ? new Float32Array(s * 4) : new Float32Array(s * 3);
    let e = 4, r = 0, i = 1, p = 2, m = 3, _ = 0, b = s, y = s * 2, w = -1;
    g === "RGB" && (e = 3, r = 0, i = 1, p = 2, m = -1), c === "RGBA" ? w = s * 3 : c === "RBG" ? (_ = 0, y = s, b = s * 2) : c === "BGR" && (y = 0, b = s, _ = s * 2);
    for (let S = 0; S < s; S++, r += e, p += e, i += e, m += e)
      t[_++] = (n[r] + f) / a, t[b++] = (n[i] + f) / a, t[y++] = (n[p] + f) / a, w !== -1 && m !== -1 && (t[w++] = (n[m] + f) / a);
    return c === "RGBA" ? new st("float32", t, [1, 4, u, l]) : new st("float32", t, [1, 3, u, l]);
  }
  static async fromImage(n, o) {
    const u = typeof HTMLImageElement < "u" && n instanceof HTMLImageElement, l = typeof ImageData < "u" && n instanceof ImageData, h = typeof ImageBitmap < "u" && n instanceof ImageBitmap, a = typeof String < "u" && (n instanceof String || typeof n == "string");
    let f, g = {};
    if (u) {
      const c = document.createElement("canvas"), s = c.getContext("2d");
      if (s != null) {
        let t = n.naturalHeight, e = n.naturalWidth;
        if (o !== void 0 && o.resizedHeight !== void 0 && o.resizedWidth !== void 0 && (t = o.resizedHeight, e = o.resizedWidth), o !== void 0) {
          if (g = o, o.tensorFormat !== void 0)
            throw new Error("Image input config format must be RGBA for HTMLImageElement");
          if (g.tensorFormat = "RGBA", o.height !== void 0 && o.height !== t)
            throw new Error("Image input config height doesn't match HTMLImageElement height");
          if (g.height = t, o.width !== void 0 && o.width !== e)
            throw new Error("Image input config width doesn't match HTMLImageElement width");
          g.width = e;
        } else
          g.tensorFormat = "RGBA", g.height = t, g.width = e;
        c.width = e, c.height = t, s.drawImage(n, 0, 0, e, t), f = s.getImageData(0, 0, e, t).data;
      } else
        throw new Error("Can not access image data");
    } else if (l) {
      const c = "RGBA";
      let s, t;
      if (o !== void 0 && o.resizedWidth !== void 0 && o.resizedHeight !== void 0 ? (s = o.resizedHeight, t = o.resizedWidth) : (s = n.height, t = n.width), o !== void 0) {
        if (g = o, o.bitmapFormat !== void 0 && o.bitmapFormat !== c)
          throw new Error("Image input config format must be RGBA for ImageData");
        g.bitmapFormat = "RGBA";
      } else
        g.bitmapFormat = "RGBA";
      if (g.height = s, g.width = t, o !== void 0) {
        const e = document.createElement("canvas");
        e.width = t, e.height = s;
        const r = e.getContext("2d");
        if (r != null)
          r.putImageData(n, 0, 0), f = r.getImageData(0, 0, t, s).data;
        else
          throw new Error("Can not access image data");
      } else
        f = n.data;
    } else if (h) {
      if (o === void 0)
        throw new Error("Please provide image config with format for Imagebitmap");
      if (o.bitmapFormat !== void 0)
        throw new Error("Image input config format must be defined for ImageBitmap");
      const c = document.createElement("canvas").getContext("2d");
      if (c != null) {
        const s = n.height, t = n.width;
        if (c.drawImage(n, 0, 0, t, s), f = c.getImageData(0, 0, t, s).data, o !== void 0) {
          if (o.height !== void 0 && o.height !== s)
            throw new Error("Image input config height doesn't match ImageBitmap height");
          if (g.height = s, o.width !== void 0 && o.width !== t)
            throw new Error("Image input config width doesn't match ImageBitmap width");
          g.width = t;
        } else
          g.height = s, g.width = t;
        return st.bufferToTensor(f, g);
      } else
        throw new Error("Can not access image data");
    } else {
      if (a)
        return new Promise((c, s) => {
          const t = document.createElement("canvas"), e = t.getContext("2d");
          if (!n || !e)
            return s();
          const r = new Image();
          r.crossOrigin = "Anonymous", r.src = n, r.onload = () => {
            t.width = r.width, t.height = r.height, e.drawImage(r, 0, 0, t.width, t.height);
            const i = e.getImageData(0, 0, t.width, t.height);
            if (o !== void 0) {
              if (o.height !== void 0 && o.height !== t.height)
                throw new Error("Image input config height doesn't match ImageBitmap height");
              if (g.height = t.height, o.width !== void 0 && o.width !== t.width)
                throw new Error("Image input config width doesn't match ImageBitmap width");
              g.width = t.width;
            } else
              g.height = t.height, g.width = t.width;
            c(st.bufferToTensor(i.data, g));
          };
        });
      throw new Error("Input data provided is not supported - aborted tensor creation");
    }
    if (f !== void 0)
      return st.bufferToTensor(f, g);
    throw new Error("Input data provided is not supported - aborted tensor creation");
  }
  toImageData(n) {
    var o, u;
    const l = document.createElement("canvas").getContext("2d");
    let h;
    if (l != null) {
      const a = this.dims[3], f = this.dims[2], g = this.dims[1], c = n !== void 0 && n.format !== void 0 ? n.format : "RGB", s = n !== void 0 && ((o = n.norm) === null || o === void 0 ? void 0 : o.mean) !== void 0 ? n.norm.mean : 255, t = n !== void 0 && ((u = n.norm) === null || u === void 0 ? void 0 : u.bias) !== void 0 ? n.norm.bias : 0, e = f * a;
      if (n !== void 0) {
        if (n.height !== void 0 && n.height !== f)
          throw new Error("Image output config height doesn't match tensor height");
        if (n.width !== void 0 && n.width !== a)
          throw new Error("Image output config width doesn't match tensor width");
        if (n.format !== void 0 && g === 4 && n.format !== "RGBA" || g === 3 && n.format !== "RGB" && n.format !== "BGR")
          throw new Error("Tensor format doesn't match input tensor dims");
      }
      const r = 4;
      let i = 0, p = 1, m = 2, _ = 3, b = 0, y = e, w = e * 2, T = -1;
      c === "RGBA" ? (b = 0, y = e, w = e * 2, T = e * 3) : c === "RGB" ? (b = 0, y = e, w = e * 2) : c === "RBG" && (b = 0, w = e, y = e * 2), h = l.createImageData(a, f);
      for (let S = 0; S < f * a; i += r, p += r, m += r, _ += r, S++)
        h.data[i] = (this.data[b++] - t) * s, h.data[p] = (this.data[y++] - t) * s, h.data[m] = (this.data[w++] - t) * s, h.data[_] = T === -1 ? 255 : (this.data[T++] - t) * s;
    } else
      throw new Error("Can not access image data");
    return h;
  }
  // #endregion
  // #region tensor utilities
  reshape(n) {
    return new st(this.type, this.data, n);
  }
};
const Tensor$1 = Tensor$2;
let InferenceSession$2 = class ln {
  constructor(n) {
    this.handler = n;
  }
  async run(n, o, u) {
    const l = {};
    let h = {};
    if (typeof n != "object" || n === null || n instanceof Tensor$1 || Array.isArray(n))
      throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");
    let a = !0;
    if (typeof o == "object") {
      if (o === null)
        throw new TypeError("Unexpected argument[1]: cannot be null.");
      if (o instanceof Tensor$1)
        throw new TypeError("'fetches' cannot be a Tensor");
      if (Array.isArray(o)) {
        if (o.length === 0)
          throw new TypeError("'fetches' cannot be an empty array.");
        a = !1;
        for (const c of o) {
          if (typeof c != "string")
            throw new TypeError("'fetches' must be a string array or an object.");
          if (this.outputNames.indexOf(c) === -1)
            throw new RangeError(`'fetches' contains invalid output name: ${c}.`);
          l[c] = null;
        }
        if (typeof u == "object" && u !== null)
          h = u;
        else if (typeof u < "u")
          throw new TypeError("'options' must be an object.");
      } else {
        let c = !1;
        const s = Object.getOwnPropertyNames(o);
        for (const t of this.outputNames)
          if (s.indexOf(t) !== -1) {
            const e = o[t];
            (e === null || e instanceof Tensor$1) && (c = !0, a = !1, l[t] = e);
          }
        if (c) {
          if (typeof u == "object" && u !== null)
            h = u;
          else if (typeof u < "u")
            throw new TypeError("'options' must be an object.");
        } else
          h = o;
      }
    } else if (typeof o < "u")
      throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");
    for (const c of this.inputNames)
      if (typeof n[c] > "u")
        throw new Error(`input '${c}' is missing in 'feeds'.`);
    if (a)
      for (const c of this.outputNames)
        l[c] = null;
    const f = await this.handler.run(n, l, h), g = {};
    for (const c in f)
      Object.hasOwnProperty.call(f, c) && (g[c] = new Tensor$1(f[c].type, f[c].data, f[c].dims));
    return g;
  }
  static async create(n, o, u, l) {
    let h, a = {};
    if (typeof n == "string") {
      if (h = n, typeof o == "object" && o !== null)
        a = o;
      else if (typeof o < "u")
        throw new TypeError("'options' must be an object.");
    } else if (n instanceof Uint8Array) {
      if (h = n, typeof o == "object" && o !== null)
        a = o;
      else if (typeof o < "u")
        throw new TypeError("'options' must be an object.");
    } else if (n instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && n instanceof SharedArrayBuffer) {
      const t = n;
      let e = 0, r = n.byteLength;
      if (typeof o == "object" && o !== null)
        a = o;
      else if (typeof o == "number") {
        if (e = o, !Number.isSafeInteger(e))
          throw new RangeError("'byteOffset' must be an integer.");
        if (e < 0 || e >= t.byteLength)
          throw new RangeError(`'byteOffset' is out of range [0, ${t.byteLength}).`);
        if (r = n.byteLength - e, typeof u == "number") {
          if (r = u, !Number.isSafeInteger(r))
            throw new RangeError("'byteLength' must be an integer.");
          if (r <= 0 || e + r > t.byteLength)
            throw new RangeError(`'byteLength' is out of range (0, ${t.byteLength - e}].`);
          if (typeof l == "object" && l !== null)
            a = l;
          else if (typeof l < "u")
            throw new TypeError("'options' must be an object.");
        } else if (typeof u < "u")
          throw new TypeError("'byteLength' must be a number.");
      } else if (typeof o < "u")
        throw new TypeError("'options' must be an object.");
      h = new Uint8Array(t, e, r);
    } else
      throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");
    const g = (a.executionProviders || []).map((t) => typeof t == "string" ? t : t.name), s = await (await resolveBackend(g)).createSessionHandler(h, a);
    return new ln(s);
  }
  startProfiling() {
    this.handler.startProfiling();
  }
  endProfiling() {
    this.handler.endProfiling();
  }
  get inputNames() {
    return this.handler.inputNames;
  }
  get outputNames() {
    return this.handler.outputNames;
  }
};
const InferenceSession$1 = InferenceSession$2, lib = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  InferenceSession: InferenceSession$1,
  Tensor: Tensor$1,
  env: env$2,
  registerBackend
}, Symbol.toStringTag, { value: "Module" })), require$$0 = /* @__PURE__ */ getAugmentedNamespace(lib);
var hasRequiredOrtWeb_min;
function requireOrtWeb_min() {
  return hasRequiredOrtWeb_min || (hasRequiredOrtWeb_min = 1, (function(module, exports$1) {
    (function(d, n) {
      module.exports = n(require$$0);
    })(self, ((__WEBPACK_EXTERNAL_MODULE__1670__) => (() => {
      var __webpack_modules__ = { 3474: (d, n, o) => {
        var u, l = (u = (u = typeof document < "u" && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(h) {
          function a() {
            return Y.buffer != ne && Pe(Y.buffer), me;
          }
          function f() {
            return Y.buffer != ne && Pe(Y.buffer), Ae;
          }
          function g() {
            return Y.buffer != ne && Pe(Y.buffer), Ee;
          }
          function c() {
            return Y.buffer != ne && Pe(Y.buffer), ce;
          }
          function s() {
            return Y.buffer != ne && Pe(Y.buffer), ve;
          }
          var t, e, r;
          h = h || {}, t || (t = h !== void 0 ? h : {}), t.ready = new Promise((function(x, P) {
            e = x, r = P;
          }));
          var i, p, m, _, b, y, w = Object.assign({}, t), T = "./this.program", S = (x, P) => {
            throw P;
          }, E = typeof window == "object", O = typeof importScripts == "function", v = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", A = t.ENVIRONMENT_IS_PTHREAD || !1, L = "";
          function j(x) {
            return t.locateFile ? t.locateFile(x, L) : L + x;
          }
          if (v) {
            let x;
            L = O ? o(908).dirname(L) + "/" : "//", y = () => {
              b || (_ = o(1384), b = o(908));
            }, i = function(P, k) {
              return y(), P = b.normalize(P), _.readFileSync(P, k ? void 0 : "utf8");
            }, m = (P) => ((P = i(P, !0)).buffer || (P = new Uint8Array(P)), P), p = (P, k, N) => {
              y(), P = b.normalize(P), _.readFile(P, (function(z, G) {
                z ? N(z) : k(G.buffer);
              }));
            }, 1 < process.argv.length && (T = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", (function(P) {
              if (!(P instanceof Qe)) throw P;
            })), process.on("unhandledRejection", (function(P) {
              throw P;
            })), S = (P, k) => {
              if (Ue()) throw process.exitCode = P, k;
              k instanceof Qe || $("exiting due to exception: " + k), process.exit(P);
            }, t.inspect = function() {
              return "[Emscripten Module object]";
            };
            try {
              x = o(9925);
            } catch (P) {
              throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), P;
            }
            o.g.Worker = x.Worker;
          } else (E || O) && (O ? L = self.location.href : typeof document < "u" && document.currentScript && (L = document.currentScript.src), u && (L = u), L = L.indexOf("blob:") !== 0 ? L.substr(0, L.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", v || (i = (x) => {
            var P = new XMLHttpRequest();
            return P.open("GET", x, !1), P.send(null), P.responseText;
          }, O && (m = (x) => {
            var P = new XMLHttpRequest();
            return P.open("GET", x, !1), P.responseType = "arraybuffer", P.send(null), new Uint8Array(P.response);
          }), p = (x, P, k) => {
            var N = new XMLHttpRequest();
            N.open("GET", x, !0), N.responseType = "arraybuffer", N.onload = () => {
              N.status == 200 || N.status == 0 && N.response ? P(N.response) : k();
            }, N.onerror = k, N.send(null);
          }));
          v && typeof performance > "u" && (o.g.performance = o(6953).performance);
          var B = console.log.bind(console), F = console.warn.bind(console);
          v && (y(), B = (x) => _.writeSync(1, x + `
`), F = (x) => _.writeSync(2, x + `
`));
          var D, I = t.print || B, $ = t.printErr || F;
          Object.assign(t, w), w = null, t.thisProgram && (T = t.thisProgram), t.quit && (S = t.quit), t.wasmBinary && (D = t.wasmBinary);
          var Q = t.noExitRuntime || !1;
          typeof WebAssembly != "object" && he("no native wasm support detected");
          var Y, te, ne, me, Ae, Ee, ce, ve, ye = !1, Le = typeof TextDecoder < "u" ? new TextDecoder("utf8") : void 0;
          function We(x, P, k) {
            var N = (P >>>= 0) + k;
            for (k = P; x[k] && !(k >= N); ) ++k;
            if (16 < k - P && x.buffer && Le) return Le.decode(x.buffer instanceof SharedArrayBuffer ? x.slice(P, k) : x.subarray(P, k));
            for (N = ""; P < k; ) {
              var z = x[P++];
              if (128 & z) {
                var G = 63 & x[P++];
                if ((224 & z) == 192) N += String.fromCharCode((31 & z) << 6 | G);
                else {
                  var X = 63 & x[P++];
                  65536 > (z = (240 & z) == 224 ? (15 & z) << 12 | G << 6 | X : (7 & z) << 18 | G << 12 | X << 6 | 63 & x[P++]) ? N += String.fromCharCode(z) : (z -= 65536, N += String.fromCharCode(55296 | z >> 10, 56320 | 1023 & z));
                }
              } else N += String.fromCharCode(z);
            }
            return N;
          }
          function Oe(x, P) {
            return (x >>>= 0) ? We(f(), x, P) : "";
          }
          function Ne(x, P, k, N) {
            if (!(0 < N)) return 0;
            var z = k >>>= 0;
            N = k + N - 1;
            for (var G = 0; G < x.length; ++G) {
              var X = x.charCodeAt(G);
              if (55296 <= X && 57343 >= X && (X = 65536 + ((1023 & X) << 10) | 1023 & x.charCodeAt(++G)), 127 >= X) {
                if (k >= N) break;
                P[k++ >>> 0] = X;
              } else {
                if (2047 >= X) {
                  if (k + 1 >= N) break;
                  P[k++ >>> 0] = 192 | X >> 6;
                } else {
                  if (65535 >= X) {
                    if (k + 2 >= N) break;
                    P[k++ >>> 0] = 224 | X >> 12;
                  } else {
                    if (k + 3 >= N) break;
                    P[k++ >>> 0] = 240 | X >> 18, P[k++ >>> 0] = 128 | X >> 12 & 63;
                  }
                  P[k++ >>> 0] = 128 | X >> 6 & 63;
                }
                P[k++ >>> 0] = 128 | 63 & X;
              }
            }
            return P[k >>> 0] = 0, k - z;
          }
          function Ce(x) {
            for (var P = 0, k = 0; k < x.length; ++k) {
              var N = x.charCodeAt(k);
              127 >= N ? P++ : 2047 >= N ? P += 2 : 55296 <= N && 57343 >= N ? (P += 4, ++k) : P += 3;
            }
            return P;
          }
          function Pe(x) {
            ne = x, t.HEAP8 = me = new Int8Array(x), t.HEAP16 = new Int16Array(x), t.HEAP32 = Ee = new Int32Array(x), t.HEAPU8 = Ae = new Uint8Array(x), t.HEAPU16 = new Uint16Array(x), t.HEAPU32 = ce = new Uint32Array(x), t.HEAPF32 = new Float32Array(x), t.HEAPF64 = ve = new Float64Array(x);
          }
          A && (ne = t.buffer);
          var Te = t.INITIAL_MEMORY || 16777216;
          if (A) Y = t.wasmMemory, ne = t.buffer;
          else if (t.wasmMemory) Y = t.wasmMemory;
          else if (!((Y = new WebAssembly.Memory({ initial: Te / 65536, maximum: 65536, shared: !0 })).buffer instanceof SharedArrayBuffer)) throw $("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), v && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory");
          Y && (ne = Y.buffer), Te = ne.byteLength, Pe(ne);
          var Be, Ve = [], ze = [], He = [], Xe = [];
          function Ue() {
            return Q || !1;
          }
          function je() {
            var x = t.preRun.shift();
            Ve.unshift(x);
          }
          var Se, $e = 0, Ye = null;
          function he(x) {
            throw A ? postMessage({ cmd: "onAbort", arg: x }) : t.onAbort && t.onAbort(x), $(x = "Aborted(" + x + ")"), ye = !0, x = new WebAssembly.RuntimeError(x + ". Build with -sASSERTIONS for more info."), r(x), x;
          }
          function dt() {
            return Se.startsWith("data:application/octet-stream;base64,");
          }
          function at() {
            var x = Se;
            try {
              if (x == Se && D) return new Uint8Array(D);
              if (m) return m(x);
              throw "both async and sync fetching of the wasm failed";
            } catch (P) {
              he(P);
            }
          }
          Se = "ort-wasm-threaded.wasm", dt() || (Se = j(Se));
          var Ot = {};
          function Qe(x) {
            this.name = "ExitStatus", this.message = "Program terminated with exit(" + x + ")", this.status = x;
          }
          function ut(x) {
            (x = re.Vb[x]) || he(), re.mc(x);
          }
          function lt(x) {
            var P = re.Cc();
            if (!P) return 6;
            re.ac.push(P), re.Vb[x.Ub] = P, P.Ub = x.Ub;
            var k = { cmd: "run", start_routine: x.Ic, arg: x.zc, pthread_ptr: x.Ub };
            return P.$b = () => {
              k.time = performance.now(), P.postMessage(k, x.Nc);
            }, P.loaded && (P.$b(), delete P.$b), 0;
          }
          function Fe(x) {
            if (A) return J(1, 1, x);
            Ue() || (re.oc(), t.onExit && t.onExit(x), ye = !0), S(x, new Qe(x));
          }
          function nt(x, P) {
            if (!P && A) throw Mt(x), "unwind";
            Ue() || A || (Gt(), tt(He), Ut(0), Dt[1].length && Nt(1, 10), Dt[2].length && Nt(2, 10), re.oc()), Fe(x);
          }
          var re = { Yb: [], ac: [], qc: [], Vb: {}, fc: function() {
            A && re.Ec();
          }, Pc: function() {
          }, Ec: function() {
            re.receiveObjectTransfer = re.Gc, re.threadInitTLS = re.pc, re.setExitStatus = re.nc, Q = !1;
          }, nc: function() {
          }, oc: function() {
            for (var x of Object.values(re.Vb)) re.mc(x);
            for (x of re.Yb) x.terminate();
            re.Yb = [];
          }, mc: function(x) {
            var P = x.Ub;
            delete re.Vb[P], re.Yb.push(x), re.ac.splice(re.ac.indexOf(x), 1), x.Ub = 0, Lt(P);
          }, Gc: function() {
          }, pc: function() {
            re.qc.forEach(((x) => x()));
          }, Fc: function(x, P) {
            x.onmessage = (k) => {
              var N = (k = k.data).cmd;
              if (x.Ub && (re.Bc = x.Ub), k.targetThread && k.targetThread != kt()) {
                var z = re.Vb[k.Qc];
                z ? z.postMessage(k, k.transferList) : $('Internal error! Worker sent a message "' + N + '" to target pthread ' + k.targetThread + ", but that thread no longer exists!");
              } else N === "processProxyingQueue" ? R(k.queue) : N === "spawnThread" ? lt(k) : N === "cleanupThread" ? ut(k.thread) : N === "killThread" ? (k = k.thread, N = re.Vb[k], delete re.Vb[k], N.terminate(), Lt(k), re.ac.splice(re.ac.indexOf(N), 1), N.Ub = 0) : N === "cancelThread" ? re.Vb[k.thread].postMessage({ cmd: "cancel" }) : N === "loaded" ? (x.loaded = !0, P && P(x), x.$b && (x.$b(), delete x.$b)) : N === "print" ? I("Thread " + k.threadId + ": " + k.text) : N === "printErr" ? $("Thread " + k.threadId + ": " + k.text) : N === "alert" ? alert("Thread " + k.threadId + ": " + k.text) : k.target === "setimmediate" ? x.postMessage(k) : N === "onAbort" ? t.onAbort && t.onAbort(k.arg) : N && $("worker sent an unknown command " + N);
              re.Bc = void 0;
            }, x.onerror = (k) => {
              throw $("worker sent an error! " + k.filename + ":" + k.lineno + ": " + k.message), k;
            }, v && (x.on("message", (function(k) {
              x.onmessage({ data: k });
            })), x.on("error", (function(k) {
              x.onerror(k);
            })), x.on("detachedExit", (function() {
            }))), x.postMessage({ cmd: "load", urlOrBlob: t.mainScriptUrlOrBlob || u, wasmMemory: Y, wasmModule: te });
          }, yc: function() {
            var x = j("ort-wasm-threaded.worker.js");
            re.Yb.push(new Worker(x));
          }, Cc: function() {
            return re.Yb.length == 0 && (re.yc(), re.Fc(re.Yb[0])), re.Yb.pop();
          } };
          function tt(x) {
            for (; 0 < x.length; ) x.shift()(t);
          }
          function Pt(x) {
            var P = le();
            return x = x(), ue(P), x;
          }
          function Mt(x) {
            if (A) return J(2, 0, x);
            try {
              nt(x);
            } catch (P) {
              P instanceof Qe || P == "unwind" || S(1, P);
            }
          }
          t.PThread = re, t.establishStackSpace = function() {
            var x = kt(), P = g()[x + 44 >> 2 >>> 0];
            x = g()[x + 48 >> 2 >>> 0], Kt(P, P - x), ue(P);
          };
          var Je = [];
          function be(x) {
            var P = Je[x];
            return P || (x >= Je.length && (Je.length = x + 1), Je[x] = P = Be.get(x)), P;
          }
          t.invokeEntryPoint = function(x, P) {
            x = be(x)(P), Ue() ? re.nc(x) : Yt(x);
          };
          var rt, pt, it = [], se = 0, ie = 0;
          function oe(x) {
            this.Zb = x, this.Sb = x - 24, this.xc = function(P) {
              c()[this.Sb + 4 >> 2 >>> 0] = P;
            }, this.bc = function() {
              return c()[this.Sb + 4 >> 2 >>> 0];
            }, this.wc = function(P) {
              c()[this.Sb + 8 >> 2 >>> 0] = P;
            }, this.Dc = function() {
              return c()[this.Sb + 8 >> 2 >>> 0];
            }, this.rc = function() {
              g()[this.Sb >> 2 >>> 0] = 0;
            }, this.hc = function(P) {
              P = P ? 1 : 0, a()[this.Sb + 12 >> 0 >>> 0] = P;
            }, this.uc = function() {
              return a()[this.Sb + 12 >> 0 >>> 0] != 0;
            }, this.ic = function(P) {
              P = P ? 1 : 0, a()[this.Sb + 13 >> 0 >>> 0] = P;
            }, this.kc = function() {
              return a()[this.Sb + 13 >> 0 >>> 0] != 0;
            }, this.fc = function(P, k) {
              this.cc(0), this.xc(P), this.wc(k), this.rc(), this.hc(!1), this.ic(!1);
            }, this.sc = function() {
              Atomics.add(g(), this.Sb >> 2, 1);
            }, this.Hc = function() {
              return Atomics.sub(g(), this.Sb >> 2, 1) === 1;
            }, this.cc = function(P) {
              c()[this.Sb + 16 >> 2 >>> 0] = P;
            }, this.tc = function() {
              return c()[this.Sb + 16 >> 2 >>> 0];
            }, this.vc = function() {
              if (Xt(this.bc())) return c()[this.Zb >> 2 >>> 0];
              var P = this.tc();
              return P !== 0 ? P : this.Zb;
            };
          }
          function ht(x) {
            return zt(new oe(x).Sb);
          }
          function ot(x, P, k, N) {
            return A ? J(3, 1, x, P, k, N) : ft(x, P, k, N);
          }
          function ft(x, P, k, N) {
            if (typeof SharedArrayBuffer > "u") return $("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
            var z = [];
            return A && z.length === 0 ? ot(x, P, k, N) : (x = { Ic: k, Ub: x, zc: N, Nc: z }, A ? (x.Oc = "spawnThread", postMessage(x, z), 0) : lt(x));
          }
          function gt(x, P, k) {
            return A ? J(4, 1, x, P, k) : 0;
          }
          function mt(x, P) {
            if (A) return J(5, 1, x, P);
          }
          function _t(x, P) {
            if (A) return J(6, 1, x, P);
          }
          function bt(x, P, k) {
            if (A) return J(7, 1, x, P, k);
          }
          function yt(x, P, k) {
            return A ? J(8, 1, x, P, k) : 0;
          }
          function wt(x, P) {
            if (A) return J(9, 1, x, P);
          }
          function Tt(x, P, k) {
            if (A) return J(10, 1, x, P, k);
          }
          function vt(x, P, k, N) {
            if (A) return J(11, 1, x, P, k, N);
          }
          function xt(x, P, k, N) {
            if (A) return J(12, 1, x, P, k, N);
          }
          function St(x, P, k, N) {
            if (A) return J(13, 1, x, P, k, N);
          }
          function Et(x) {
            if (A) return J(14, 1, x);
          }
          function M(x, P) {
            if (A) return J(15, 1, x, P);
          }
          function C(x, P, k) {
            if (A) return J(16, 1, x, P, k);
          }
          function R(x) {
            Atomics.store(g(), x >> 2, 1), kt() && Ht(x), Atomics.compareExchange(g(), x >> 2, 1, 0);
          }
          function V(x) {
            return c()[x >>> 2] + 4294967296 * g()[x + 4 >>> 2];
          }
          function U(x, P, k, N, z, G) {
            return A ? J(17, 1, x, P, k, N, z, G) : -52;
          }
          function H(x, P, k, N, z, G) {
            if (A) return J(18, 1, x, P, k, N, z, G);
          }
          function K(x) {
            var P = Ce(x) + 1, k = Ft(P);
            return k && Ne(x, a(), k, P), k;
          }
          function Z(x, P, k) {
            function N(fe) {
              return (fe = fe.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? fe[1] : "GMT";
            }
            if (A) return J(19, 1, x, P, k);
            var z = (/* @__PURE__ */ new Date()).getFullYear(), G = new Date(z, 0, 1), X = new Date(z, 6, 1);
            z = G.getTimezoneOffset();
            var ee = X.getTimezoneOffset(), pe = Math.max(z, ee);
            g()[x >> 2 >>> 0] = 60 * pe, g()[P >> 2 >>> 0] = +(z != ee), x = N(G), P = N(X), x = K(x), P = K(P), ee < z ? (c()[k >> 2 >>> 0] = x, c()[k + 4 >> 2 >>> 0] = P) : (c()[k >> 2 >>> 0] = P, c()[k + 4 >> 2 >>> 0] = x);
          }
          function J(x, P) {
            var k = arguments.length - 2, N = arguments;
            return Pt((() => {
              for (var z = $t(8 * k), G = z >> 3, X = 0; X < k; X++) {
                var ee = N[2 + X];
                s()[G + X >>> 0] = ee;
              }
              return Wt(x, k, z, P);
            }));
          }
          t.executeNotifiedProxyingQueue = R, pt = v ? () => {
            var x = process.hrtime();
            return 1e3 * x[0] + x[1] / 1e6;
          } : A ? () => performance.now() - t.__performance_now_clock_drift : () => performance.now();
          var ae, we = [], De = {};
          function Ie() {
            if (!ae) {
              var x, P = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: T || "./this.program" };
              for (x in De) De[x] === void 0 ? delete P[x] : P[x] = De[x];
              var k = [];
              for (x in P) k.push(x + "=" + P[x]);
              ae = k;
            }
            return ae;
          }
          function q(x, P) {
            if (A) return J(20, 1, x, P);
            var k = 0;
            return Ie().forEach((function(N, z) {
              var G = P + k;
              for (z = c()[x + 4 * z >> 2 >>> 0] = G, G = 0; G < N.length; ++G) a()[z++ >> 0 >>> 0] = N.charCodeAt(G);
              a()[z >> 0 >>> 0] = 0, k += N.length + 1;
            })), 0;
          }
          function ge(x, P) {
            if (A) return J(21, 1, x, P);
            var k = Ie();
            c()[x >> 2 >>> 0] = k.length;
            var N = 0;
            return k.forEach((function(z) {
              N += z.length + 1;
            })), c()[P >> 2 >>> 0] = N, 0;
          }
          function xe(x) {
            return A ? J(22, 1, x) : 52;
          }
          function Ge(x, P, k, N) {
            return A ? J(23, 1, x, P, k, N) : 52;
          }
          function Ze(x, P, k, N, z) {
            return A ? J(24, 1, x, P, k, N, z) : 70;
          }
          var Dt = [null, [], []];
          function Nt(x, P) {
            var k = Dt[x];
            P === 0 || P === 10 ? ((x === 1 ? I : $)(We(k, 0)), k.length = 0) : k.push(P);
          }
          function Rt(x, P, k, N) {
            if (A) return J(25, 1, x, P, k, N);
            for (var z = 0, G = 0; G < k; G++) {
              var X = c()[P >> 2 >>> 0], ee = c()[P + 4 >> 2 >>> 0];
              P += 8;
              for (var pe = 0; pe < ee; pe++) Nt(x, f()[X + pe >>> 0]);
              z += ee;
            }
            return c()[N >> 2 >>> 0] = z, 0;
          }
          var Re = 0;
          function At(x) {
            return x % 4 == 0 && (x % 100 != 0 || x % 400 == 0);
          }
          var Bt = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], jt = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          function Vt(x, P, k, N) {
            function z(W, _e, Me) {
              for (W = typeof W == "number" ? W.toString() : W || ""; W.length < _e; ) W = Me[0] + W;
              return W;
            }
            function G(W, _e) {
              return z(W, _e, "0");
            }
            function X(W, _e) {
              function Me(ct) {
                return 0 > ct ? -1 : 0 < ct ? 1 : 0;
              }
              var et;
              return (et = Me(W.getFullYear() - _e.getFullYear())) === 0 && (et = Me(W.getMonth() - _e.getMonth())) === 0 && (et = Me(W.getDate() - _e.getDate())), et;
            }
            function ee(W) {
              switch (W.getDay()) {
                case 0:
                  return new Date(W.getFullYear() - 1, 11, 29);
                case 1:
                  return W;
                case 2:
                  return new Date(W.getFullYear(), 0, 3);
                case 3:
                  return new Date(W.getFullYear(), 0, 2);
                case 4:
                  return new Date(W.getFullYear(), 0, 1);
                case 5:
                  return new Date(W.getFullYear() - 1, 11, 31);
                case 6:
                  return new Date(W.getFullYear() - 1, 11, 30);
              }
            }
            function pe(W) {
              var _e = W.Wb;
              for (W = new Date(new Date(W.Xb + 1900, 0, 1).getTime()); 0 < _e; ) {
                var Me = W.getMonth(), et = (At(W.getFullYear()) ? Bt : jt)[Me];
                if (!(_e > et - W.getDate())) {
                  W.setDate(W.getDate() + _e);
                  break;
                }
                _e -= et - W.getDate() + 1, W.setDate(1), 11 > Me ? W.setMonth(Me + 1) : (W.setMonth(0), W.setFullYear(W.getFullYear() + 1));
              }
              return Me = new Date(W.getFullYear() + 1, 0, 4), _e = ee(new Date(W.getFullYear(), 0, 4)), Me = ee(Me), 0 >= X(_e, W) ? 0 >= X(Me, W) ? W.getFullYear() + 1 : W.getFullYear() : W.getFullYear() - 1;
            }
            var fe = g()[N + 40 >> 2 >>> 0];
            for (var ke in N = { Lc: g()[N >> 2 >>> 0], Kc: g()[N + 4 >> 2 >>> 0], dc: g()[N + 8 >> 2 >>> 0], jc: g()[N + 12 >> 2 >>> 0], ec: g()[N + 16 >> 2 >>> 0], Xb: g()[N + 20 >> 2 >>> 0], Tb: g()[N + 24 >> 2 >>> 0], Wb: g()[N + 28 >> 2 >>> 0], Rc: g()[N + 32 >> 2 >>> 0], Jc: g()[N + 36 >> 2 >>> 0], Mc: fe ? Oe(fe) : "" }, k = Oe(k), fe = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) k = k.replace(new RegExp(ke, "g"), fe[ke]);
            var Ke = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), qe = "January February March April May June July August September October November December".split(" ");
            for (ke in fe = { "%a": function(W) {
              return Ke[W.Tb].substring(0, 3);
            }, "%A": function(W) {
              return Ke[W.Tb];
            }, "%b": function(W) {
              return qe[W.ec].substring(0, 3);
            }, "%B": function(W) {
              return qe[W.ec];
            }, "%C": function(W) {
              return G((W.Xb + 1900) / 100 | 0, 2);
            }, "%d": function(W) {
              return G(W.jc, 2);
            }, "%e": function(W) {
              return z(W.jc, 2, " ");
            }, "%g": function(W) {
              return pe(W).toString().substring(2);
            }, "%G": function(W) {
              return pe(W);
            }, "%H": function(W) {
              return G(W.dc, 2);
            }, "%I": function(W) {
              return (W = W.dc) == 0 ? W = 12 : 12 < W && (W -= 12), G(W, 2);
            }, "%j": function(W) {
              for (var _e = 0, Me = 0; Me <= W.ec - 1; _e += (At(W.Xb + 1900) ? Bt : jt)[Me++]) ;
              return G(W.jc + _e, 3);
            }, "%m": function(W) {
              return G(W.ec + 1, 2);
            }, "%M": function(W) {
              return G(W.Kc, 2);
            }, "%n": function() {
              return `
`;
            }, "%p": function(W) {
              return 0 <= W.dc && 12 > W.dc ? "AM" : "PM";
            }, "%S": function(W) {
              return G(W.Lc, 2);
            }, "%t": function() {
              return "	";
            }, "%u": function(W) {
              return W.Tb || 7;
            }, "%U": function(W) {
              return G(Math.floor((W.Wb + 7 - W.Tb) / 7), 2);
            }, "%V": function(W) {
              var _e = Math.floor((W.Wb + 7 - (W.Tb + 6) % 7) / 7);
              if (2 >= (W.Tb + 371 - W.Wb - 2) % 7 && _e++, _e) _e == 53 && ((Me = (W.Tb + 371 - W.Wb) % 7) == 4 || Me == 3 && At(W.Xb) || (_e = 1));
              else {
                _e = 52;
                var Me = (W.Tb + 7 - W.Wb - 1) % 7;
                (Me == 4 || Me == 5 && At(W.Xb % 400 - 1)) && _e++;
              }
              return G(_e, 2);
            }, "%w": function(W) {
              return W.Tb;
            }, "%W": function(W) {
              return G(Math.floor((W.Wb + 7 - (W.Tb + 6) % 7) / 7), 2);
            }, "%y": function(W) {
              return (W.Xb + 1900).toString().substring(2);
            }, "%Y": function(W) {
              return W.Xb + 1900;
            }, "%z": function(W) {
              var _e = 0 <= (W = W.Jc);
              return W = Math.abs(W) / 60, (_e ? "+" : "-") + ("0000" + (W / 60 * 100 + W % 60)).slice(-4);
            }, "%Z": function(W) {
              return W.Mc;
            }, "%%": function() {
              return "%";
            } }, k = k.replace(/%%/g, "\0\0"), fe) k.includes(ke) && (k = k.replace(new RegExp(ke, "g"), fe[ke](N)));
            return ke = (function(W) {
              var _e = Array(Ce(W) + 1);
              return Ne(W, _e, 0, _e.length), _e;
            })(k = k.replace(/\0\0/g, "%")), ke.length > P ? 0 : ((function(W, _e) {
              a().set(W, _e >>> 0);
            })(ke, x), ke.length - 1);
          }
          re.fc();
          var cn = [null, Fe, Mt, ot, gt, mt, _t, bt, yt, wt, Tt, vt, xt, St, Et, M, C, U, H, Z, q, ge, xe, Ge, Ze, Rt], dn = { b: function(x) {
            return Ft(x + 24) + 24;
          }, n: function(x) {
            return (x = new oe(x)).uc() || (x.hc(!0), se--), x.ic(!1), it.push(x), x.sc(), x.vc();
          }, ma: function(x) {
            throw $("Unexpected exception thrown, this is not properly supported - aborting"), ye = !0, x;
          }, x: function() {
            de(0);
            var x = it.pop();
            if (x.Hc() && !x.kc()) {
              var P = x.Dc();
              P && be(P)(x.Zb), ht(x.Zb);
            }
            ie = 0;
          }, e: function() {
            var x = ie;
            if (!x) return Re = 0;
            var P = new oe(x);
            P.cc(x);
            var k = P.bc();
            if (!k) return Re = 0, x;
            for (var N = Array.prototype.slice.call(arguments), z = 0; z < N.length; z++) {
              var G = N[z];
              if (G === 0 || G === k) break;
              if (Ct(G, k, P.Sb + 16)) return Re = G, x;
            }
            return Re = k, x;
          }, l: function() {
            var x = ie;
            if (!x) return Re = 0;
            var P = new oe(x);
            P.cc(x);
            var k = P.bc();
            if (!k) return Re = 0, x;
            for (var N = Array.prototype.slice.call(arguments), z = 0; z < N.length; z++) {
              var G = N[z];
              if (G === 0 || G === k) break;
              if (Ct(G, k, P.Sb + 16)) return Re = G, x;
            }
            return Re = k, x;
          }, h: function() {
            var x = ie;
            if (!x) return Re = 0;
            var P = new oe(x);
            P.cc(x);
            var k = P.bc();
            if (!k) return Re = 0, x;
            for (var N = Array.prototype.slice.call(arguments), z = 0; z < N.length; z++) {
              var G = N[z];
              if (G === 0 || G === k) break;
              if (Ct(G, k, P.Sb + 16)) return Re = G, x;
            }
            return Re = k, x;
          }, t: ht, M: function() {
            var x = it.pop();
            x || he("no exception to throw");
            var P = x.Zb;
            throw x.kc() || (it.push(x), x.ic(!0), x.hc(!1), se++), ie = P, P;
          }, c: function(x, P, k) {
            throw new oe(x).fc(P, k), ie = x, se++, x;
          }, pa: function() {
            return se;
          }, Fa: function(x) {
            qt(x, !O, 1, !E), re.pc();
          }, T: function(x) {
            A ? postMessage({ cmd: "cleanupThread", thread: x }) : ut(x);
          }, xa: ft, j: function(x) {
            throw ie || (ie = x), x;
          }, H: gt, Ma: mt, ua: _t, wa: bt, oa: yt, Ka: wt, Ca: Tt, Ja: vt, V: xt, va: St, sa: Et, La: M, ta: C, Ta: function() {
          }, X: function() {
            he("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
          }, Ua: function() {
            he("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
          }, W: function() {
            return Date.now();
          }, ya: function() {
            return 2097152;
          }, Oa: function() {
            return !0;
          }, za: function(x, P, k, N) {
            if (x == P) setTimeout((() => R(N)));
            else if (A) postMessage({ targetThread: x, cmd: "processProxyingQueue", queue: N });
            else {
              if (!(x = re.Vb[x])) return;
              x.postMessage({ cmd: "processProxyingQueue", queue: N });
            }
            return 1;
          }, Ea: function() {
            return -1;
          }, Pa: function(x, P) {
            x = new Date(1e3 * V(x)), g()[P >> 2 >>> 0] = x.getUTCSeconds(), g()[P + 4 >> 2 >>> 0] = x.getUTCMinutes(), g()[P + 8 >> 2 >>> 0] = x.getUTCHours(), g()[P + 12 >> 2 >>> 0] = x.getUTCDate(), g()[P + 16 >> 2 >>> 0] = x.getUTCMonth(), g()[P + 20 >> 2 >>> 0] = x.getUTCFullYear() - 1900, g()[P + 24 >> 2 >>> 0] = x.getUTCDay(), x = (x.getTime() - Date.UTC(x.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, g()[P + 28 >> 2 >>> 0] = x;
          }, Qa: function(x, P) {
            x = new Date(1e3 * V(x)), g()[P >> 2 >>> 0] = x.getSeconds(), g()[P + 4 >> 2 >>> 0] = x.getMinutes(), g()[P + 8 >> 2 >>> 0] = x.getHours(), g()[P + 12 >> 2 >>> 0] = x.getDate(), g()[P + 16 >> 2 >>> 0] = x.getMonth(), g()[P + 20 >> 2 >>> 0] = x.getFullYear() - 1900, g()[P + 24 >> 2 >>> 0] = x.getDay();
            var k = new Date(x.getFullYear(), 0, 1), N = (x.getTime() - k.getTime()) / 864e5 | 0;
            g()[P + 28 >> 2 >>> 0] = N, g()[P + 36 >> 2 >>> 0] = -60 * x.getTimezoneOffset(), N = new Date(x.getFullYear(), 6, 1).getTimezoneOffset(), x = 0 | (N != (k = k.getTimezoneOffset()) && x.getTimezoneOffset() == Math.min(k, N)), g()[P + 32 >> 2 >>> 0] = x;
          }, Ra: function(x) {
            var P = new Date(g()[x + 20 >> 2 >>> 0] + 1900, g()[x + 16 >> 2 >>> 0], g()[x + 12 >> 2 >>> 0], g()[x + 8 >> 2 >>> 0], g()[x + 4 >> 2 >>> 0], g()[x >> 2 >>> 0], 0), k = g()[x + 32 >> 2 >>> 0], N = P.getTimezoneOffset(), z = new Date(P.getFullYear(), 0, 1), G = new Date(P.getFullYear(), 6, 1).getTimezoneOffset(), X = z.getTimezoneOffset(), ee = Math.min(X, G);
            return 0 > k ? g()[x + 32 >> 2 >>> 0] = +(G != X && ee == N) : 0 < k != (ee == N) && (G = Math.max(X, G), P.setTime(P.getTime() + 6e4 * ((0 < k ? ee : G) - N))), g()[x + 24 >> 2 >>> 0] = P.getDay(), k = (P.getTime() - z.getTime()) / 864e5 | 0, g()[x + 28 >> 2 >>> 0] = k, g()[x >> 2 >>> 0] = P.getSeconds(), g()[x + 4 >> 2 >>> 0] = P.getMinutes(), g()[x + 8 >> 2 >>> 0] = P.getHours(), g()[x + 12 >> 2 >>> 0] = P.getDate(), g()[x + 16 >> 2 >>> 0] = P.getMonth(), P.getTime() / 1e3 | 0;
          }, Aa: U, Ba: H, Sa: function x(P, k, N) {
            x.Ac || (x.Ac = !0, Z(P, k, N));
          }, y: function() {
            he("");
          }, U: function() {
            if (!v && !O) {
              var x = "Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";
              rt || (rt = {}), rt[x] || (rt[x] = 1, v && (x = "warning: " + x), $(x));
            }
          }, ra: function() {
            return 4294901760;
          }, B: pt, Ia: function(x, P, k) {
            f().copyWithin(x >>> 0, P >>> 0, P + k >>> 0);
          }, F: function() {
            return v ? o(3993).cpus().length : navigator.hardwareConcurrency;
          }, Da: function(x, P, k) {
            we.length = P, k >>= 3;
            for (var N = 0; N < P; N++) we[N] = s()[k + N >>> 0];
            return (0 > x ? Ot[-x - 1] : cn[x]).apply(null, we);
          }, qa: function(x) {
            var P = f().length;
            if ((x >>>= 0) <= P || 4294901760 < x) return !1;
            for (var k = 1; 4 >= k; k *= 2) {
              var N = P * (1 + 0.2 / k);
              N = Math.min(N, x + 100663296);
              var z = Math;
              N = Math.max(x, N), z = z.min.call(z, 4294901760, N + (65536 - N % 65536) % 65536);
              e: {
                try {
                  Y.grow(z - ne.byteLength + 65535 >>> 16), Pe(Y.buffer);
                  var G = 1;
                  break e;
                } catch {
                }
                G = void 0;
              }
              if (G) return !0;
            }
            return !1;
          }, Na: function() {
            throw "unwind";
          }, Ga: q, Ha: ge, J: nt, I: xe, S: Ge, ga: Ze, R: Rt, d: function() {
            return Re;
          }, na: function x(P, k) {
            x.lc || (x.lc = (function() {
              if (typeof crypto == "object" && typeof crypto.getRandomValues == "function") {
                var z = new Uint8Array(1);
                return () => (crypto.getRandomValues(z), z[0]);
              }
              if (v) try {
                var G = o(Object((function() {
                  var X = new Error("Cannot find module 'crypto'");
                  throw X.code = "MODULE_NOT_FOUND", X;
                })()));
                return () => G.randomBytes(1)[0];
              } catch {
              }
              return () => he("randomDevice");
            })());
            for (var N = 0; N < k; N++) a()[P + N >> 0 >>> 0] = x.lc();
            return 0;
          }, ia: function(x, P, k) {
            var N = le();
            try {
              return be(x)(P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, ja: function(x, P, k) {
            var N = le();
            try {
              return be(x)(P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, K: function(x) {
            var P = le();
            try {
              return be(x)();
            } catch (k) {
              if (ue(P), k !== k + 0) throw k;
              de(1, 0);
            }
          }, f: function(x, P) {
            var k = le();
            try {
              return be(x)(P);
            } catch (N) {
              if (ue(k), N !== N + 0) throw N;
              de(1, 0);
            }
          }, P: function(x, P, k) {
            var N = le();
            try {
              return be(x)(P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, Q: function(x, P, k) {
            var N = le();
            try {
              return be(x)(P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, k: function(x, P, k) {
            var N = le();
            try {
              return be(x)(P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, p: function(x, P, k, N) {
            var z = le();
            try {
              return be(x)(P, k, N);
            } catch (G) {
              if (ue(z), G !== G + 0) throw G;
              de(1, 0);
            }
          }, q: function(x, P, k, N, z) {
            var G = le();
            try {
              return be(x)(P, k, N, z);
            } catch (X) {
              if (ue(G), X !== X + 0) throw X;
              de(1, 0);
            }
          }, N: function(x, P, k, N, z, G) {
            var X = le();
            try {
              return be(x)(P, k, N, z, G);
            } catch (ee) {
              if (ue(X), ee !== ee + 0) throw ee;
              de(1, 0);
            }
          }, s: function(x, P, k, N, z, G) {
            var X = le();
            try {
              return be(x)(P, k, N, z, G);
            } catch (ee) {
              if (ue(X), ee !== ee + 0) throw ee;
              de(1, 0);
            }
          }, w: function(x, P, k, N, z, G, X) {
            var ee = le();
            try {
              return be(x)(P, k, N, z, G, X);
            } catch (pe) {
              if (ue(ee), pe !== pe + 0) throw pe;
              de(1, 0);
            }
          }, L: function(x, P, k, N, z, G, X, ee) {
            var pe = le();
            try {
              return be(x)(P, k, N, z, G, X, ee);
            } catch (fe) {
              if (ue(pe), fe !== fe + 0) throw fe;
              de(1, 0);
            }
          }, E: function(x, P, k, N, z, G, X, ee, pe, fe, ke, Ke) {
            var qe = le();
            try {
              return be(x)(P, k, N, z, G, X, ee, pe, fe, ke, Ke);
            } catch (W) {
              if (ue(qe), W !== W + 0) throw W;
              de(1, 0);
            }
          }, aa: function(x, P, k, N, z, G, X, ee) {
            var pe = le();
            try {
              return sn(x, P, k, N, z, G, X, ee);
            } catch (fe) {
              if (ue(pe), fe !== fe + 0) throw fe;
              de(1, 0);
            }
          }, _: function(x, P, k, N, z, G, X) {
            var ee = le();
            try {
              return Jt(x, P, k, N, z, G, X);
            } catch (pe) {
              if (ue(ee), pe !== pe + 0) throw pe;
              de(1, 0);
            }
          }, Z: function(x, P, k, N, z) {
            var G = le();
            try {
              return an(x, P, k, N, z);
            } catch (X) {
              if (ue(G), X !== X + 0) throw X;
              de(1, 0);
            }
          }, ca: function(x, P, k, N) {
            var z = le();
            try {
              return rn(x, P, k, N);
            } catch (G) {
              if (ue(z), G !== G + 0) throw G;
              de(1, 0);
            }
          }, $: function(x) {
            var P = le();
            try {
              return Qt(x);
            } catch (k) {
              if (ue(P), k !== k + 0) throw k;
              de(1, 0);
            }
          }, ba: function(x, P) {
            var k = le();
            try {
              return on(x, P);
            } catch (N) {
              if (ue(k), N !== N + 0) throw N;
              de(1, 0);
            }
          }, Y: function(x, P, k) {
            var N = le();
            try {
              return Zt(x, P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, g: function(x) {
            var P = le();
            try {
              be(x)();
            } catch (k) {
              if (ue(P), k !== k + 0) throw k;
              de(1, 0);
            }
          }, r: function(x, P) {
            var k = le();
            try {
              be(x)(P);
            } catch (N) {
              if (ue(k), N !== N + 0) throw N;
              de(1, 0);
            }
          }, i: function(x, P, k) {
            var N = le();
            try {
              be(x)(P, k);
            } catch (z) {
              if (ue(N), z !== z + 0) throw z;
              de(1, 0);
            }
          }, ha: function(x, P, k, N) {
            var z = le();
            try {
              be(x)(P, k, N);
            } catch (G) {
              if (ue(z), G !== G + 0) throw G;
              de(1, 0);
            }
          }, m: function(x, P, k, N) {
            var z = le();
            try {
              be(x)(P, k, N);
            } catch (G) {
              if (ue(z), G !== G + 0) throw G;
              de(1, 0);
            }
          }, v: function(x, P, k, N, z) {
            var G = le();
            try {
              be(x)(P, k, N, z);
            } catch (X) {
              if (ue(G), X !== X + 0) throw X;
              de(1, 0);
            }
          }, u: function(x, P, k, N, z, G) {
            var X = le();
            try {
              be(x)(P, k, N, z, G);
            } catch (ee) {
              if (ue(X), ee !== ee + 0) throw ee;
              de(1, 0);
            }
          }, O: function(x, P, k, N, z, G, X) {
            var ee = le();
            try {
              be(x)(P, k, N, z, G, X);
            } catch (pe) {
              if (ue(ee), pe !== pe + 0) throw pe;
              de(1, 0);
            }
          }, A: function(x, P, k, N, z, G, X, ee) {
            var pe = le();
            try {
              be(x)(P, k, N, z, G, X, ee);
            } catch (fe) {
              if (ue(pe), fe !== fe + 0) throw fe;
              de(1, 0);
            }
          }, ka: function(x, P, k, N, z, G, X, ee, pe) {
            var fe = le();
            try {
              be(x)(P, k, N, z, G, X, ee, pe);
            } catch (ke) {
              if (ue(fe), ke !== ke + 0) throw ke;
              de(1, 0);
            }
          }, C: function(x, P, k, N, z, G, X, ee, pe, fe, ke) {
            var Ke = le();
            try {
              be(x)(P, k, N, z, G, X, ee, pe, fe, ke);
            } catch (qe) {
              if (ue(Ke), qe !== qe + 0) throw qe;
              de(1, 0);
            }
          }, D: function(x, P, k, N, z, G, X, ee, pe, fe, ke, Ke, qe, W, _e, Me) {
            var et = le();
            try {
              be(x)(P, k, N, z, G, X, ee, pe, fe, ke, Ke, qe, W, _e, Me);
            } catch (ct) {
              if (ue(et), ct !== ct + 0) throw ct;
              de(1, 0);
            }
          }, fa: function(x, P, k, N, z, G, X, ee) {
            var pe = le();
            try {
              en(x, P, k, N, z, G, X, ee);
            } catch (fe) {
              if (ue(pe), fe !== fe + 0) throw fe;
              de(1, 0);
            }
          }, da: function(x, P, k, N, z, G, X, ee, pe, fe, ke, Ke) {
            var qe = le();
            try {
              nn(x, P, k, N, z, G, X, ee, pe, fe, ke, Ke);
            } catch (W) {
              if (ue(qe), W !== W + 0) throw W;
              de(1, 0);
            }
          }, ea: function(x, P, k, N, z, G) {
            var X = le();
            try {
              tn(x, P, k, N, z, G);
            } catch (ee) {
              if (ue(X), ee !== ee + 0) throw ee;
              de(1, 0);
            }
          }, o: function(x) {
            return x;
          }, a: Y || t.wasmMemory, G: function(x) {
            Re = x;
          }, la: Vt, z: function(x, P, k, N) {
            return Vt(x, P, k, N);
          } };
          (function() {
            function x(z, G) {
              t.asm = z.exports, re.qc.push(t.asm.sb), Be = t.asm.ub, ze.unshift(t.asm.Va), te = G, A || ($e--, t.monitorRunDependencies && t.monitorRunDependencies($e), $e == 0 && Ye && (z = Ye, Ye = null, z()));
            }
            function P(z) {
              x(z.instance, z.module);
            }
            function k(z) {
              return (function() {
                if (!D && (E || O)) {
                  if (typeof fetch == "function" && !Se.startsWith("file://")) return fetch(Se, { credentials: "same-origin" }).then((function(G) {
                    if (!G.ok) throw "failed to load wasm binary file at '" + Se + "'";
                    return G.arrayBuffer();
                  })).catch((function() {
                    return at();
                  }));
                  if (p) return new Promise((function(G, X) {
                    p(Se, (function(ee) {
                      G(new Uint8Array(ee));
                    }), X);
                  }));
                }
                return Promise.resolve().then((function() {
                  return at();
                }));
              })().then((function(G) {
                return WebAssembly.instantiate(G, N);
              })).then((function(G) {
                return G;
              })).then(z, (function(G) {
                $("failed to asynchronously prepare wasm: " + G), he(G);
              }));
            }
            var N = { a: dn };
            if (A || ($e++, t.monitorRunDependencies && t.monitorRunDependencies($e)), t.instantiateWasm) try {
              return t.instantiateWasm(N, x);
            } catch (z) {
              return $("Module.instantiateWasm callback failed with error: " + z), !1;
            }
            (D || typeof WebAssembly.instantiateStreaming != "function" || dt() || Se.startsWith("file://") || v || typeof fetch != "function" ? k(P) : fetch(Se, { credentials: "same-origin" }).then((function(z) {
              return WebAssembly.instantiateStreaming(z, N).then(P, (function(G) {
                return $("wasm streaming compile failed: " + G), $("falling back to ArrayBuffer instantiation"), k(P);
              }));
            }))).catch(r);
          })(), t.___wasm_call_ctors = function() {
            return (t.___wasm_call_ctors = t.asm.Va).apply(null, arguments);
          }, t._OrtInit = function() {
            return (t._OrtInit = t.asm.Wa).apply(null, arguments);
          }, t._OrtCreateSessionOptions = function() {
            return (t._OrtCreateSessionOptions = t.asm.Xa).apply(null, arguments);
          }, t._OrtAppendExecutionProvider = function() {
            return (t._OrtAppendExecutionProvider = t.asm.Ya).apply(null, arguments);
          }, t._OrtAddSessionConfigEntry = function() {
            return (t._OrtAddSessionConfigEntry = t.asm.Za).apply(null, arguments);
          }, t._OrtReleaseSessionOptions = function() {
            return (t._OrtReleaseSessionOptions = t.asm._a).apply(null, arguments);
          }, t._OrtCreateSession = function() {
            return (t._OrtCreateSession = t.asm.$a).apply(null, arguments);
          }, t._OrtReleaseSession = function() {
            return (t._OrtReleaseSession = t.asm.ab).apply(null, arguments);
          }, t._OrtGetInputCount = function() {
            return (t._OrtGetInputCount = t.asm.bb).apply(null, arguments);
          }, t._OrtGetOutputCount = function() {
            return (t._OrtGetOutputCount = t.asm.cb).apply(null, arguments);
          }, t._OrtGetInputName = function() {
            return (t._OrtGetInputName = t.asm.db).apply(null, arguments);
          }, t._OrtGetOutputName = function() {
            return (t._OrtGetOutputName = t.asm.eb).apply(null, arguments);
          }, t._OrtFree = function() {
            return (t._OrtFree = t.asm.fb).apply(null, arguments);
          }, t._OrtCreateTensor = function() {
            return (t._OrtCreateTensor = t.asm.gb).apply(null, arguments);
          }, t._OrtGetTensorData = function() {
            return (t._OrtGetTensorData = t.asm.hb).apply(null, arguments);
          }, t._OrtReleaseTensor = function() {
            return (t._OrtReleaseTensor = t.asm.ib).apply(null, arguments);
          }, t._OrtCreateRunOptions = function() {
            return (t._OrtCreateRunOptions = t.asm.jb).apply(null, arguments);
          }, t._OrtAddRunConfigEntry = function() {
            return (t._OrtAddRunConfigEntry = t.asm.kb).apply(null, arguments);
          }, t._OrtReleaseRunOptions = function() {
            return (t._OrtReleaseRunOptions = t.asm.lb).apply(null, arguments);
          }, t._OrtRun = function() {
            return (t._OrtRun = t.asm.mb).apply(null, arguments);
          }, t._OrtEndProfiling = function() {
            return (t._OrtEndProfiling = t.asm.nb).apply(null, arguments);
          };
          var kt = t._pthread_self = function() {
            return (kt = t._pthread_self = t.asm.ob).apply(null, arguments);
          }, Ft = t._malloc = function() {
            return (Ft = t._malloc = t.asm.pb).apply(null, arguments);
          }, zt = t._free = function() {
            return (zt = t._free = t.asm.qb).apply(null, arguments);
          }, Ut = t._fflush = function() {
            return (Ut = t._fflush = t.asm.rb).apply(null, arguments);
          };
          t.__emscripten_tls_init = function() {
            return (t.__emscripten_tls_init = t.asm.sb).apply(null, arguments);
          };
          var Gt = t.___funcs_on_exit = function() {
            return (Gt = t.___funcs_on_exit = t.asm.tb).apply(null, arguments);
          }, qt = t.__emscripten_thread_init = function() {
            return (qt = t.__emscripten_thread_init = t.asm.vb).apply(null, arguments);
          };
          t.__emscripten_thread_crashed = function() {
            return (t.__emscripten_thread_crashed = t.asm.wb).apply(null, arguments);
          };
          var It, Wt = t._emscripten_run_in_main_runtime_thread_js = function() {
            return (Wt = t._emscripten_run_in_main_runtime_thread_js = t.asm.xb).apply(null, arguments);
          }, Ht = t.__emscripten_proxy_execute_task_queue = function() {
            return (Ht = t.__emscripten_proxy_execute_task_queue = t.asm.yb).apply(null, arguments);
          }, Lt = t.__emscripten_thread_free_data = function() {
            return (Lt = t.__emscripten_thread_free_data = t.asm.zb).apply(null, arguments);
          }, Yt = t.__emscripten_thread_exit = function() {
            return (Yt = t.__emscripten_thread_exit = t.asm.Ab).apply(null, arguments);
          }, de = t._setThrew = function() {
            return (de = t._setThrew = t.asm.Bb).apply(null, arguments);
          }, Kt = t._emscripten_stack_set_limits = function() {
            return (Kt = t._emscripten_stack_set_limits = t.asm.Cb).apply(null, arguments);
          }, le = t.stackSave = function() {
            return (le = t.stackSave = t.asm.Db).apply(null, arguments);
          }, ue = t.stackRestore = function() {
            return (ue = t.stackRestore = t.asm.Eb).apply(null, arguments);
          }, $t = t.stackAlloc = function() {
            return ($t = t.stackAlloc = t.asm.Fb).apply(null, arguments);
          }, Ct = t.___cxa_can_catch = function() {
            return (Ct = t.___cxa_can_catch = t.asm.Gb).apply(null, arguments);
          }, Xt = t.___cxa_is_pointer_type = function() {
            return (Xt = t.___cxa_is_pointer_type = t.asm.Hb).apply(null, arguments);
          }, Qt = t.dynCall_j = function() {
            return (Qt = t.dynCall_j = t.asm.Ib).apply(null, arguments);
          }, Jt = t.dynCall_iiiiij = function() {
            return (Jt = t.dynCall_iiiiij = t.asm.Jb).apply(null, arguments);
          }, Zt = t.dynCall_jii = function() {
            return (Zt = t.dynCall_jii = t.asm.Kb).apply(null, arguments);
          }, en = t.dynCall_viiiiij = function() {
            return (en = t.dynCall_viiiiij = t.asm.Lb).apply(null, arguments);
          }, tn = t.dynCall_vjji = function() {
            return (tn = t.dynCall_vjji = t.asm.Mb).apply(null, arguments);
          }, nn = t.dynCall_viiijjjii = function() {
            return (nn = t.dynCall_viiijjjii = t.asm.Nb).apply(null, arguments);
          }, rn = t.dynCall_iij = function() {
            return (rn = t.dynCall_iij = t.asm.Ob).apply(null, arguments);
          }, on = t.dynCall_ji = function() {
            return (on = t.dynCall_ji = t.asm.Pb).apply(null, arguments);
          }, sn = t.dynCall_iiiiiij = function() {
            return (sn = t.dynCall_iiiiiij = t.asm.Qb).apply(null, arguments);
          }, an = t.dynCall_iiij = function() {
            return (an = t.dynCall_iiij = t.asm.Rb).apply(null, arguments);
          };
          function un() {
            function x() {
              if (!It && (It = !0, t.calledRun = !0, !ye) && (A || tt(ze), e(t), t.onRuntimeInitialized && t.onRuntimeInitialized(), !A)) {
                if (t.postRun) for (typeof t.postRun == "function" && (t.postRun = [t.postRun]); t.postRun.length; ) {
                  var P = t.postRun.shift();
                  Xe.unshift(P);
                }
                tt(Xe);
              }
            }
            if (!(0 < $e)) if (A) e(t), A || tt(ze), postMessage({ cmd: "loaded" });
            else {
              if (t.preRun) for (typeof t.preRun == "function" && (t.preRun = [t.preRun]); t.preRun.length; ) je();
              tt(Ve), 0 < $e || (t.setStatus ? (t.setStatus("Running..."), setTimeout((function() {
                setTimeout((function() {
                  t.setStatus("");
                }), 1), x();
              }), 1)) : x());
            }
          }
          if (t.UTF8ToString = Oe, t.stringToUTF8 = function(x, P, k) {
            return Ne(x, f(), P, k);
          }, t.lengthBytesUTF8 = Ce, t.keepRuntimeAlive = Ue, t.wasmMemory = Y, t.stackSave = le, t.stackRestore = ue, t.stackAlloc = $t, t.ExitStatus = Qe, t.PThread = re, Ye = function x() {
            It || un(), It || (Ye = x);
          }, t.preInit) for (typeof t.preInit == "function" && (t.preInit = [t.preInit]); 0 < t.preInit.length; ) t.preInit.pop()();
          return un(), h.ready;
        });
        d.exports = l;
      }, 932: (d, n, o) => {
        var u, l = (u = (u = typeof document < "u" && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(h) {
          var a, f, g;
          h = h || {}, a || (a = h !== void 0 ? h : {}), a.ready = new Promise((function(M, C) {
            f = M, g = C;
          }));
          var c, s, t, e, r, i, p = Object.assign({}, a), m = "./this.program", _ = (M, C) => {
            throw C;
          }, b = typeof window == "object", y = typeof importScripts == "function", w = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", T = "";
          w ? (T = y ? o(908).dirname(T) + "/" : "//", i = () => {
            r || (e = o(1384), r = o(908));
          }, c = function(M, C) {
            return i(), M = r.normalize(M), e.readFileSync(M, C ? void 0 : "utf8");
          }, t = (M) => ((M = c(M, !0)).buffer || (M = new Uint8Array(M)), M), s = (M, C, R) => {
            i(), M = r.normalize(M), e.readFile(M, (function(V, U) {
              V ? R(V) : C(U.buffer);
            }));
          }, 1 < process.argv.length && (m = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", (function(M) {
            if (!(M instanceof ze)) throw M;
          })), process.on("unhandledRejection", (function(M) {
            throw M;
          })), _ = (M, C) => {
            if (v || 0 < Le) throw process.exitCode = M, C;
            C instanceof ze || O("exiting due to exception: " + C), process.exit(M);
          }, a.inspect = function() {
            return "[Emscripten Module object]";
          }) : (b || y) && (y ? T = self.location.href : typeof document < "u" && document.currentScript && (T = document.currentScript.src), u && (T = u), T = T.indexOf("blob:") !== 0 ? T.substr(0, T.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", c = (M) => {
            var C = new XMLHttpRequest();
            return C.open("GET", M, !1), C.send(null), C.responseText;
          }, y && (t = (M) => {
            var C = new XMLHttpRequest();
            return C.open("GET", M, !1), C.responseType = "arraybuffer", C.send(null), new Uint8Array(C.response);
          }), s = (M, C, R) => {
            var V = new XMLHttpRequest();
            V.open("GET", M, !0), V.responseType = "arraybuffer", V.onload = () => {
              V.status == 200 || V.status == 0 && V.response ? C(V.response) : R();
            }, V.onerror = R, V.send(null);
          });
          var S, E = a.print || console.log.bind(console), O = a.printErr || console.warn.bind(console);
          Object.assign(a, p), p = null, a.thisProgram && (m = a.thisProgram), a.quit && (_ = a.quit), a.wasmBinary && (S = a.wasmBinary);
          var v = a.noExitRuntime || !1;
          typeof WebAssembly != "object" && Pe("no native wasm support detected");
          var A, L, j, B, F, D, I = !1, $ = typeof TextDecoder < "u" ? new TextDecoder("utf8") : void 0;
          function Q(M, C, R) {
            var V = (C >>>= 0) + R;
            for (R = C; M[R] && !(R >= V); ) ++R;
            if (16 < R - C && M.buffer && $) return $.decode(M.subarray(C, R));
            for (V = ""; C < R; ) {
              var U = M[C++];
              if (128 & U) {
                var H = 63 & M[C++];
                if ((224 & U) == 192) V += String.fromCharCode((31 & U) << 6 | H);
                else {
                  var K = 63 & M[C++];
                  65536 > (U = (240 & U) == 224 ? (15 & U) << 12 | H << 6 | K : (7 & U) << 18 | H << 12 | K << 6 | 63 & M[C++]) ? V += String.fromCharCode(U) : (U -= 65536, V += String.fromCharCode(55296 | U >> 10, 56320 | 1023 & U));
                }
              } else V += String.fromCharCode(U);
            }
            return V;
          }
          function Y(M, C) {
            return (M >>>= 0) ? Q(B, M, C) : "";
          }
          function te(M, C, R, V) {
            if (!(0 < V)) return 0;
            var U = R >>>= 0;
            V = R + V - 1;
            for (var H = 0; H < M.length; ++H) {
              var K = M.charCodeAt(H);
              if (55296 <= K && 57343 >= K && (K = 65536 + ((1023 & K) << 10) | 1023 & M.charCodeAt(++H)), 127 >= K) {
                if (R >= V) break;
                C[R++ >>> 0] = K;
              } else {
                if (2047 >= K) {
                  if (R + 1 >= V) break;
                  C[R++ >>> 0] = 192 | K >> 6;
                } else {
                  if (65535 >= K) {
                    if (R + 2 >= V) break;
                    C[R++ >>> 0] = 224 | K >> 12;
                  } else {
                    if (R + 3 >= V) break;
                    C[R++ >>> 0] = 240 | K >> 18, C[R++ >>> 0] = 128 | K >> 12 & 63;
                  }
                  C[R++ >>> 0] = 128 | K >> 6 & 63;
                }
                C[R++ >>> 0] = 128 | 63 & K;
              }
            }
            return C[R >>> 0] = 0, R - U;
          }
          function ne(M) {
            for (var C = 0, R = 0; R < M.length; ++R) {
              var V = M.charCodeAt(R);
              127 >= V ? C++ : 2047 >= V ? C += 2 : 55296 <= V && 57343 >= V ? (C += 4, ++R) : C += 3;
            }
            return C;
          }
          function me() {
            var M = A.buffer;
            L = M, a.HEAP8 = j = new Int8Array(M), a.HEAP16 = new Int16Array(M), a.HEAP32 = F = new Int32Array(M), a.HEAPU8 = B = new Uint8Array(M), a.HEAPU16 = new Uint16Array(M), a.HEAPU32 = D = new Uint32Array(M), a.HEAPF32 = new Float32Array(M), a.HEAPF64 = new Float64Array(M);
          }
          var Ae, Ee = [], ce = [], ve = [], ye = [], Le = 0;
          function We() {
            var M = a.preRun.shift();
            Ee.unshift(M);
          }
          var Oe, Ne = 0, Ce = null;
          function Pe(M) {
            throw a.onAbort && a.onAbort(M), O(M = "Aborted(" + M + ")"), I = !0, M = new WebAssembly.RuntimeError(M + ". Build with -sASSERTIONS for more info."), g(M), M;
          }
          function Te() {
            return Oe.startsWith("data:application/octet-stream;base64,");
          }
          if (Oe = "ort-wasm.wasm", !Te()) {
            var Be = Oe;
            Oe = a.locateFile ? a.locateFile(Be, T) : T + Be;
          }
          function Ve() {
            var M = Oe;
            try {
              if (M == Oe && S) return new Uint8Array(S);
              if (t) return t(M);
              throw "both async and sync fetching of the wasm failed";
            } catch (C) {
              Pe(C);
            }
          }
          function ze(M) {
            this.name = "ExitStatus", this.message = "Program terminated with exit(" + M + ")", this.status = M;
          }
          function He(M) {
            for (; 0 < M.length; ) M.shift()(a);
          }
          var Xe = [], Ue = 0, je = 0;
          function Se(M) {
            this.Db = M, this.zb = M - 24, this.Ub = function(C) {
              D[this.zb + 4 >> 2 >>> 0] = C;
            }, this.Eb = function() {
              return D[this.zb + 4 >> 2 >>> 0];
            }, this.Sb = function(C) {
              D[this.zb + 8 >> 2 >>> 0] = C;
            }, this.Wb = function() {
              return D[this.zb + 8 >> 2 >>> 0];
            }, this.Tb = function() {
              F[this.zb >> 2 >>> 0] = 0;
            }, this.Ib = function(C) {
              j[this.zb + 12 >> 0 >>> 0] = C ? 1 : 0;
            }, this.Pb = function() {
              return j[this.zb + 12 >> 0 >>> 0] != 0;
            }, this.Jb = function(C) {
              j[this.zb + 13 >> 0 >>> 0] = C ? 1 : 0;
            }, this.Lb = function() {
              return j[this.zb + 13 >> 0 >>> 0] != 0;
            }, this.Rb = function(C, R) {
              this.Fb(0), this.Ub(C), this.Sb(R), this.Tb(), this.Ib(!1), this.Jb(!1);
            }, this.Nb = function() {
              F[this.zb >> 2 >>> 0] += 1;
            }, this.Xb = function() {
              var C = F[this.zb >> 2 >>> 0];
              return F[this.zb >> 2 >>> 0] = C - 1, C === 1;
            }, this.Fb = function(C) {
              D[this.zb + 16 >> 2 >>> 0] = C;
            }, this.Ob = function() {
              return D[this.zb + 16 >> 2 >>> 0];
            }, this.Qb = function() {
              if (ft(this.Eb())) return D[this.Db >> 2 >>> 0];
              var C = this.Ob();
              return C !== 0 ? C : this.Db;
            };
          }
          function $e(M) {
            return rt(new Se(M).zb);
          }
          var Ye = [];
          function he(M) {
            var C = Ye[M];
            return C || (M >= Ye.length && (Ye.length = M + 1), Ye[M] = C = Ae.get(M)), C;
          }
          function dt(M) {
            var C = ne(M) + 1, R = be(C);
            return R && te(M, j, R, C), R;
          }
          var at = {};
          function Ot() {
            if (!Qe) {
              var M, C = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: m || "./this.program" };
              for (M in at) at[M] === void 0 ? delete C[M] : C[M] = at[M];
              var R = [];
              for (M in C) R.push(M + "=" + C[M]);
              Qe = R;
            }
            return Qe;
          }
          var Qe, ut = [null, [], []];
          function lt(M, C) {
            var R = ut[M];
            C === 0 || C === 10 ? ((M === 1 ? E : O)(Q(R, 0)), R.length = 0) : R.push(C);
          }
          var Fe = 0;
          function nt(M) {
            return M % 4 == 0 && (M % 100 != 0 || M % 400 == 0);
          }
          var re = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], tt = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          function Pt(M, C, R, V) {
            function U(q, ge, xe) {
              for (q = typeof q == "number" ? q.toString() : q || ""; q.length < ge; ) q = xe[0] + q;
              return q;
            }
            function H(q, ge) {
              return U(q, ge, "0");
            }
            function K(q, ge) {
              function xe(Ze) {
                return 0 > Ze ? -1 : 0 < Ze ? 1 : 0;
              }
              var Ge;
              return (Ge = xe(q.getFullYear() - ge.getFullYear())) === 0 && (Ge = xe(q.getMonth() - ge.getMonth())) === 0 && (Ge = xe(q.getDate() - ge.getDate())), Ge;
            }
            function Z(q) {
              switch (q.getDay()) {
                case 0:
                  return new Date(q.getFullYear() - 1, 11, 29);
                case 1:
                  return q;
                case 2:
                  return new Date(q.getFullYear(), 0, 3);
                case 3:
                  return new Date(q.getFullYear(), 0, 2);
                case 4:
                  return new Date(q.getFullYear(), 0, 1);
                case 5:
                  return new Date(q.getFullYear() - 1, 11, 31);
                case 6:
                  return new Date(q.getFullYear() - 1, 11, 30);
              }
            }
            function J(q) {
              var ge = q.Bb;
              for (q = new Date(new Date(q.Cb + 1900, 0, 1).getTime()); 0 < ge; ) {
                var xe = q.getMonth(), Ge = (nt(q.getFullYear()) ? re : tt)[xe];
                if (!(ge > Ge - q.getDate())) {
                  q.setDate(q.getDate() + ge);
                  break;
                }
                ge -= Ge - q.getDate() + 1, q.setDate(1), 11 > xe ? q.setMonth(xe + 1) : (q.setMonth(0), q.setFullYear(q.getFullYear() + 1));
              }
              return xe = new Date(q.getFullYear() + 1, 0, 4), ge = Z(new Date(q.getFullYear(), 0, 4)), xe = Z(xe), 0 >= K(ge, q) ? 0 >= K(xe, q) ? q.getFullYear() + 1 : q.getFullYear() : q.getFullYear() - 1;
            }
            var ae = F[V + 40 >> 2 >>> 0];
            for (var we in V = { $b: F[V >> 2 >>> 0], Zb: F[V + 4 >> 2 >>> 0], Gb: F[V + 8 >> 2 >>> 0], Kb: F[V + 12 >> 2 >>> 0], Hb: F[V + 16 >> 2 >>> 0], Cb: F[V + 20 >> 2 >>> 0], Ab: F[V + 24 >> 2 >>> 0], Bb: F[V + 28 >> 2 >>> 0], bc: F[V + 32 >> 2 >>> 0], Yb: F[V + 36 >> 2 >>> 0], ac: ae ? Y(ae) : "" }, R = Y(R), ae = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) R = R.replace(new RegExp(we, "g"), ae[we]);
            var De = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), Ie = "January February March April May June July August September October November December".split(" ");
            for (we in ae = { "%a": function(q) {
              return De[q.Ab].substring(0, 3);
            }, "%A": function(q) {
              return De[q.Ab];
            }, "%b": function(q) {
              return Ie[q.Hb].substring(0, 3);
            }, "%B": function(q) {
              return Ie[q.Hb];
            }, "%C": function(q) {
              return H((q.Cb + 1900) / 100 | 0, 2);
            }, "%d": function(q) {
              return H(q.Kb, 2);
            }, "%e": function(q) {
              return U(q.Kb, 2, " ");
            }, "%g": function(q) {
              return J(q).toString().substring(2);
            }, "%G": function(q) {
              return J(q);
            }, "%H": function(q) {
              return H(q.Gb, 2);
            }, "%I": function(q) {
              return (q = q.Gb) == 0 ? q = 12 : 12 < q && (q -= 12), H(q, 2);
            }, "%j": function(q) {
              for (var ge = 0, xe = 0; xe <= q.Hb - 1; ge += (nt(q.Cb + 1900) ? re : tt)[xe++]) ;
              return H(q.Kb + ge, 3);
            }, "%m": function(q) {
              return H(q.Hb + 1, 2);
            }, "%M": function(q) {
              return H(q.Zb, 2);
            }, "%n": function() {
              return `
`;
            }, "%p": function(q) {
              return 0 <= q.Gb && 12 > q.Gb ? "AM" : "PM";
            }, "%S": function(q) {
              return H(q.$b, 2);
            }, "%t": function() {
              return "	";
            }, "%u": function(q) {
              return q.Ab || 7;
            }, "%U": function(q) {
              return H(Math.floor((q.Bb + 7 - q.Ab) / 7), 2);
            }, "%V": function(q) {
              var ge = Math.floor((q.Bb + 7 - (q.Ab + 6) % 7) / 7);
              if (2 >= (q.Ab + 371 - q.Bb - 2) % 7 && ge++, ge) ge == 53 && ((xe = (q.Ab + 371 - q.Bb) % 7) == 4 || xe == 3 && nt(q.Cb) || (ge = 1));
              else {
                ge = 52;
                var xe = (q.Ab + 7 - q.Bb - 1) % 7;
                (xe == 4 || xe == 5 && nt(q.Cb % 400 - 1)) && ge++;
              }
              return H(ge, 2);
            }, "%w": function(q) {
              return q.Ab;
            }, "%W": function(q) {
              return H(Math.floor((q.Bb + 7 - (q.Ab + 6) % 7) / 7), 2);
            }, "%y": function(q) {
              return (q.Cb + 1900).toString().substring(2);
            }, "%Y": function(q) {
              return q.Cb + 1900;
            }, "%z": function(q) {
              var ge = 0 <= (q = q.Yb);
              return q = Math.abs(q) / 60, (ge ? "+" : "-") + ("0000" + (q / 60 * 100 + q % 60)).slice(-4);
            }, "%Z": function(q) {
              return q.ac;
            }, "%%": function() {
              return "%";
            } }, R = R.replace(/%%/g, "\0\0"), ae) R.includes(we) && (R = R.replace(new RegExp(we, "g"), ae[we](V)));
            return we = (function(q) {
              var ge = Array(ne(q) + 1);
              return te(q, ge, 0, ge.length), ge;
            })(R = R.replace(/\0\0/g, "%")), we.length > C ? 0 : (j.set(we, M >>> 0), we.length - 1);
          }
          var Mt = { a: function(M) {
            return be(M + 24) + 24;
          }, m: function(M) {
            return (M = new Se(M)).Pb() || (M.Ib(!0), Ue--), M.Jb(!1), Xe.push(M), M.Nb(), M.Qb();
          }, ia: function(M) {
            throw O("Unexpected exception thrown, this is not properly supported - aborting"), I = !0, M;
          }, w: function() {
            se(0);
            var M = Xe.pop();
            if (M.Xb() && !M.Lb()) {
              var C = M.Wb();
              C && he(C)(M.Db), $e(M.Db);
            }
            je = 0;
          }, d: function() {
            var M = je;
            if (!M) return Fe = 0;
            var C = new Se(M);
            C.Fb(M);
            var R = C.Eb();
            if (!R) return Fe = 0, M;
            for (var V = Array.prototype.slice.call(arguments), U = 0; U < V.length; U++) {
              var H = V[U];
              if (H === 0 || H === R) break;
              if (ot(H, R, C.zb + 16)) return Fe = H, M;
            }
            return Fe = R, M;
          }, k: function() {
            var M = je;
            if (!M) return Fe = 0;
            var C = new Se(M);
            C.Fb(M);
            var R = C.Eb();
            if (!R) return Fe = 0, M;
            for (var V = Array.prototype.slice.call(arguments), U = 0; U < V.length; U++) {
              var H = V[U];
              if (H === 0 || H === R) break;
              if (ot(H, R, C.zb + 16)) return Fe = H, M;
            }
            return Fe = R, M;
          }, g: function() {
            var M = je;
            if (!M) return Fe = 0;
            var C = new Se(M);
            C.Fb(M);
            var R = C.Eb();
            if (!R) return Fe = 0, M;
            for (var V = Array.prototype.slice.call(arguments), U = 0; U < V.length; U++) {
              var H = V[U];
              if (H === 0 || H === R) break;
              if (ot(H, R, C.zb + 16)) return Fe = H, M;
            }
            return Fe = R, M;
          }, s: $e, L: function() {
            var M = Xe.pop();
            M || Pe("no exception to throw");
            var C = M.Db;
            throw M.Lb() || (Xe.push(M), M.Jb(!0), M.Ib(!1), Ue++), je = C, C;
          }, b: function(M, C, R) {
            throw new Se(M).Rb(C, R), je = M, Ue++, M;
          }, la: function() {
            return Ue;
          }, i: function(M) {
            throw je || (je = M), M;
          }, H: function() {
            return 0;
          }, Ba: function() {
          }, pa: function() {
          }, ra: function() {
          }, ka: function() {
            return 0;
          }, za: function() {
          }, ua: function() {
          }, ya: function() {
          }, R: function() {
          }, qa: function() {
          }, na: function() {
          }, Aa: function() {
          }, oa: function() {
          }, Ha: function() {
          }, Ja: function() {
            Pe("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
          }, Ia: function() {
            Pe("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
          }, S: function() {
            return Date.now();
          }, Ca: function() {
            return !0;
          }, Da: function(M, C) {
            M = new Date(1e3 * (D[M >>> 2] + 4294967296 * F[M + 4 >>> 2])), F[C >> 2 >>> 0] = M.getUTCSeconds(), F[C + 4 >> 2 >>> 0] = M.getUTCMinutes(), F[C + 8 >> 2 >>> 0] = M.getUTCHours(), F[C + 12 >> 2 >>> 0] = M.getUTCDate(), F[C + 16 >> 2 >>> 0] = M.getUTCMonth(), F[C + 20 >> 2 >>> 0] = M.getUTCFullYear() - 1900, F[C + 24 >> 2 >>> 0] = M.getUTCDay(), F[C + 28 >> 2 >>> 0] = (M.getTime() - Date.UTC(M.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;
          }, Ea: function(M, C) {
            M = new Date(1e3 * (D[M >>> 2] + 4294967296 * F[M + 4 >>> 2])), F[C >> 2 >>> 0] = M.getSeconds(), F[C + 4 >> 2 >>> 0] = M.getMinutes(), F[C + 8 >> 2 >>> 0] = M.getHours(), F[C + 12 >> 2 >>> 0] = M.getDate(), F[C + 16 >> 2 >>> 0] = M.getMonth(), F[C + 20 >> 2 >>> 0] = M.getFullYear() - 1900, F[C + 24 >> 2 >>> 0] = M.getDay();
            var R = new Date(M.getFullYear(), 0, 1);
            F[C + 28 >> 2 >>> 0] = (M.getTime() - R.getTime()) / 864e5 | 0, F[C + 36 >> 2 >>> 0] = -60 * M.getTimezoneOffset();
            var V = new Date(M.getFullYear(), 6, 1).getTimezoneOffset();
            R = R.getTimezoneOffset(), F[C + 32 >> 2 >>> 0] = 0 | (V != R && M.getTimezoneOffset() == Math.min(R, V));
          }, Fa: function(M) {
            var C = new Date(F[M + 20 >> 2 >>> 0] + 1900, F[M + 16 >> 2 >>> 0], F[M + 12 >> 2 >>> 0], F[M + 8 >> 2 >>> 0], F[M + 4 >> 2 >>> 0], F[M >> 2 >>> 0], 0), R = F[M + 32 >> 2 >>> 0], V = C.getTimezoneOffset(), U = new Date(C.getFullYear(), 0, 1), H = new Date(C.getFullYear(), 6, 1).getTimezoneOffset(), K = U.getTimezoneOffset(), Z = Math.min(K, H);
            return 0 > R ? F[M + 32 >> 2 >>> 0] = +(H != K && Z == V) : 0 < R != (Z == V) && (H = Math.max(K, H), C.setTime(C.getTime() + 6e4 * ((0 < R ? Z : H) - V))), F[M + 24 >> 2 >>> 0] = C.getDay(), F[M + 28 >> 2 >>> 0] = (C.getTime() - U.getTime()) / 864e5 | 0, F[M >> 2 >>> 0] = C.getSeconds(), F[M + 4 >> 2 >>> 0] = C.getMinutes(), F[M + 8 >> 2 >>> 0] = C.getHours(), F[M + 12 >> 2 >>> 0] = C.getDate(), F[M + 16 >> 2 >>> 0] = C.getMonth(), C.getTime() / 1e3 | 0;
          }, sa: function() {
            return -52;
          }, ta: function() {
          }, Ga: function M(C, R, V) {
            M.Vb || (M.Vb = !0, (function(U, H, K) {
              function Z(Ie) {
                return (Ie = Ie.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? Ie[1] : "GMT";
              }
              var J = (/* @__PURE__ */ new Date()).getFullYear(), ae = new Date(J, 0, 1), we = new Date(J, 6, 1);
              J = ae.getTimezoneOffset();
              var De = we.getTimezoneOffset();
              F[U >> 2 >>> 0] = 60 * Math.max(J, De), F[H >> 2 >>> 0] = +(J != De), U = Z(ae), H = Z(we), U = dt(U), H = dt(H), De < J ? (D[K >> 2 >>> 0] = U, D[K + 4 >> 2 >>> 0] = H) : (D[K >> 2 >>> 0] = H, D[K + 4 >> 2 >>> 0] = U);
            })(C, R, V));
          }, B: function() {
            Pe("");
          }, ma: function() {
            return 4294901760;
          }, I: w ? () => {
            var M = process.hrtime();
            return 1e3 * M[0] + M[1] / 1e6;
          } : () => performance.now(), xa: function(M, C, R) {
            B.copyWithin(M >>> 0, C >>> 0, C + R >>> 0);
          }, G: function(M) {
            var C = B.length;
            if (4294901760 < (M >>>= 0)) return !1;
            for (var R = 1; 4 >= R; R *= 2) {
              var V = C * (1 + 0.2 / R);
              V = Math.min(V, M + 100663296);
              var U = Math;
              V = Math.max(M, V), U = U.min.call(U, 4294901760, V + (65536 - V % 65536) % 65536);
              e: {
                try {
                  A.grow(U - L.byteLength + 65535 >>> 16), me();
                  var H = 1;
                  break e;
                } catch {
                }
                H = void 0;
              }
              if (H) return !0;
            }
            return !1;
          }, va: function(M, C) {
            var R = 0;
            return Ot().forEach((function(V, U) {
              var H = C + R;
              for (U = D[M + 4 * U >> 2 >>> 0] = H, H = 0; H < V.length; ++H) j[U++ >> 0 >>> 0] = V.charCodeAt(H);
              j[U >> 0 >>> 0] = 0, R += V.length + 1;
            })), 0;
          }, wa: function(M, C) {
            var R = Ot();
            D[M >> 2 >>> 0] = R.length;
            var V = 0;
            return R.forEach((function(U) {
              V += U.length + 1;
            })), D[C >> 2 >>> 0] = V, 0;
          }, ba: function(M) {
            v || 0 < Le || (it(), He(ve), pt(0), ut[1].length && lt(1, 10), ut[2].length && lt(2, 10)), v || 0 < Le || (a.onExit && a.onExit(M), I = !0), _(M, new ze(M));
          }, E: function() {
            return 52;
          }, Q: function() {
            return 52;
          }, ca: function() {
            return 70;
          }, P: function(M, C, R, V) {
            for (var U = 0, H = 0; H < R; H++) {
              var K = D[C >> 2 >>> 0], Z = D[C + 4 >> 2 >>> 0];
              C += 8;
              for (var J = 0; J < Z; J++) lt(M, B[K + J >>> 0]);
              U += Z;
            }
            return D[V >> 2 >>> 0] = U, 0;
          }, c: function() {
            return Fe;
          }, ja: function M(C, R) {
            M.Mb || (M.Mb = (function() {
              if (typeof crypto == "object" && typeof crypto.getRandomValues == "function") {
                var U = new Uint8Array(1);
                return () => (crypto.getRandomValues(U), U[0]);
              }
              if (w) try {
                var H = o(Object((function() {
                  var K = new Error("Cannot find module 'crypto'");
                  throw K.code = "MODULE_NOT_FOUND", K;
                })()));
                return () => H.randomBytes(1)[0];
              } catch {
              }
              return () => Pe("randomDevice");
            })());
            for (var V = 0; V < R; V++) j[C + V >> 0 >>> 0] = M.Mb();
            return 0;
          }, ea: function(M, C, R) {
            var V = ie();
            try {
              return he(M)(C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, fa: function(M, C, R) {
            var V = ie();
            try {
              return he(M)(C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, J: function(M) {
            var C = ie();
            try {
              return he(M)();
            } catch (R) {
              if (oe(C), R !== R + 0) throw R;
              se(1, 0);
            }
          }, e: function(M, C) {
            var R = ie();
            try {
              return he(M)(C);
            } catch (V) {
              if (oe(R), V !== V + 0) throw V;
              se(1, 0);
            }
          }, N: function(M, C, R) {
            var V = ie();
            try {
              return he(M)(C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, O: function(M, C, R) {
            var V = ie();
            try {
              return he(M)(C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, j: function(M, C, R) {
            var V = ie();
            try {
              return he(M)(C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, o: function(M, C, R, V) {
            var U = ie();
            try {
              return he(M)(C, R, V);
            } catch (H) {
              if (oe(U), H !== H + 0) throw H;
              se(1, 0);
            }
          }, p: function(M, C, R, V, U) {
            var H = ie();
            try {
              return he(M)(C, R, V, U);
            } catch (K) {
              if (oe(H), K !== K + 0) throw K;
              se(1, 0);
            }
          }, M: function(M, C, R, V, U, H) {
            var K = ie();
            try {
              return he(M)(C, R, V, U, H);
            } catch (Z) {
              if (oe(K), Z !== Z + 0) throw Z;
              se(1, 0);
            }
          }, r: function(M, C, R, V, U, H) {
            var K = ie();
            try {
              return he(M)(C, R, V, U, H);
            } catch (Z) {
              if (oe(K), Z !== Z + 0) throw Z;
              se(1, 0);
            }
          }, v: function(M, C, R, V, U, H, K) {
            var Z = ie();
            try {
              return he(M)(C, R, V, U, H, K);
            } catch (J) {
              if (oe(Z), J !== J + 0) throw J;
              se(1, 0);
            }
          }, K: function(M, C, R, V, U, H, K, Z) {
            var J = ie();
            try {
              return he(M)(C, R, V, U, H, K, Z);
            } catch (ae) {
              if (oe(J), ae !== ae + 0) throw ae;
              se(1, 0);
            }
          }, D: function(M, C, R, V, U, H, K, Z, J, ae, we, De) {
            var Ie = ie();
            try {
              return he(M)(C, R, V, U, H, K, Z, J, ae, we, De);
            } catch (q) {
              if (oe(Ie), q !== q + 0) throw q;
              se(1, 0);
            }
          }, X: function(M, C, R, V, U, H, K, Z) {
            var J = ie();
            try {
              return xt(M, C, R, V, U, H, K, Z);
            } catch (ae) {
              if (oe(J), ae !== ae + 0) throw ae;
              se(1, 0);
            }
          }, V: function(M, C, R, V, U, H, K) {
            var Z = ie();
            try {
              return mt(M, C, R, V, U, H, K);
            } catch (J) {
              if (oe(Z), J !== J + 0) throw J;
              se(1, 0);
            }
          }, U: function(M, C, R, V, U) {
            var H = ie();
            try {
              return St(M, C, R, V, U);
            } catch (K) {
              if (oe(H), K !== K + 0) throw K;
              se(1, 0);
            }
          }, Z: function(M, C, R, V) {
            var U = ie();
            try {
              return Tt(M, C, R, V);
            } catch (H) {
              if (oe(U), H !== H + 0) throw H;
              se(1, 0);
            }
          }, W: function(M) {
            var C = ie();
            try {
              return gt(M);
            } catch (R) {
              if (oe(C), R !== R + 0) throw R;
              se(1, 0);
            }
          }, Y: function(M, C) {
            var R = ie();
            try {
              return vt(M, C);
            } catch (V) {
              if (oe(R), V !== V + 0) throw V;
              se(1, 0);
            }
          }, T: function(M, C, R) {
            var V = ie();
            try {
              return _t(M, C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, f: function(M) {
            var C = ie();
            try {
              he(M)();
            } catch (R) {
              if (oe(C), R !== R + 0) throw R;
              se(1, 0);
            }
          }, q: function(M, C) {
            var R = ie();
            try {
              he(M)(C);
            } catch (V) {
              if (oe(R), V !== V + 0) throw V;
              se(1, 0);
            }
          }, h: function(M, C, R) {
            var V = ie();
            try {
              he(M)(C, R);
            } catch (U) {
              if (oe(V), U !== U + 0) throw U;
              se(1, 0);
            }
          }, da: function(M, C, R, V) {
            var U = ie();
            try {
              he(M)(C, R, V);
            } catch (H) {
              if (oe(U), H !== H + 0) throw H;
              se(1, 0);
            }
          }, l: function(M, C, R, V) {
            var U = ie();
            try {
              he(M)(C, R, V);
            } catch (H) {
              if (oe(U), H !== H + 0) throw H;
              se(1, 0);
            }
          }, t: function(M, C, R, V, U) {
            var H = ie();
            try {
              he(M)(C, R, V, U);
            } catch (K) {
              if (oe(H), K !== K + 0) throw K;
              se(1, 0);
            }
          }, u: function(M, C, R, V, U, H) {
            var K = ie();
            try {
              he(M)(C, R, V, U, H);
            } catch (Z) {
              if (oe(K), Z !== Z + 0) throw Z;
              se(1, 0);
            }
          }, x: function(M, C, R, V, U, H, K) {
            var Z = ie();
            try {
              he(M)(C, R, V, U, H, K);
            } catch (J) {
              if (oe(Z), J !== J + 0) throw J;
              se(1, 0);
            }
          }, z: function(M, C, R, V, U, H, K, Z) {
            var J = ie();
            try {
              he(M)(C, R, V, U, H, K, Z);
            } catch (ae) {
              if (oe(J), ae !== ae + 0) throw ae;
              se(1, 0);
            }
          }, ga: function(M, C, R, V, U, H, K, Z, J) {
            var ae = ie();
            try {
              he(M)(C, R, V, U, H, K, Z, J);
            } catch (we) {
              if (oe(ae), we !== we + 0) throw we;
              se(1, 0);
            }
          }, A: function(M, C, R, V, U, H, K, Z, J, ae, we) {
            var De = ie();
            try {
              he(M)(C, R, V, U, H, K, Z, J, ae, we);
            } catch (Ie) {
              if (oe(De), Ie !== Ie + 0) throw Ie;
              se(1, 0);
            }
          }, C: function(M, C, R, V, U, H, K, Z, J, ae, we, De, Ie, q, ge, xe) {
            var Ge = ie();
            try {
              he(M)(C, R, V, U, H, K, Z, J, ae, we, De, Ie, q, ge, xe);
            } catch (Ze) {
              if (oe(Ge), Ze !== Ze + 0) throw Ze;
              se(1, 0);
            }
          }, aa: function(M, C, R, V, U, H, K, Z) {
            var J = ie();
            try {
              bt(M, C, R, V, U, H, K, Z);
            } catch (ae) {
              if (oe(J), ae !== ae + 0) throw ae;
              se(1, 0);
            }
          }, _: function(M, C, R, V, U, H, K, Z, J, ae, we, De) {
            var Ie = ie();
            try {
              wt(M, C, R, V, U, H, K, Z, J, ae, we, De);
            } catch (q) {
              if (oe(Ie), q !== q + 0) throw q;
              se(1, 0);
            }
          }, $: function(M, C, R, V, U, H) {
            var K = ie();
            try {
              yt(M, C, R, V, U, H);
            } catch (Z) {
              if (oe(K), Z !== Z + 0) throw Z;
              se(1, 0);
            }
          }, n: function(M) {
            return M;
          }, F: function(M) {
            Fe = M;
          }, ha: Pt, y: function(M, C, R, V) {
            return Pt(M, C, R, V);
          } };
          (function() {
            function M(U) {
              a.asm = U.exports, A = a.asm.Ka, me(), Ae = a.asm.ib, ce.unshift(a.asm.La), Ne--, a.monitorRunDependencies && a.monitorRunDependencies(Ne), Ne == 0 && Ce && (U = Ce, Ce = null, U());
            }
            function C(U) {
              M(U.instance);
            }
            function R(U) {
              return (function() {
                if (!S && (b || y)) {
                  if (typeof fetch == "function" && !Oe.startsWith("file://")) return fetch(Oe, { credentials: "same-origin" }).then((function(H) {
                    if (!H.ok) throw "failed to load wasm binary file at '" + Oe + "'";
                    return H.arrayBuffer();
                  })).catch((function() {
                    return Ve();
                  }));
                  if (s) return new Promise((function(H, K) {
                    s(Oe, (function(Z) {
                      H(new Uint8Array(Z));
                    }), K);
                  }));
                }
                return Promise.resolve().then((function() {
                  return Ve();
                }));
              })().then((function(H) {
                return WebAssembly.instantiate(H, V);
              })).then((function(H) {
                return H;
              })).then(U, (function(H) {
                O("failed to asynchronously prepare wasm: " + H), Pe(H);
              }));
            }
            var V = { a: Mt };
            if (Ne++, a.monitorRunDependencies && a.monitorRunDependencies(Ne), a.instantiateWasm) try {
              return a.instantiateWasm(V, M);
            } catch (U) {
              return O("Module.instantiateWasm callback failed with error: " + U), !1;
            }
            (S || typeof WebAssembly.instantiateStreaming != "function" || Te() || Oe.startsWith("file://") || w || typeof fetch != "function" ? R(C) : fetch(Oe, { credentials: "same-origin" }).then((function(U) {
              return WebAssembly.instantiateStreaming(U, V).then(C, (function(H) {
                return O("wasm streaming compile failed: " + H), O("falling back to ArrayBuffer instantiation"), R(C);
              }));
            }))).catch(g);
          })(), a.___wasm_call_ctors = function() {
            return (a.___wasm_call_ctors = a.asm.La).apply(null, arguments);
          }, a._OrtInit = function() {
            return (a._OrtInit = a.asm.Ma).apply(null, arguments);
          }, a._OrtCreateSessionOptions = function() {
            return (a._OrtCreateSessionOptions = a.asm.Na).apply(null, arguments);
          }, a._OrtAppendExecutionProvider = function() {
            return (a._OrtAppendExecutionProvider = a.asm.Oa).apply(null, arguments);
          }, a._OrtAddSessionConfigEntry = function() {
            return (a._OrtAddSessionConfigEntry = a.asm.Pa).apply(null, arguments);
          }, a._OrtReleaseSessionOptions = function() {
            return (a._OrtReleaseSessionOptions = a.asm.Qa).apply(null, arguments);
          }, a._OrtCreateSession = function() {
            return (a._OrtCreateSession = a.asm.Ra).apply(null, arguments);
          }, a._OrtReleaseSession = function() {
            return (a._OrtReleaseSession = a.asm.Sa).apply(null, arguments);
          }, a._OrtGetInputCount = function() {
            return (a._OrtGetInputCount = a.asm.Ta).apply(null, arguments);
          }, a._OrtGetOutputCount = function() {
            return (a._OrtGetOutputCount = a.asm.Ua).apply(null, arguments);
          }, a._OrtGetInputName = function() {
            return (a._OrtGetInputName = a.asm.Va).apply(null, arguments);
          }, a._OrtGetOutputName = function() {
            return (a._OrtGetOutputName = a.asm.Wa).apply(null, arguments);
          }, a._OrtFree = function() {
            return (a._OrtFree = a.asm.Xa).apply(null, arguments);
          }, a._OrtCreateTensor = function() {
            return (a._OrtCreateTensor = a.asm.Ya).apply(null, arguments);
          }, a._OrtGetTensorData = function() {
            return (a._OrtGetTensorData = a.asm.Za).apply(null, arguments);
          }, a._OrtReleaseTensor = function() {
            return (a._OrtReleaseTensor = a.asm._a).apply(null, arguments);
          }, a._OrtCreateRunOptions = function() {
            return (a._OrtCreateRunOptions = a.asm.$a).apply(null, arguments);
          }, a._OrtAddRunConfigEntry = function() {
            return (a._OrtAddRunConfigEntry = a.asm.ab).apply(null, arguments);
          }, a._OrtReleaseRunOptions = function() {
            return (a._OrtReleaseRunOptions = a.asm.bb).apply(null, arguments);
          }, a._OrtRun = function() {
            return (a._OrtRun = a.asm.cb).apply(null, arguments);
          }, a._OrtEndProfiling = function() {
            return (a._OrtEndProfiling = a.asm.db).apply(null, arguments);
          };
          var Je, be = a._malloc = function() {
            return (be = a._malloc = a.asm.eb).apply(null, arguments);
          }, rt = a._free = function() {
            return (rt = a._free = a.asm.fb).apply(null, arguments);
          }, pt = a._fflush = function() {
            return (pt = a._fflush = a.asm.gb).apply(null, arguments);
          }, it = a.___funcs_on_exit = function() {
            return (it = a.___funcs_on_exit = a.asm.hb).apply(null, arguments);
          }, se = a._setThrew = function() {
            return (se = a._setThrew = a.asm.jb).apply(null, arguments);
          }, ie = a.stackSave = function() {
            return (ie = a.stackSave = a.asm.kb).apply(null, arguments);
          }, oe = a.stackRestore = function() {
            return (oe = a.stackRestore = a.asm.lb).apply(null, arguments);
          }, ht = a.stackAlloc = function() {
            return (ht = a.stackAlloc = a.asm.mb).apply(null, arguments);
          }, ot = a.___cxa_can_catch = function() {
            return (ot = a.___cxa_can_catch = a.asm.nb).apply(null, arguments);
          }, ft = a.___cxa_is_pointer_type = function() {
            return (ft = a.___cxa_is_pointer_type = a.asm.ob).apply(null, arguments);
          }, gt = a.dynCall_j = function() {
            return (gt = a.dynCall_j = a.asm.pb).apply(null, arguments);
          }, mt = a.dynCall_iiiiij = function() {
            return (mt = a.dynCall_iiiiij = a.asm.qb).apply(null, arguments);
          }, _t = a.dynCall_jii = function() {
            return (_t = a.dynCall_jii = a.asm.rb).apply(null, arguments);
          }, bt = a.dynCall_viiiiij = function() {
            return (bt = a.dynCall_viiiiij = a.asm.sb).apply(null, arguments);
          }, yt = a.dynCall_vjji = function() {
            return (yt = a.dynCall_vjji = a.asm.tb).apply(null, arguments);
          }, wt = a.dynCall_viiijjjii = function() {
            return (wt = a.dynCall_viiijjjii = a.asm.ub).apply(null, arguments);
          }, Tt = a.dynCall_iij = function() {
            return (Tt = a.dynCall_iij = a.asm.vb).apply(null, arguments);
          }, vt = a.dynCall_ji = function() {
            return (vt = a.dynCall_ji = a.asm.wb).apply(null, arguments);
          }, xt = a.dynCall_iiiiiij = function() {
            return (xt = a.dynCall_iiiiiij = a.asm.xb).apply(null, arguments);
          }, St = a.dynCall_iiij = function() {
            return (St = a.dynCall_iiij = a.asm.yb).apply(null, arguments);
          };
          function Et() {
            function M() {
              if (!Je && (Je = !0, a.calledRun = !0, !I)) {
                if (He(ce), f(a), a.onRuntimeInitialized && a.onRuntimeInitialized(), a.postRun) for (typeof a.postRun == "function" && (a.postRun = [a.postRun]); a.postRun.length; ) {
                  var C = a.postRun.shift();
                  ye.unshift(C);
                }
                He(ye);
              }
            }
            if (!(0 < Ne)) {
              if (a.preRun) for (typeof a.preRun == "function" && (a.preRun = [a.preRun]); a.preRun.length; ) We();
              He(Ee), 0 < Ne || (a.setStatus ? (a.setStatus("Running..."), setTimeout((function() {
                setTimeout((function() {
                  a.setStatus("");
                }), 1), M();
              }), 1)) : M());
            }
          }
          if (a.UTF8ToString = Y, a.stringToUTF8 = function(M, C, R) {
            return te(M, B, C, R);
          }, a.lengthBytesUTF8 = ne, a.stackSave = ie, a.stackRestore = oe, a.stackAlloc = ht, Ce = function M() {
            Je || Et(), Je || (Ce = M);
          }, a.preInit) for (typeof a.preInit == "function" && (a.preInit = [a.preInit]); 0 < a.preInit.length; ) a.preInit.pop()();
          return Et(), h.ready;
        });
        d.exports = l;
      }, 4537: (d) => {
        d.exports = function(n, o) {
          for (var u = new Array(arguments.length - 1), l = 0, h = 2, a = !0; h < arguments.length; ) u[l++] = arguments[h++];
          return new Promise((function(f, g) {
            u[l] = function(c) {
              if (a) if (a = !1, c) g(c);
              else {
                for (var s = new Array(arguments.length - 1), t = 0; t < s.length; ) s[t++] = arguments[t];
                f.apply(null, s);
              }
            };
            try {
              n.apply(o || null, u);
            } catch (c) {
              a && (a = !1, g(c));
            }
          }));
        };
      }, 7419: (d, n) => {
        var o = n;
        o.length = function(f) {
          var g = f.length;
          if (!g) return 0;
          for (var c = 0; --g % 4 > 1 && f.charAt(g) === "="; ) ++c;
          return Math.ceil(3 * f.length) / 4 - c;
        };
        for (var u = new Array(64), l = new Array(123), h = 0; h < 64; ) l[u[h] = h < 26 ? h + 65 : h < 52 ? h + 71 : h < 62 ? h - 4 : h - 59 | 43] = h++;
        o.encode = function(f, g, c) {
          for (var s, t = null, e = [], r = 0, i = 0; g < c; ) {
            var p = f[g++];
            switch (i) {
              case 0:
                e[r++] = u[p >> 2], s = (3 & p) << 4, i = 1;
                break;
              case 1:
                e[r++] = u[s | p >> 4], s = (15 & p) << 2, i = 2;
                break;
              case 2:
                e[r++] = u[s | p >> 6], e[r++] = u[63 & p], i = 0;
            }
            r > 8191 && ((t || (t = [])).push(String.fromCharCode.apply(String, e)), r = 0);
          }
          return i && (e[r++] = u[s], e[r++] = 61, i === 1 && (e[r++] = 61)), t ? (r && t.push(String.fromCharCode.apply(String, e.slice(0, r))), t.join("")) : String.fromCharCode.apply(String, e.slice(0, r));
        };
        var a = "invalid encoding";
        o.decode = function(f, g, c) {
          for (var s, t = c, e = 0, r = 0; r < f.length; ) {
            var i = f.charCodeAt(r++);
            if (i === 61 && e > 1) break;
            if ((i = l[i]) === void 0) throw Error(a);
            switch (e) {
              case 0:
                s = i, e = 1;
                break;
              case 1:
                g[c++] = s << 2 | (48 & i) >> 4, s = i, e = 2;
                break;
              case 2:
                g[c++] = (15 & s) << 4 | (60 & i) >> 2, s = i, e = 3;
                break;
              case 3:
                g[c++] = (3 & s) << 6 | i, e = 0;
            }
          }
          if (e === 1) throw Error(a);
          return c - t;
        }, o.test = function(f) {
          return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(f);
        };
      }, 9211: (d) => {
        function n() {
          this._listeners = {};
        }
        d.exports = n, n.prototype.on = function(o, u, l) {
          return (this._listeners[o] || (this._listeners[o] = [])).push({ fn: u, ctx: l || this }), this;
        }, n.prototype.off = function(o, u) {
          if (o === void 0) this._listeners = {};
          else if (u === void 0) this._listeners[o] = [];
          else for (var l = this._listeners[o], h = 0; h < l.length; ) l[h].fn === u ? l.splice(h, 1) : ++h;
          return this;
        }, n.prototype.emit = function(o) {
          var u = this._listeners[o];
          if (u) {
            for (var l = [], h = 1; h < arguments.length; ) l.push(arguments[h++]);
            for (h = 0; h < u.length; ) u[h].fn.apply(u[h++].ctx, l);
          }
          return this;
        };
      }, 945: (d) => {
        function n(a) {
          return typeof Float32Array < "u" ? (function() {
            var f = new Float32Array([-0]), g = new Uint8Array(f.buffer), c = g[3] === 128;
            function s(i, p, m) {
              f[0] = i, p[m] = g[0], p[m + 1] = g[1], p[m + 2] = g[2], p[m + 3] = g[3];
            }
            function t(i, p, m) {
              f[0] = i, p[m] = g[3], p[m + 1] = g[2], p[m + 2] = g[1], p[m + 3] = g[0];
            }
            function e(i, p) {
              return g[0] = i[p], g[1] = i[p + 1], g[2] = i[p + 2], g[3] = i[p + 3], f[0];
            }
            function r(i, p) {
              return g[3] = i[p], g[2] = i[p + 1], g[1] = i[p + 2], g[0] = i[p + 3], f[0];
            }
            a.writeFloatLE = c ? s : t, a.writeFloatBE = c ? t : s, a.readFloatLE = c ? e : r, a.readFloatBE = c ? r : e;
          })() : (function() {
            function f(c, s, t, e) {
              var r = s < 0 ? 1 : 0;
              if (r && (s = -s), s === 0) c(1 / s > 0 ? 0 : 2147483648, t, e);
              else if (isNaN(s)) c(2143289344, t, e);
              else if (s > 34028234663852886e22) c((r << 31 | 2139095040) >>> 0, t, e);
              else if (s < 11754943508222875e-54) c((r << 31 | Math.round(s / 1401298464324817e-60)) >>> 0, t, e);
              else {
                var i = Math.floor(Math.log(s) / Math.LN2);
                c((r << 31 | i + 127 << 23 | 8388607 & Math.round(s * Math.pow(2, -i) * 8388608)) >>> 0, t, e);
              }
            }
            function g(c, s, t) {
              var e = c(s, t), r = 2 * (e >> 31) + 1, i = e >>> 23 & 255, p = 8388607 & e;
              return i === 255 ? p ? NaN : r * (1 / 0) : i === 0 ? 1401298464324817e-60 * r * p : r * Math.pow(2, i - 150) * (p + 8388608);
            }
            a.writeFloatLE = f.bind(null, o), a.writeFloatBE = f.bind(null, u), a.readFloatLE = g.bind(null, l), a.readFloatBE = g.bind(null, h);
          })(), typeof Float64Array < "u" ? (function() {
            var f = new Float64Array([-0]), g = new Uint8Array(f.buffer), c = g[7] === 128;
            function s(i, p, m) {
              f[0] = i, p[m] = g[0], p[m + 1] = g[1], p[m + 2] = g[2], p[m + 3] = g[3], p[m + 4] = g[4], p[m + 5] = g[5], p[m + 6] = g[6], p[m + 7] = g[7];
            }
            function t(i, p, m) {
              f[0] = i, p[m] = g[7], p[m + 1] = g[6], p[m + 2] = g[5], p[m + 3] = g[4], p[m + 4] = g[3], p[m + 5] = g[2], p[m + 6] = g[1], p[m + 7] = g[0];
            }
            function e(i, p) {
              return g[0] = i[p], g[1] = i[p + 1], g[2] = i[p + 2], g[3] = i[p + 3], g[4] = i[p + 4], g[5] = i[p + 5], g[6] = i[p + 6], g[7] = i[p + 7], f[0];
            }
            function r(i, p) {
              return g[7] = i[p], g[6] = i[p + 1], g[5] = i[p + 2], g[4] = i[p + 3], g[3] = i[p + 4], g[2] = i[p + 5], g[1] = i[p + 6], g[0] = i[p + 7], f[0];
            }
            a.writeDoubleLE = c ? s : t, a.writeDoubleBE = c ? t : s, a.readDoubleLE = c ? e : r, a.readDoubleBE = c ? r : e;
          })() : (function() {
            function f(c, s, t, e, r, i) {
              var p = e < 0 ? 1 : 0;
              if (p && (e = -e), e === 0) c(0, r, i + s), c(1 / e > 0 ? 0 : 2147483648, r, i + t);
              else if (isNaN(e)) c(0, r, i + s), c(2146959360, r, i + t);
              else if (e > 17976931348623157e292) c(0, r, i + s), c((p << 31 | 2146435072) >>> 0, r, i + t);
              else {
                var m;
                if (e < 22250738585072014e-324) c((m = e / 5e-324) >>> 0, r, i + s), c((p << 31 | m / 4294967296) >>> 0, r, i + t);
                else {
                  var _ = Math.floor(Math.log(e) / Math.LN2);
                  _ === 1024 && (_ = 1023), c(4503599627370496 * (m = e * Math.pow(2, -_)) >>> 0, r, i + s), c((p << 31 | _ + 1023 << 20 | 1048576 * m & 1048575) >>> 0, r, i + t);
                }
              }
            }
            function g(c, s, t, e, r) {
              var i = c(e, r + s), p = c(e, r + t), m = 2 * (p >> 31) + 1, _ = p >>> 20 & 2047, b = 4294967296 * (1048575 & p) + i;
              return _ === 2047 ? b ? NaN : m * (1 / 0) : _ === 0 ? 5e-324 * m * b : m * Math.pow(2, _ - 1075) * (b + 4503599627370496);
            }
            a.writeDoubleLE = f.bind(null, o, 0, 4), a.writeDoubleBE = f.bind(null, u, 4, 0), a.readDoubleLE = g.bind(null, l, 0, 4), a.readDoubleBE = g.bind(null, h, 4, 0);
          })(), a;
        }
        function o(a, f, g) {
          f[g] = 255 & a, f[g + 1] = a >>> 8 & 255, f[g + 2] = a >>> 16 & 255, f[g + 3] = a >>> 24;
        }
        function u(a, f, g) {
          f[g] = a >>> 24, f[g + 1] = a >>> 16 & 255, f[g + 2] = a >>> 8 & 255, f[g + 3] = 255 & a;
        }
        function l(a, f) {
          return (a[f] | a[f + 1] << 8 | a[f + 2] << 16 | a[f + 3] << 24) >>> 0;
        }
        function h(a, f) {
          return (a[f] << 24 | a[f + 1] << 16 | a[f + 2] << 8 | a[f + 3]) >>> 0;
        }
        d.exports = n(n);
      }, 7199: (module) => {
        function inquire(moduleName) {
          try {
            var mod = eval("quire".replace(/^/, "re"))(moduleName);
            if (mod && (mod.length || Object.keys(mod).length)) return mod;
          } catch (d) {
          }
          return null;
        }
        module.exports = inquire;
      }, 6662: (d) => {
        d.exports = function(n, o, u) {
          var l = u || 8192, h = l >>> 1, a = null, f = l;
          return function(g) {
            if (g < 1 || g > h) return n(g);
            f + g > l && (a = n(l), f = 0);
            var c = o.call(a, f, f += g);
            return 7 & f && (f = 1 + (7 | f)), c;
          };
        };
      }, 4997: (d, n) => {
        var o = n;
        o.length = function(u) {
          for (var l = 0, h = 0, a = 0; a < u.length; ++a) (h = u.charCodeAt(a)) < 128 ? l += 1 : h < 2048 ? l += 2 : (64512 & h) == 55296 && (64512 & u.charCodeAt(a + 1)) == 56320 ? (++a, l += 4) : l += 3;
          return l;
        }, o.read = function(u, l, h) {
          if (h - l < 1) return "";
          for (var a, f = null, g = [], c = 0; l < h; ) (a = u[l++]) < 128 ? g[c++] = a : a > 191 && a < 224 ? g[c++] = (31 & a) << 6 | 63 & u[l++] : a > 239 && a < 365 ? (a = ((7 & a) << 18 | (63 & u[l++]) << 12 | (63 & u[l++]) << 6 | 63 & u[l++]) - 65536, g[c++] = 55296 + (a >> 10), g[c++] = 56320 + (1023 & a)) : g[c++] = (15 & a) << 12 | (63 & u[l++]) << 6 | 63 & u[l++], c > 8191 && ((f || (f = [])).push(String.fromCharCode.apply(String, g)), c = 0);
          return f ? (c && f.push(String.fromCharCode.apply(String, g.slice(0, c))), f.join("")) : String.fromCharCode.apply(String, g.slice(0, c));
        }, o.write = function(u, l, h) {
          for (var a, f, g = h, c = 0; c < u.length; ++c) (a = u.charCodeAt(c)) < 128 ? l[h++] = a : a < 2048 ? (l[h++] = a >> 6 | 192, l[h++] = 63 & a | 128) : (64512 & a) == 55296 && (64512 & (f = u.charCodeAt(c + 1))) == 56320 ? (a = 65536 + ((1023 & a) << 10) + (1023 & f), ++c, l[h++] = a >> 18 | 240, l[h++] = a >> 12 & 63 | 128, l[h++] = a >> 6 & 63 | 128, l[h++] = 63 & a | 128) : (l[h++] = a >> 12 | 224, l[h++] = a >> 6 & 63 | 128, l[h++] = 63 & a | 128);
          return h - g;
        };
      }, 3442: (d, n) => {
        n.__esModule = !0;
        var o = (function() {
          function u(l) {
            if (!l) throw new TypeError("Invalid argument; `value` has no value.");
            this.value = u.EMPTY, l && u.isGuid(l) && (this.value = l);
          }
          return u.isGuid = function(l) {
            var h = l.toString();
            return l && (l instanceof u || u.validator.test(h));
          }, u.create = function() {
            return new u([u.gen(2), u.gen(1), u.gen(1), u.gen(1), u.gen(3)].join("-"));
          }, u.createEmpty = function() {
            return new u("emptyguid");
          }, u.parse = function(l) {
            return new u(l);
          }, u.raw = function() {
            return [u.gen(2), u.gen(1), u.gen(1), u.gen(1), u.gen(3)].join("-");
          }, u.gen = function(l) {
            for (var h = "", a = 0; a < l; a++) h += (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
            return h;
          }, u.prototype.equals = function(l) {
            return u.isGuid(l) && this.value === l.toString();
          }, u.prototype.isEmpty = function() {
            return this.value === u.EMPTY;
          }, u.prototype.toString = function() {
            return this.value;
          }, u.prototype.toJSON = function() {
            return { value: this.value };
          }, u.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), u.EMPTY = "00000000-0000-0000-0000-000000000000", u;
        })();
        n.Guid = o;
      }, 3720: (d) => {
        d.exports = o;
        var n = null;
        try {
          n = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
        } catch {
        }
        function o(v, A, L) {
          this.low = 0 | v, this.high = 0 | A, this.unsigned = !!L;
        }
        function u(v) {
          return (v && v.__isLong__) === !0;
        }
        o.prototype.__isLong__, Object.defineProperty(o.prototype, "__isLong__", { value: !0 }), o.isLong = u;
        var l = {}, h = {};
        function a(v, A) {
          var L, j, B;
          return A ? (B = 0 <= (v >>>= 0) && v < 256) && (j = h[v]) ? j : (L = g(v, (0 | v) < 0 ? -1 : 0, !0), B && (h[v] = L), L) : (B = -128 <= (v |= 0) && v < 128) && (j = l[v]) ? j : (L = g(v, v < 0 ? -1 : 0, !1), B && (l[v] = L), L);
        }
        function f(v, A) {
          if (isNaN(v)) return A ? _ : m;
          if (A) {
            if (v < 0) return _;
            if (v >= r) return S;
          } else {
            if (v <= -i) return E;
            if (v + 1 >= i) return T;
          }
          return v < 0 ? f(-v, A).neg() : g(v % e | 0, v / e | 0, A);
        }
        function g(v, A, L) {
          return new o(v, A, L);
        }
        o.fromInt = a, o.fromNumber = f, o.fromBits = g;
        var c = Math.pow;
        function s(v, A, L) {
          if (v.length === 0) throw Error("empty string");
          if (v === "NaN" || v === "Infinity" || v === "+Infinity" || v === "-Infinity") return m;
          if (typeof A == "number" ? (L = A, A = !1) : A = !!A, (L = L || 10) < 2 || 36 < L) throw RangeError("radix");
          var j;
          if ((j = v.indexOf("-")) > 0) throw Error("interior hyphen");
          if (j === 0) return s(v.substring(1), A, L).neg();
          for (var B = f(c(L, 8)), F = m, D = 0; D < v.length; D += 8) {
            var I = Math.min(8, v.length - D), $ = parseInt(v.substring(D, D + I), L);
            if (I < 8) {
              var Q = f(c(L, I));
              F = F.mul(Q).add(f($));
            } else F = (F = F.mul(B)).add(f($));
          }
          return F.unsigned = A, F;
        }
        function t(v, A) {
          return typeof v == "number" ? f(v, A) : typeof v == "string" ? s(v, A) : g(v.low, v.high, typeof A == "boolean" ? A : v.unsigned);
        }
        o.fromString = s, o.fromValue = t;
        var e = 4294967296, r = e * e, i = r / 2, p = a(1 << 24), m = a(0);
        o.ZERO = m;
        var _ = a(0, !0);
        o.UZERO = _;
        var b = a(1);
        o.ONE = b;
        var y = a(1, !0);
        o.UONE = y;
        var w = a(-1);
        o.NEG_ONE = w;
        var T = g(-1, 2147483647, !1);
        o.MAX_VALUE = T;
        var S = g(-1, -1, !0);
        o.MAX_UNSIGNED_VALUE = S;
        var E = g(0, -2147483648, !1);
        o.MIN_VALUE = E;
        var O = o.prototype;
        O.toInt = function() {
          return this.unsigned ? this.low >>> 0 : this.low;
        }, O.toNumber = function() {
          return this.unsigned ? (this.high >>> 0) * e + (this.low >>> 0) : this.high * e + (this.low >>> 0);
        }, O.toString = function(v) {
          if ((v = v || 10) < 2 || 36 < v) throw RangeError("radix");
          if (this.isZero()) return "0";
          if (this.isNegative()) {
            if (this.eq(E)) {
              var A = f(v), L = this.div(A), j = L.mul(A).sub(this);
              return L.toString(v) + j.toInt().toString(v);
            }
            return "-" + this.neg().toString(v);
          }
          for (var B = f(c(v, 6), this.unsigned), F = this, D = ""; ; ) {
            var I = F.div(B), $ = (F.sub(I.mul(B)).toInt() >>> 0).toString(v);
            if ((F = I).isZero()) return $ + D;
            for (; $.length < 6; ) $ = "0" + $;
            D = "" + $ + D;
          }
        }, O.getHighBits = function() {
          return this.high;
        }, O.getHighBitsUnsigned = function() {
          return this.high >>> 0;
        }, O.getLowBits = function() {
          return this.low;
        }, O.getLowBitsUnsigned = function() {
          return this.low >>> 0;
        }, O.getNumBitsAbs = function() {
          if (this.isNegative()) return this.eq(E) ? 64 : this.neg().getNumBitsAbs();
          for (var v = this.high != 0 ? this.high : this.low, A = 31; A > 0 && (v & 1 << A) == 0; A--) ;
          return this.high != 0 ? A + 33 : A + 1;
        }, O.isZero = function() {
          return this.high === 0 && this.low === 0;
        }, O.eqz = O.isZero, O.isNegative = function() {
          return !this.unsigned && this.high < 0;
        }, O.isPositive = function() {
          return this.unsigned || this.high >= 0;
        }, O.isOdd = function() {
          return (1 & this.low) == 1;
        }, O.isEven = function() {
          return (1 & this.low) == 0;
        }, O.equals = function(v) {
          return u(v) || (v = t(v)), (this.unsigned === v.unsigned || this.high >>> 31 != 1 || v.high >>> 31 != 1) && this.high === v.high && this.low === v.low;
        }, O.eq = O.equals, O.notEquals = function(v) {
          return !this.eq(v);
        }, O.neq = O.notEquals, O.ne = O.notEquals, O.lessThan = function(v) {
          return this.comp(v) < 0;
        }, O.lt = O.lessThan, O.lessThanOrEqual = function(v) {
          return this.comp(v) <= 0;
        }, O.lte = O.lessThanOrEqual, O.le = O.lessThanOrEqual, O.greaterThan = function(v) {
          return this.comp(v) > 0;
        }, O.gt = O.greaterThan, O.greaterThanOrEqual = function(v) {
          return this.comp(v) >= 0;
        }, O.gte = O.greaterThanOrEqual, O.ge = O.greaterThanOrEqual, O.compare = function(v) {
          if (u(v) || (v = t(v)), this.eq(v)) return 0;
          var A = this.isNegative(), L = v.isNegative();
          return A && !L ? -1 : !A && L ? 1 : this.unsigned ? v.high >>> 0 > this.high >>> 0 || v.high === this.high && v.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(v).isNegative() ? -1 : 1;
        }, O.comp = O.compare, O.negate = function() {
          return !this.unsigned && this.eq(E) ? E : this.not().add(b);
        }, O.neg = O.negate, O.add = function(v) {
          u(v) || (v = t(v));
          var A = this.high >>> 16, L = 65535 & this.high, j = this.low >>> 16, B = 65535 & this.low, F = v.high >>> 16, D = 65535 & v.high, I = v.low >>> 16, $ = 0, Q = 0, Y = 0, te = 0;
          return Y += (te += B + (65535 & v.low)) >>> 16, Q += (Y += j + I) >>> 16, $ += (Q += L + D) >>> 16, $ += A + F, g((Y &= 65535) << 16 | (te &= 65535), ($ &= 65535) << 16 | (Q &= 65535), this.unsigned);
        }, O.subtract = function(v) {
          return u(v) || (v = t(v)), this.add(v.neg());
        }, O.sub = O.subtract, O.multiply = function(v) {
          if (this.isZero()) return m;
          if (u(v) || (v = t(v)), n) return g(n.mul(this.low, this.high, v.low, v.high), n.get_high(), this.unsigned);
          if (v.isZero()) return m;
          if (this.eq(E)) return v.isOdd() ? E : m;
          if (v.eq(E)) return this.isOdd() ? E : m;
          if (this.isNegative()) return v.isNegative() ? this.neg().mul(v.neg()) : this.neg().mul(v).neg();
          if (v.isNegative()) return this.mul(v.neg()).neg();
          if (this.lt(p) && v.lt(p)) return f(this.toNumber() * v.toNumber(), this.unsigned);
          var A = this.high >>> 16, L = 65535 & this.high, j = this.low >>> 16, B = 65535 & this.low, F = v.high >>> 16, D = 65535 & v.high, I = v.low >>> 16, $ = 65535 & v.low, Q = 0, Y = 0, te = 0, ne = 0;
          return te += (ne += B * $) >>> 16, Y += (te += j * $) >>> 16, te &= 65535, Y += (te += B * I) >>> 16, Q += (Y += L * $) >>> 16, Y &= 65535, Q += (Y += j * I) >>> 16, Y &= 65535, Q += (Y += B * D) >>> 16, Q += A * $ + L * I + j * D + B * F, g((te &= 65535) << 16 | (ne &= 65535), (Q &= 65535) << 16 | (Y &= 65535), this.unsigned);
        }, O.mul = O.multiply, O.divide = function(v) {
          if (u(v) || (v = t(v)), v.isZero()) throw Error("division by zero");
          var A, L, j;
          if (n) return this.unsigned || this.high !== -2147483648 || v.low !== -1 || v.high !== -1 ? g((this.unsigned ? n.div_u : n.div_s)(this.low, this.high, v.low, v.high), n.get_high(), this.unsigned) : this;
          if (this.isZero()) return this.unsigned ? _ : m;
          if (this.unsigned) {
            if (v.unsigned || (v = v.toUnsigned()), v.gt(this)) return _;
            if (v.gt(this.shru(1))) return y;
            j = _;
          } else {
            if (this.eq(E)) return v.eq(b) || v.eq(w) ? E : v.eq(E) ? b : (A = this.shr(1).div(v).shl(1)).eq(m) ? v.isNegative() ? b : w : (L = this.sub(v.mul(A)), j = A.add(L.div(v)));
            if (v.eq(E)) return this.unsigned ? _ : m;
            if (this.isNegative()) return v.isNegative() ? this.neg().div(v.neg()) : this.neg().div(v).neg();
            if (v.isNegative()) return this.div(v.neg()).neg();
            j = m;
          }
          for (L = this; L.gte(v); ) {
            A = Math.max(1, Math.floor(L.toNumber() / v.toNumber()));
            for (var B = Math.ceil(Math.log(A) / Math.LN2), F = B <= 48 ? 1 : c(2, B - 48), D = f(A), I = D.mul(v); I.isNegative() || I.gt(L); ) I = (D = f(A -= F, this.unsigned)).mul(v);
            D.isZero() && (D = b), j = j.add(D), L = L.sub(I);
          }
          return j;
        }, O.div = O.divide, O.modulo = function(v) {
          return u(v) || (v = t(v)), n ? g((this.unsigned ? n.rem_u : n.rem_s)(this.low, this.high, v.low, v.high), n.get_high(), this.unsigned) : this.sub(this.div(v).mul(v));
        }, O.mod = O.modulo, O.rem = O.modulo, O.not = function() {
          return g(~this.low, ~this.high, this.unsigned);
        }, O.and = function(v) {
          return u(v) || (v = t(v)), g(this.low & v.low, this.high & v.high, this.unsigned);
        }, O.or = function(v) {
          return u(v) || (v = t(v)), g(this.low | v.low, this.high | v.high, this.unsigned);
        }, O.xor = function(v) {
          return u(v) || (v = t(v)), g(this.low ^ v.low, this.high ^ v.high, this.unsigned);
        }, O.shiftLeft = function(v) {
          return u(v) && (v = v.toInt()), (v &= 63) == 0 ? this : v < 32 ? g(this.low << v, this.high << v | this.low >>> 32 - v, this.unsigned) : g(0, this.low << v - 32, this.unsigned);
        }, O.shl = O.shiftLeft, O.shiftRight = function(v) {
          return u(v) && (v = v.toInt()), (v &= 63) == 0 ? this : v < 32 ? g(this.low >>> v | this.high << 32 - v, this.high >> v, this.unsigned) : g(this.high >> v - 32, this.high >= 0 ? 0 : -1, this.unsigned);
        }, O.shr = O.shiftRight, O.shiftRightUnsigned = function(v) {
          if (u(v) && (v = v.toInt()), (v &= 63) == 0) return this;
          var A = this.high;
          return v < 32 ? g(this.low >>> v | A << 32 - v, A >>> v, this.unsigned) : g(v === 32 ? A : A >>> v - 32, 0, this.unsigned);
        }, O.shru = O.shiftRightUnsigned, O.shr_u = O.shiftRightUnsigned, O.toSigned = function() {
          return this.unsigned ? g(this.low, this.high, !1) : this;
        }, O.toUnsigned = function() {
          return this.unsigned ? this : g(this.low, this.high, !0);
        }, O.toBytes = function(v) {
          return v ? this.toBytesLE() : this.toBytesBE();
        }, O.toBytesLE = function() {
          var v = this.high, A = this.low;
          return [255 & A, A >>> 8 & 255, A >>> 16 & 255, A >>> 24, 255 & v, v >>> 8 & 255, v >>> 16 & 255, v >>> 24];
        }, O.toBytesBE = function() {
          var v = this.high, A = this.low;
          return [v >>> 24, v >>> 16 & 255, v >>> 8 & 255, 255 & v, A >>> 24, A >>> 16 & 255, A >>> 8 & 255, 255 & A];
        }, o.fromBytes = function(v, A, L) {
          return L ? o.fromBytesLE(v, A) : o.fromBytesBE(v, A);
        }, o.fromBytesLE = function(v, A) {
          return new o(v[0] | v[1] << 8 | v[2] << 16 | v[3] << 24, v[4] | v[5] << 8 | v[6] << 16 | v[7] << 24, A);
        }, o.fromBytesBE = function(v, A) {
          return new o(v[4] << 24 | v[5] << 16 | v[6] << 8 | v[7], v[0] << 24 | v[1] << 16 | v[2] << 8 | v[3], A);
        };
      }, 1446: (d, n, o) => {
        var u, l, h, a = o(2100), f = a.Reader, g = a.Writer, c = a.util, s = a.roots.default || (a.roots.default = {});
        s.onnx = ((h = {}).Version = (u = {}, (l = Object.create(u))[u[0] = "_START_VERSION"] = 0, l[u[1] = "IR_VERSION_2017_10_10"] = 1, l[u[2] = "IR_VERSION_2017_10_30"] = 2, l[u[3] = "IR_VERSION_2017_11_3"] = 3, l[u[4] = "IR_VERSION_2019_1_22"] = 4, l[u[5] = "IR_VERSION"] = 5, l), h.AttributeProto = (function() {
          function t(e) {
            if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.name = "", t.prototype.refAttrName = "", t.prototype.docString = "", t.prototype.type = 0, t.prototype.f = 0, t.prototype.i = c.Long ? c.Long.fromBits(0, 0, !1) : 0, t.prototype.s = c.newBuffer([]), t.prototype.t = null, t.prototype.g = null, t.prototype.floats = c.emptyArray, t.prototype.ints = c.emptyArray, t.prototype.strings = c.emptyArray, t.prototype.tensors = c.emptyArray, t.prototype.graphs = c.emptyArray, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.name != null && e.hasOwnProperty("name") && r.uint32(10).string(e.name), e.f != null && e.hasOwnProperty("f") && r.uint32(21).float(e.f), e.i != null && e.hasOwnProperty("i") && r.uint32(24).int64(e.i), e.s != null && e.hasOwnProperty("s") && r.uint32(34).bytes(e.s), e.t != null && e.hasOwnProperty("t") && s.onnx.TensorProto.encode(e.t, r.uint32(42).fork()).ldelim(), e.g != null && e.hasOwnProperty("g") && s.onnx.GraphProto.encode(e.g, r.uint32(50).fork()).ldelim(), e.floats != null && e.floats.length) {
              r.uint32(58).fork();
              for (var i = 0; i < e.floats.length; ++i) r.float(e.floats[i]);
              r.ldelim();
            }
            if (e.ints != null && e.ints.length) {
              for (r.uint32(66).fork(), i = 0; i < e.ints.length; ++i) r.int64(e.ints[i]);
              r.ldelim();
            }
            if (e.strings != null && e.strings.length) for (i = 0; i < e.strings.length; ++i) r.uint32(74).bytes(e.strings[i]);
            if (e.tensors != null && e.tensors.length) for (i = 0; i < e.tensors.length; ++i) s.onnx.TensorProto.encode(e.tensors[i], r.uint32(82).fork()).ldelim();
            if (e.graphs != null && e.graphs.length) for (i = 0; i < e.graphs.length; ++i) s.onnx.GraphProto.encode(e.graphs[i], r.uint32(90).fork()).ldelim();
            return e.docString != null && e.hasOwnProperty("docString") && r.uint32(106).string(e.docString), e.type != null && e.hasOwnProperty("type") && r.uint32(160).int32(e.type), e.refAttrName != null && e.hasOwnProperty("refAttrName") && r.uint32(170).string(e.refAttrName), r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.AttributeProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.name = e.string();
                  break;
                case 21:
                  p.refAttrName = e.string();
                  break;
                case 13:
                  p.docString = e.string();
                  break;
                case 20:
                  p.type = e.int32();
                  break;
                case 2:
                  p.f = e.float();
                  break;
                case 3:
                  p.i = e.int64();
                  break;
                case 4:
                  p.s = e.bytes();
                  break;
                case 5:
                  p.t = s.onnx.TensorProto.decode(e, e.uint32());
                  break;
                case 6:
                  p.g = s.onnx.GraphProto.decode(e, e.uint32());
                  break;
                case 7:
                  if (p.floats && p.floats.length || (p.floats = []), (7 & m) == 2) for (var _ = e.uint32() + e.pos; e.pos < _; ) p.floats.push(e.float());
                  else p.floats.push(e.float());
                  break;
                case 8:
                  if (p.ints && p.ints.length || (p.ints = []), (7 & m) == 2) for (_ = e.uint32() + e.pos; e.pos < _; ) p.ints.push(e.int64());
                  else p.ints.push(e.int64());
                  break;
                case 9:
                  p.strings && p.strings.length || (p.strings = []), p.strings.push(e.bytes());
                  break;
                case 10:
                  p.tensors && p.tensors.length || (p.tensors = []), p.tensors.push(s.onnx.TensorProto.decode(e, e.uint32()));
                  break;
                case 11:
                  p.graphs && p.graphs.length || (p.graphs = []), p.graphs.push(s.onnx.GraphProto.decode(e, e.uint32()));
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.name != null && e.hasOwnProperty("name") && !c.isString(e.name)) return "name: string expected";
            if (e.refAttrName != null && e.hasOwnProperty("refAttrName") && !c.isString(e.refAttrName)) return "refAttrName: string expected";
            if (e.docString != null && e.hasOwnProperty("docString") && !c.isString(e.docString)) return "docString: string expected";
            if (e.type != null && e.hasOwnProperty("type")) switch (e.type) {
              default:
                return "type: enum value expected";
              case 0:
              case 1:
              case 2:
              case 3:
              case 4:
              case 5:
              case 6:
              case 7:
              case 8:
              case 9:
              case 10:
            }
            if (e.f != null && e.hasOwnProperty("f") && typeof e.f != "number") return "f: number expected";
            if (e.i != null && e.hasOwnProperty("i") && !(c.isInteger(e.i) || e.i && c.isInteger(e.i.low) && c.isInteger(e.i.high))) return "i: integer|Long expected";
            if (e.s != null && e.hasOwnProperty("s") && !(e.s && typeof e.s.length == "number" || c.isString(e.s))) return "s: buffer expected";
            if (e.t != null && e.hasOwnProperty("t") && (i = s.onnx.TensorProto.verify(e.t))) return "t." + i;
            if (e.g != null && e.hasOwnProperty("g") && (i = s.onnx.GraphProto.verify(e.g))) return "g." + i;
            if (e.floats != null && e.hasOwnProperty("floats")) {
              if (!Array.isArray(e.floats)) return "floats: array expected";
              for (var r = 0; r < e.floats.length; ++r) if (typeof e.floats[r] != "number") return "floats: number[] expected";
            }
            if (e.ints != null && e.hasOwnProperty("ints")) {
              if (!Array.isArray(e.ints)) return "ints: array expected";
              for (r = 0; r < e.ints.length; ++r) if (!(c.isInteger(e.ints[r]) || e.ints[r] && c.isInteger(e.ints[r].low) && c.isInteger(e.ints[r].high))) return "ints: integer|Long[] expected";
            }
            if (e.strings != null && e.hasOwnProperty("strings")) {
              if (!Array.isArray(e.strings)) return "strings: array expected";
              for (r = 0; r < e.strings.length; ++r) if (!(e.strings[r] && typeof e.strings[r].length == "number" || c.isString(e.strings[r]))) return "strings: buffer[] expected";
            }
            if (e.tensors != null && e.hasOwnProperty("tensors")) {
              if (!Array.isArray(e.tensors)) return "tensors: array expected";
              for (r = 0; r < e.tensors.length; ++r) if (i = s.onnx.TensorProto.verify(e.tensors[r])) return "tensors." + i;
            }
            if (e.graphs != null && e.hasOwnProperty("graphs")) {
              if (!Array.isArray(e.graphs)) return "graphs: array expected";
              for (r = 0; r < e.graphs.length; ++r) {
                var i;
                if (i = s.onnx.GraphProto.verify(e.graphs[r])) return "graphs." + i;
              }
            }
            return null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.AttributeProto) return e;
            var r = new s.onnx.AttributeProto();
            switch (e.name != null && (r.name = String(e.name)), e.refAttrName != null && (r.refAttrName = String(e.refAttrName)), e.docString != null && (r.docString = String(e.docString)), e.type) {
              case "UNDEFINED":
              case 0:
                r.type = 0;
                break;
              case "FLOAT":
              case 1:
                r.type = 1;
                break;
              case "INT":
              case 2:
                r.type = 2;
                break;
              case "STRING":
              case 3:
                r.type = 3;
                break;
              case "TENSOR":
              case 4:
                r.type = 4;
                break;
              case "GRAPH":
              case 5:
                r.type = 5;
                break;
              case "FLOATS":
              case 6:
                r.type = 6;
                break;
              case "INTS":
              case 7:
                r.type = 7;
                break;
              case "STRINGS":
              case 8:
                r.type = 8;
                break;
              case "TENSORS":
              case 9:
                r.type = 9;
                break;
              case "GRAPHS":
              case 10:
                r.type = 10;
            }
            if (e.f != null && (r.f = Number(e.f)), e.i != null && (c.Long ? (r.i = c.Long.fromValue(e.i)).unsigned = !1 : typeof e.i == "string" ? r.i = parseInt(e.i, 10) : typeof e.i == "number" ? r.i = e.i : typeof e.i == "object" && (r.i = new c.LongBits(e.i.low >>> 0, e.i.high >>> 0).toNumber())), e.s != null && (typeof e.s == "string" ? c.base64.decode(e.s, r.s = c.newBuffer(c.base64.length(e.s)), 0) : e.s.length && (r.s = e.s)), e.t != null) {
              if (typeof e.t != "object") throw TypeError(".onnx.AttributeProto.t: object expected");
              r.t = s.onnx.TensorProto.fromObject(e.t);
            }
            if (e.g != null) {
              if (typeof e.g != "object") throw TypeError(".onnx.AttributeProto.g: object expected");
              r.g = s.onnx.GraphProto.fromObject(e.g);
            }
            if (e.floats) {
              if (!Array.isArray(e.floats)) throw TypeError(".onnx.AttributeProto.floats: array expected");
              r.floats = [];
              for (var i = 0; i < e.floats.length; ++i) r.floats[i] = Number(e.floats[i]);
            }
            if (e.ints) {
              if (!Array.isArray(e.ints)) throw TypeError(".onnx.AttributeProto.ints: array expected");
              for (r.ints = [], i = 0; i < e.ints.length; ++i) c.Long ? (r.ints[i] = c.Long.fromValue(e.ints[i])).unsigned = !1 : typeof e.ints[i] == "string" ? r.ints[i] = parseInt(e.ints[i], 10) : typeof e.ints[i] == "number" ? r.ints[i] = e.ints[i] : typeof e.ints[i] == "object" && (r.ints[i] = new c.LongBits(e.ints[i].low >>> 0, e.ints[i].high >>> 0).toNumber());
            }
            if (e.strings) {
              if (!Array.isArray(e.strings)) throw TypeError(".onnx.AttributeProto.strings: array expected");
              for (r.strings = [], i = 0; i < e.strings.length; ++i) typeof e.strings[i] == "string" ? c.base64.decode(e.strings[i], r.strings[i] = c.newBuffer(c.base64.length(e.strings[i])), 0) : e.strings[i].length && (r.strings[i] = e.strings[i]);
            }
            if (e.tensors) {
              if (!Array.isArray(e.tensors)) throw TypeError(".onnx.AttributeProto.tensors: array expected");
              for (r.tensors = [], i = 0; i < e.tensors.length; ++i) {
                if (typeof e.tensors[i] != "object") throw TypeError(".onnx.AttributeProto.tensors: object expected");
                r.tensors[i] = s.onnx.TensorProto.fromObject(e.tensors[i]);
              }
            }
            if (e.graphs) {
              if (!Array.isArray(e.graphs)) throw TypeError(".onnx.AttributeProto.graphs: array expected");
              for (r.graphs = [], i = 0; i < e.graphs.length; ++i) {
                if (typeof e.graphs[i] != "object") throw TypeError(".onnx.AttributeProto.graphs: object expected");
                r.graphs[i] = s.onnx.GraphProto.fromObject(e.graphs[i]);
              }
            }
            return r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.floats = [], i.ints = [], i.strings = [], i.tensors = [], i.graphs = []), r.defaults) {
              if (i.name = "", i.f = 0, c.Long) {
                var p = new c.Long(0, 0, !1);
                i.i = r.longs === String ? p.toString() : r.longs === Number ? p.toNumber() : p;
              } else i.i = r.longs === String ? "0" : 0;
              r.bytes === String ? i.s = "" : (i.s = [], r.bytes !== Array && (i.s = c.newBuffer(i.s))), i.t = null, i.g = null, i.docString = "", i.type = r.enums === String ? "UNDEFINED" : 0, i.refAttrName = "";
            }
            if (e.name != null && e.hasOwnProperty("name") && (i.name = e.name), e.f != null && e.hasOwnProperty("f") && (i.f = r.json && !isFinite(e.f) ? String(e.f) : e.f), e.i != null && e.hasOwnProperty("i") && (typeof e.i == "number" ? i.i = r.longs === String ? String(e.i) : e.i : i.i = r.longs === String ? c.Long.prototype.toString.call(e.i) : r.longs === Number ? new c.LongBits(e.i.low >>> 0, e.i.high >>> 0).toNumber() : e.i), e.s != null && e.hasOwnProperty("s") && (i.s = r.bytes === String ? c.base64.encode(e.s, 0, e.s.length) : r.bytes === Array ? Array.prototype.slice.call(e.s) : e.s), e.t != null && e.hasOwnProperty("t") && (i.t = s.onnx.TensorProto.toObject(e.t, r)), e.g != null && e.hasOwnProperty("g") && (i.g = s.onnx.GraphProto.toObject(e.g, r)), e.floats && e.floats.length) {
              i.floats = [];
              for (var m = 0; m < e.floats.length; ++m) i.floats[m] = r.json && !isFinite(e.floats[m]) ? String(e.floats[m]) : e.floats[m];
            }
            if (e.ints && e.ints.length) for (i.ints = [], m = 0; m < e.ints.length; ++m) typeof e.ints[m] == "number" ? i.ints[m] = r.longs === String ? String(e.ints[m]) : e.ints[m] : i.ints[m] = r.longs === String ? c.Long.prototype.toString.call(e.ints[m]) : r.longs === Number ? new c.LongBits(e.ints[m].low >>> 0, e.ints[m].high >>> 0).toNumber() : e.ints[m];
            if (e.strings && e.strings.length) for (i.strings = [], m = 0; m < e.strings.length; ++m) i.strings[m] = r.bytes === String ? c.base64.encode(e.strings[m], 0, e.strings[m].length) : r.bytes === Array ? Array.prototype.slice.call(e.strings[m]) : e.strings[m];
            if (e.tensors && e.tensors.length) for (i.tensors = [], m = 0; m < e.tensors.length; ++m) i.tensors[m] = s.onnx.TensorProto.toObject(e.tensors[m], r);
            if (e.graphs && e.graphs.length) for (i.graphs = [], m = 0; m < e.graphs.length; ++m) i.graphs[m] = s.onnx.GraphProto.toObject(e.graphs[m], r);
            return e.docString != null && e.hasOwnProperty("docString") && (i.docString = e.docString), e.type != null && e.hasOwnProperty("type") && (i.type = r.enums === String ? s.onnx.AttributeProto.AttributeType[e.type] : e.type), e.refAttrName != null && e.hasOwnProperty("refAttrName") && (i.refAttrName = e.refAttrName), i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t.AttributeType = (function() {
            var e = {}, r = Object.create(e);
            return r[e[0] = "UNDEFINED"] = 0, r[e[1] = "FLOAT"] = 1, r[e[2] = "INT"] = 2, r[e[3] = "STRING"] = 3, r[e[4] = "TENSOR"] = 4, r[e[5] = "GRAPH"] = 5, r[e[6] = "FLOATS"] = 6, r[e[7] = "INTS"] = 7, r[e[8] = "STRINGS"] = 8, r[e[9] = "TENSORS"] = 9, r[e[10] = "GRAPHS"] = 10, r;
          })(), t;
        })(), h.ValueInfoProto = (function() {
          function t(e) {
            if (e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.name = "", t.prototype.type = null, t.prototype.docString = "", t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            return r || (r = g.create()), e.name != null && e.hasOwnProperty("name") && r.uint32(10).string(e.name), e.type != null && e.hasOwnProperty("type") && s.onnx.TypeProto.encode(e.type, r.uint32(18).fork()).ldelim(), e.docString != null && e.hasOwnProperty("docString") && r.uint32(26).string(e.docString), r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.ValueInfoProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.name = e.string();
                  break;
                case 2:
                  p.type = s.onnx.TypeProto.decode(e, e.uint32());
                  break;
                case 3:
                  p.docString = e.string();
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.name != null && e.hasOwnProperty("name") && !c.isString(e.name)) return "name: string expected";
            if (e.type != null && e.hasOwnProperty("type")) {
              var r = s.onnx.TypeProto.verify(e.type);
              if (r) return "type." + r;
            }
            return e.docString != null && e.hasOwnProperty("docString") && !c.isString(e.docString) ? "docString: string expected" : null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.ValueInfoProto) return e;
            var r = new s.onnx.ValueInfoProto();
            if (e.name != null && (r.name = String(e.name)), e.type != null) {
              if (typeof e.type != "object") throw TypeError(".onnx.ValueInfoProto.type: object expected");
              r.type = s.onnx.TypeProto.fromObject(e.type);
            }
            return e.docString != null && (r.docString = String(e.docString)), r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            return r.defaults && (i.name = "", i.type = null, i.docString = ""), e.name != null && e.hasOwnProperty("name") && (i.name = e.name), e.type != null && e.hasOwnProperty("type") && (i.type = s.onnx.TypeProto.toObject(e.type, r)), e.docString != null && e.hasOwnProperty("docString") && (i.docString = e.docString), i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h.NodeProto = (function() {
          function t(e) {
            if (this.input = [], this.output = [], this.attribute = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.input = c.emptyArray, t.prototype.output = c.emptyArray, t.prototype.name = "", t.prototype.opType = "", t.prototype.domain = "", t.prototype.attribute = c.emptyArray, t.prototype.docString = "", t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.input != null && e.input.length) for (var i = 0; i < e.input.length; ++i) r.uint32(10).string(e.input[i]);
            if (e.output != null && e.output.length) for (i = 0; i < e.output.length; ++i) r.uint32(18).string(e.output[i]);
            if (e.name != null && e.hasOwnProperty("name") && r.uint32(26).string(e.name), e.opType != null && e.hasOwnProperty("opType") && r.uint32(34).string(e.opType), e.attribute != null && e.attribute.length) for (i = 0; i < e.attribute.length; ++i) s.onnx.AttributeProto.encode(e.attribute[i], r.uint32(42).fork()).ldelim();
            return e.docString != null && e.hasOwnProperty("docString") && r.uint32(50).string(e.docString), e.domain != null && e.hasOwnProperty("domain") && r.uint32(58).string(e.domain), r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.NodeProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.input && p.input.length || (p.input = []), p.input.push(e.string());
                  break;
                case 2:
                  p.output && p.output.length || (p.output = []), p.output.push(e.string());
                  break;
                case 3:
                  p.name = e.string();
                  break;
                case 4:
                  p.opType = e.string();
                  break;
                case 7:
                  p.domain = e.string();
                  break;
                case 5:
                  p.attribute && p.attribute.length || (p.attribute = []), p.attribute.push(s.onnx.AttributeProto.decode(e, e.uint32()));
                  break;
                case 6:
                  p.docString = e.string();
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.input != null && e.hasOwnProperty("input")) {
              if (!Array.isArray(e.input)) return "input: array expected";
              for (var r = 0; r < e.input.length; ++r) if (!c.isString(e.input[r])) return "input: string[] expected";
            }
            if (e.output != null && e.hasOwnProperty("output")) {
              if (!Array.isArray(e.output)) return "output: array expected";
              for (r = 0; r < e.output.length; ++r) if (!c.isString(e.output[r])) return "output: string[] expected";
            }
            if (e.name != null && e.hasOwnProperty("name") && !c.isString(e.name)) return "name: string expected";
            if (e.opType != null && e.hasOwnProperty("opType") && !c.isString(e.opType)) return "opType: string expected";
            if (e.domain != null && e.hasOwnProperty("domain") && !c.isString(e.domain)) return "domain: string expected";
            if (e.attribute != null && e.hasOwnProperty("attribute")) {
              if (!Array.isArray(e.attribute)) return "attribute: array expected";
              for (r = 0; r < e.attribute.length; ++r) {
                var i = s.onnx.AttributeProto.verify(e.attribute[r]);
                if (i) return "attribute." + i;
              }
            }
            return e.docString != null && e.hasOwnProperty("docString") && !c.isString(e.docString) ? "docString: string expected" : null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.NodeProto) return e;
            var r = new s.onnx.NodeProto();
            if (e.input) {
              if (!Array.isArray(e.input)) throw TypeError(".onnx.NodeProto.input: array expected");
              r.input = [];
              for (var i = 0; i < e.input.length; ++i) r.input[i] = String(e.input[i]);
            }
            if (e.output) {
              if (!Array.isArray(e.output)) throw TypeError(".onnx.NodeProto.output: array expected");
              for (r.output = [], i = 0; i < e.output.length; ++i) r.output[i] = String(e.output[i]);
            }
            if (e.name != null && (r.name = String(e.name)), e.opType != null && (r.opType = String(e.opType)), e.domain != null && (r.domain = String(e.domain)), e.attribute) {
              if (!Array.isArray(e.attribute)) throw TypeError(".onnx.NodeProto.attribute: array expected");
              for (r.attribute = [], i = 0; i < e.attribute.length; ++i) {
                if (typeof e.attribute[i] != "object") throw TypeError(".onnx.NodeProto.attribute: object expected");
                r.attribute[i] = s.onnx.AttributeProto.fromObject(e.attribute[i]);
              }
            }
            return e.docString != null && (r.docString = String(e.docString)), r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.input = [], i.output = [], i.attribute = []), r.defaults && (i.name = "", i.opType = "", i.docString = "", i.domain = ""), e.input && e.input.length) {
              i.input = [];
              for (var p = 0; p < e.input.length; ++p) i.input[p] = e.input[p];
            }
            if (e.output && e.output.length) for (i.output = [], p = 0; p < e.output.length; ++p) i.output[p] = e.output[p];
            if (e.name != null && e.hasOwnProperty("name") && (i.name = e.name), e.opType != null && e.hasOwnProperty("opType") && (i.opType = e.opType), e.attribute && e.attribute.length) for (i.attribute = [], p = 0; p < e.attribute.length; ++p) i.attribute[p] = s.onnx.AttributeProto.toObject(e.attribute[p], r);
            return e.docString != null && e.hasOwnProperty("docString") && (i.docString = e.docString), e.domain != null && e.hasOwnProperty("domain") && (i.domain = e.domain), i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h.ModelProto = (function() {
          function t(e) {
            if (this.opsetImport = [], this.metadataProps = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.irVersion = c.Long ? c.Long.fromBits(0, 0, !1) : 0, t.prototype.opsetImport = c.emptyArray, t.prototype.producerName = "", t.prototype.producerVersion = "", t.prototype.domain = "", t.prototype.modelVersion = c.Long ? c.Long.fromBits(0, 0, !1) : 0, t.prototype.docString = "", t.prototype.graph = null, t.prototype.metadataProps = c.emptyArray, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.irVersion != null && e.hasOwnProperty("irVersion") && r.uint32(8).int64(e.irVersion), e.producerName != null && e.hasOwnProperty("producerName") && r.uint32(18).string(e.producerName), e.producerVersion != null && e.hasOwnProperty("producerVersion") && r.uint32(26).string(e.producerVersion), e.domain != null && e.hasOwnProperty("domain") && r.uint32(34).string(e.domain), e.modelVersion != null && e.hasOwnProperty("modelVersion") && r.uint32(40).int64(e.modelVersion), e.docString != null && e.hasOwnProperty("docString") && r.uint32(50).string(e.docString), e.graph != null && e.hasOwnProperty("graph") && s.onnx.GraphProto.encode(e.graph, r.uint32(58).fork()).ldelim(), e.opsetImport != null && e.opsetImport.length) for (var i = 0; i < e.opsetImport.length; ++i) s.onnx.OperatorSetIdProto.encode(e.opsetImport[i], r.uint32(66).fork()).ldelim();
            if (e.metadataProps != null && e.metadataProps.length) for (i = 0; i < e.metadataProps.length; ++i) s.onnx.StringStringEntryProto.encode(e.metadataProps[i], r.uint32(114).fork()).ldelim();
            return r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.ModelProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.irVersion = e.int64();
                  break;
                case 8:
                  p.opsetImport && p.opsetImport.length || (p.opsetImport = []), p.opsetImport.push(s.onnx.OperatorSetIdProto.decode(e, e.uint32()));
                  break;
                case 2:
                  p.producerName = e.string();
                  break;
                case 3:
                  p.producerVersion = e.string();
                  break;
                case 4:
                  p.domain = e.string();
                  break;
                case 5:
                  p.modelVersion = e.int64();
                  break;
                case 6:
                  p.docString = e.string();
                  break;
                case 7:
                  p.graph = s.onnx.GraphProto.decode(e, e.uint32());
                  break;
                case 14:
                  p.metadataProps && p.metadataProps.length || (p.metadataProps = []), p.metadataProps.push(s.onnx.StringStringEntryProto.decode(e, e.uint32()));
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.irVersion != null && e.hasOwnProperty("irVersion") && !(c.isInteger(e.irVersion) || e.irVersion && c.isInteger(e.irVersion.low) && c.isInteger(e.irVersion.high))) return "irVersion: integer|Long expected";
            if (e.opsetImport != null && e.hasOwnProperty("opsetImport")) {
              if (!Array.isArray(e.opsetImport)) return "opsetImport: array expected";
              for (var r = 0; r < e.opsetImport.length; ++r) if (i = s.onnx.OperatorSetIdProto.verify(e.opsetImport[r])) return "opsetImport." + i;
            }
            if (e.producerName != null && e.hasOwnProperty("producerName") && !c.isString(e.producerName)) return "producerName: string expected";
            if (e.producerVersion != null && e.hasOwnProperty("producerVersion") && !c.isString(e.producerVersion)) return "producerVersion: string expected";
            if (e.domain != null && e.hasOwnProperty("domain") && !c.isString(e.domain)) return "domain: string expected";
            if (e.modelVersion != null && e.hasOwnProperty("modelVersion") && !(c.isInteger(e.modelVersion) || e.modelVersion && c.isInteger(e.modelVersion.low) && c.isInteger(e.modelVersion.high))) return "modelVersion: integer|Long expected";
            if (e.docString != null && e.hasOwnProperty("docString") && !c.isString(e.docString)) return "docString: string expected";
            if (e.graph != null && e.hasOwnProperty("graph") && (i = s.onnx.GraphProto.verify(e.graph))) return "graph." + i;
            if (e.metadataProps != null && e.hasOwnProperty("metadataProps")) {
              if (!Array.isArray(e.metadataProps)) return "metadataProps: array expected";
              for (r = 0; r < e.metadataProps.length; ++r) {
                var i;
                if (i = s.onnx.StringStringEntryProto.verify(e.metadataProps[r])) return "metadataProps." + i;
              }
            }
            return null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.ModelProto) return e;
            var r = new s.onnx.ModelProto();
            if (e.irVersion != null && (c.Long ? (r.irVersion = c.Long.fromValue(e.irVersion)).unsigned = !1 : typeof e.irVersion == "string" ? r.irVersion = parseInt(e.irVersion, 10) : typeof e.irVersion == "number" ? r.irVersion = e.irVersion : typeof e.irVersion == "object" && (r.irVersion = new c.LongBits(e.irVersion.low >>> 0, e.irVersion.high >>> 0).toNumber())), e.opsetImport) {
              if (!Array.isArray(e.opsetImport)) throw TypeError(".onnx.ModelProto.opsetImport: array expected");
              r.opsetImport = [];
              for (var i = 0; i < e.opsetImport.length; ++i) {
                if (typeof e.opsetImport[i] != "object") throw TypeError(".onnx.ModelProto.opsetImport: object expected");
                r.opsetImport[i] = s.onnx.OperatorSetIdProto.fromObject(e.opsetImport[i]);
              }
            }
            if (e.producerName != null && (r.producerName = String(e.producerName)), e.producerVersion != null && (r.producerVersion = String(e.producerVersion)), e.domain != null && (r.domain = String(e.domain)), e.modelVersion != null && (c.Long ? (r.modelVersion = c.Long.fromValue(e.modelVersion)).unsigned = !1 : typeof e.modelVersion == "string" ? r.modelVersion = parseInt(e.modelVersion, 10) : typeof e.modelVersion == "number" ? r.modelVersion = e.modelVersion : typeof e.modelVersion == "object" && (r.modelVersion = new c.LongBits(e.modelVersion.low >>> 0, e.modelVersion.high >>> 0).toNumber())), e.docString != null && (r.docString = String(e.docString)), e.graph != null) {
              if (typeof e.graph != "object") throw TypeError(".onnx.ModelProto.graph: object expected");
              r.graph = s.onnx.GraphProto.fromObject(e.graph);
            }
            if (e.metadataProps) {
              if (!Array.isArray(e.metadataProps)) throw TypeError(".onnx.ModelProto.metadataProps: array expected");
              for (r.metadataProps = [], i = 0; i < e.metadataProps.length; ++i) {
                if (typeof e.metadataProps[i] != "object") throw TypeError(".onnx.ModelProto.metadataProps: object expected");
                r.metadataProps[i] = s.onnx.StringStringEntryProto.fromObject(e.metadataProps[i]);
              }
            }
            return r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.opsetImport = [], i.metadataProps = []), r.defaults) {
              if (c.Long) {
                var p = new c.Long(0, 0, !1);
                i.irVersion = r.longs === String ? p.toString() : r.longs === Number ? p.toNumber() : p;
              } else i.irVersion = r.longs === String ? "0" : 0;
              i.producerName = "", i.producerVersion = "", i.domain = "", c.Long ? (p = new c.Long(0, 0, !1), i.modelVersion = r.longs === String ? p.toString() : r.longs === Number ? p.toNumber() : p) : i.modelVersion = r.longs === String ? "0" : 0, i.docString = "", i.graph = null;
            }
            if (e.irVersion != null && e.hasOwnProperty("irVersion") && (typeof e.irVersion == "number" ? i.irVersion = r.longs === String ? String(e.irVersion) : e.irVersion : i.irVersion = r.longs === String ? c.Long.prototype.toString.call(e.irVersion) : r.longs === Number ? new c.LongBits(e.irVersion.low >>> 0, e.irVersion.high >>> 0).toNumber() : e.irVersion), e.producerName != null && e.hasOwnProperty("producerName") && (i.producerName = e.producerName), e.producerVersion != null && e.hasOwnProperty("producerVersion") && (i.producerVersion = e.producerVersion), e.domain != null && e.hasOwnProperty("domain") && (i.domain = e.domain), e.modelVersion != null && e.hasOwnProperty("modelVersion") && (typeof e.modelVersion == "number" ? i.modelVersion = r.longs === String ? String(e.modelVersion) : e.modelVersion : i.modelVersion = r.longs === String ? c.Long.prototype.toString.call(e.modelVersion) : r.longs === Number ? new c.LongBits(e.modelVersion.low >>> 0, e.modelVersion.high >>> 0).toNumber() : e.modelVersion), e.docString != null && e.hasOwnProperty("docString") && (i.docString = e.docString), e.graph != null && e.hasOwnProperty("graph") && (i.graph = s.onnx.GraphProto.toObject(e.graph, r)), e.opsetImport && e.opsetImport.length) {
              i.opsetImport = [];
              for (var m = 0; m < e.opsetImport.length; ++m) i.opsetImport[m] = s.onnx.OperatorSetIdProto.toObject(e.opsetImport[m], r);
            }
            if (e.metadataProps && e.metadataProps.length) for (i.metadataProps = [], m = 0; m < e.metadataProps.length; ++m) i.metadataProps[m] = s.onnx.StringStringEntryProto.toObject(e.metadataProps[m], r);
            return i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h.StringStringEntryProto = (function() {
          function t(e) {
            if (e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.key = "", t.prototype.value = "", t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            return r || (r = g.create()), e.key != null && e.hasOwnProperty("key") && r.uint32(10).string(e.key), e.value != null && e.hasOwnProperty("value") && r.uint32(18).string(e.value), r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.StringStringEntryProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.key = e.string();
                  break;
                case 2:
                  p.value = e.string();
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            return typeof e != "object" || e === null ? "object expected" : e.key != null && e.hasOwnProperty("key") && !c.isString(e.key) ? "key: string expected" : e.value != null && e.hasOwnProperty("value") && !c.isString(e.value) ? "value: string expected" : null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.StringStringEntryProto) return e;
            var r = new s.onnx.StringStringEntryProto();
            return e.key != null && (r.key = String(e.key)), e.value != null && (r.value = String(e.value)), r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            return r.defaults && (i.key = "", i.value = ""), e.key != null && e.hasOwnProperty("key") && (i.key = e.key), e.value != null && e.hasOwnProperty("value") && (i.value = e.value), i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h.TensorAnnotation = (function() {
          function t(e) {
            if (this.quantParameterTensorNames = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.tensorName = "", t.prototype.quantParameterTensorNames = c.emptyArray, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.tensorName != null && e.hasOwnProperty("tensorName") && r.uint32(10).string(e.tensorName), e.quantParameterTensorNames != null && e.quantParameterTensorNames.length) for (var i = 0; i < e.quantParameterTensorNames.length; ++i) s.onnx.StringStringEntryProto.encode(e.quantParameterTensorNames[i], r.uint32(18).fork()).ldelim();
            return r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.TensorAnnotation(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.tensorName = e.string();
                  break;
                case 2:
                  p.quantParameterTensorNames && p.quantParameterTensorNames.length || (p.quantParameterTensorNames = []), p.quantParameterTensorNames.push(s.onnx.StringStringEntryProto.decode(e, e.uint32()));
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.tensorName != null && e.hasOwnProperty("tensorName") && !c.isString(e.tensorName)) return "tensorName: string expected";
            if (e.quantParameterTensorNames != null && e.hasOwnProperty("quantParameterTensorNames")) {
              if (!Array.isArray(e.quantParameterTensorNames)) return "quantParameterTensorNames: array expected";
              for (var r = 0; r < e.quantParameterTensorNames.length; ++r) {
                var i = s.onnx.StringStringEntryProto.verify(e.quantParameterTensorNames[r]);
                if (i) return "quantParameterTensorNames." + i;
              }
            }
            return null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.TensorAnnotation) return e;
            var r = new s.onnx.TensorAnnotation();
            if (e.tensorName != null && (r.tensorName = String(e.tensorName)), e.quantParameterTensorNames) {
              if (!Array.isArray(e.quantParameterTensorNames)) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");
              r.quantParameterTensorNames = [];
              for (var i = 0; i < e.quantParameterTensorNames.length; ++i) {
                if (typeof e.quantParameterTensorNames[i] != "object") throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");
                r.quantParameterTensorNames[i] = s.onnx.StringStringEntryProto.fromObject(e.quantParameterTensorNames[i]);
              }
            }
            return r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.quantParameterTensorNames = []), r.defaults && (i.tensorName = ""), e.tensorName != null && e.hasOwnProperty("tensorName") && (i.tensorName = e.tensorName), e.quantParameterTensorNames && e.quantParameterTensorNames.length) {
              i.quantParameterTensorNames = [];
              for (var p = 0; p < e.quantParameterTensorNames.length; ++p) i.quantParameterTensorNames[p] = s.onnx.StringStringEntryProto.toObject(e.quantParameterTensorNames[p], r);
            }
            return i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h.GraphProto = (function() {
          function t(e) {
            if (this.node = [], this.initializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.node = c.emptyArray, t.prototype.name = "", t.prototype.initializer = c.emptyArray, t.prototype.docString = "", t.prototype.input = c.emptyArray, t.prototype.output = c.emptyArray, t.prototype.valueInfo = c.emptyArray, t.prototype.quantizationAnnotation = c.emptyArray, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.node != null && e.node.length) for (var i = 0; i < e.node.length; ++i) s.onnx.NodeProto.encode(e.node[i], r.uint32(10).fork()).ldelim();
            if (e.name != null && e.hasOwnProperty("name") && r.uint32(18).string(e.name), e.initializer != null && e.initializer.length) for (i = 0; i < e.initializer.length; ++i) s.onnx.TensorProto.encode(e.initializer[i], r.uint32(42).fork()).ldelim();
            if (e.docString != null && e.hasOwnProperty("docString") && r.uint32(82).string(e.docString), e.input != null && e.input.length) for (i = 0; i < e.input.length; ++i) s.onnx.ValueInfoProto.encode(e.input[i], r.uint32(90).fork()).ldelim();
            if (e.output != null && e.output.length) for (i = 0; i < e.output.length; ++i) s.onnx.ValueInfoProto.encode(e.output[i], r.uint32(98).fork()).ldelim();
            if (e.valueInfo != null && e.valueInfo.length) for (i = 0; i < e.valueInfo.length; ++i) s.onnx.ValueInfoProto.encode(e.valueInfo[i], r.uint32(106).fork()).ldelim();
            if (e.quantizationAnnotation != null && e.quantizationAnnotation.length) for (i = 0; i < e.quantizationAnnotation.length; ++i) s.onnx.TensorAnnotation.encode(e.quantizationAnnotation[i], r.uint32(114).fork()).ldelim();
            return r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.GraphProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.node && p.node.length || (p.node = []), p.node.push(s.onnx.NodeProto.decode(e, e.uint32()));
                  break;
                case 2:
                  p.name = e.string();
                  break;
                case 5:
                  p.initializer && p.initializer.length || (p.initializer = []), p.initializer.push(s.onnx.TensorProto.decode(e, e.uint32()));
                  break;
                case 10:
                  p.docString = e.string();
                  break;
                case 11:
                  p.input && p.input.length || (p.input = []), p.input.push(s.onnx.ValueInfoProto.decode(e, e.uint32()));
                  break;
                case 12:
                  p.output && p.output.length || (p.output = []), p.output.push(s.onnx.ValueInfoProto.decode(e, e.uint32()));
                  break;
                case 13:
                  p.valueInfo && p.valueInfo.length || (p.valueInfo = []), p.valueInfo.push(s.onnx.ValueInfoProto.decode(e, e.uint32()));
                  break;
                case 14:
                  p.quantizationAnnotation && p.quantizationAnnotation.length || (p.quantizationAnnotation = []), p.quantizationAnnotation.push(s.onnx.TensorAnnotation.decode(e, e.uint32()));
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.node != null && e.hasOwnProperty("node")) {
              if (!Array.isArray(e.node)) return "node: array expected";
              for (var r = 0; r < e.node.length; ++r) if (i = s.onnx.NodeProto.verify(e.node[r])) return "node." + i;
            }
            if (e.name != null && e.hasOwnProperty("name") && !c.isString(e.name)) return "name: string expected";
            if (e.initializer != null && e.hasOwnProperty("initializer")) {
              if (!Array.isArray(e.initializer)) return "initializer: array expected";
              for (r = 0; r < e.initializer.length; ++r) if (i = s.onnx.TensorProto.verify(e.initializer[r])) return "initializer." + i;
            }
            if (e.docString != null && e.hasOwnProperty("docString") && !c.isString(e.docString)) return "docString: string expected";
            if (e.input != null && e.hasOwnProperty("input")) {
              if (!Array.isArray(e.input)) return "input: array expected";
              for (r = 0; r < e.input.length; ++r) if (i = s.onnx.ValueInfoProto.verify(e.input[r])) return "input." + i;
            }
            if (e.output != null && e.hasOwnProperty("output")) {
              if (!Array.isArray(e.output)) return "output: array expected";
              for (r = 0; r < e.output.length; ++r) if (i = s.onnx.ValueInfoProto.verify(e.output[r])) return "output." + i;
            }
            if (e.valueInfo != null && e.hasOwnProperty("valueInfo")) {
              if (!Array.isArray(e.valueInfo)) return "valueInfo: array expected";
              for (r = 0; r < e.valueInfo.length; ++r) if (i = s.onnx.ValueInfoProto.verify(e.valueInfo[r])) return "valueInfo." + i;
            }
            if (e.quantizationAnnotation != null && e.hasOwnProperty("quantizationAnnotation")) {
              if (!Array.isArray(e.quantizationAnnotation)) return "quantizationAnnotation: array expected";
              for (r = 0; r < e.quantizationAnnotation.length; ++r) {
                var i;
                if (i = s.onnx.TensorAnnotation.verify(e.quantizationAnnotation[r])) return "quantizationAnnotation." + i;
              }
            }
            return null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.GraphProto) return e;
            var r = new s.onnx.GraphProto();
            if (e.node) {
              if (!Array.isArray(e.node)) throw TypeError(".onnx.GraphProto.node: array expected");
              r.node = [];
              for (var i = 0; i < e.node.length; ++i) {
                if (typeof e.node[i] != "object") throw TypeError(".onnx.GraphProto.node: object expected");
                r.node[i] = s.onnx.NodeProto.fromObject(e.node[i]);
              }
            }
            if (e.name != null && (r.name = String(e.name)), e.initializer) {
              if (!Array.isArray(e.initializer)) throw TypeError(".onnx.GraphProto.initializer: array expected");
              for (r.initializer = [], i = 0; i < e.initializer.length; ++i) {
                if (typeof e.initializer[i] != "object") throw TypeError(".onnx.GraphProto.initializer: object expected");
                r.initializer[i] = s.onnx.TensorProto.fromObject(e.initializer[i]);
              }
            }
            if (e.docString != null && (r.docString = String(e.docString)), e.input) {
              if (!Array.isArray(e.input)) throw TypeError(".onnx.GraphProto.input: array expected");
              for (r.input = [], i = 0; i < e.input.length; ++i) {
                if (typeof e.input[i] != "object") throw TypeError(".onnx.GraphProto.input: object expected");
                r.input[i] = s.onnx.ValueInfoProto.fromObject(e.input[i]);
              }
            }
            if (e.output) {
              if (!Array.isArray(e.output)) throw TypeError(".onnx.GraphProto.output: array expected");
              for (r.output = [], i = 0; i < e.output.length; ++i) {
                if (typeof e.output[i] != "object") throw TypeError(".onnx.GraphProto.output: object expected");
                r.output[i] = s.onnx.ValueInfoProto.fromObject(e.output[i]);
              }
            }
            if (e.valueInfo) {
              if (!Array.isArray(e.valueInfo)) throw TypeError(".onnx.GraphProto.valueInfo: array expected");
              for (r.valueInfo = [], i = 0; i < e.valueInfo.length; ++i) {
                if (typeof e.valueInfo[i] != "object") throw TypeError(".onnx.GraphProto.valueInfo: object expected");
                r.valueInfo[i] = s.onnx.ValueInfoProto.fromObject(e.valueInfo[i]);
              }
            }
            if (e.quantizationAnnotation) {
              if (!Array.isArray(e.quantizationAnnotation)) throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");
              for (r.quantizationAnnotation = [], i = 0; i < e.quantizationAnnotation.length; ++i) {
                if (typeof e.quantizationAnnotation[i] != "object") throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");
                r.quantizationAnnotation[i] = s.onnx.TensorAnnotation.fromObject(e.quantizationAnnotation[i]);
              }
            }
            return r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.node = [], i.initializer = [], i.input = [], i.output = [], i.valueInfo = [], i.quantizationAnnotation = []), r.defaults && (i.name = "", i.docString = ""), e.node && e.node.length) {
              i.node = [];
              for (var p = 0; p < e.node.length; ++p) i.node[p] = s.onnx.NodeProto.toObject(e.node[p], r);
            }
            if (e.name != null && e.hasOwnProperty("name") && (i.name = e.name), e.initializer && e.initializer.length) for (i.initializer = [], p = 0; p < e.initializer.length; ++p) i.initializer[p] = s.onnx.TensorProto.toObject(e.initializer[p], r);
            if (e.docString != null && e.hasOwnProperty("docString") && (i.docString = e.docString), e.input && e.input.length) for (i.input = [], p = 0; p < e.input.length; ++p) i.input[p] = s.onnx.ValueInfoProto.toObject(e.input[p], r);
            if (e.output && e.output.length) for (i.output = [], p = 0; p < e.output.length; ++p) i.output[p] = s.onnx.ValueInfoProto.toObject(e.output[p], r);
            if (e.valueInfo && e.valueInfo.length) for (i.valueInfo = [], p = 0; p < e.valueInfo.length; ++p) i.valueInfo[p] = s.onnx.ValueInfoProto.toObject(e.valueInfo[p], r);
            if (e.quantizationAnnotation && e.quantizationAnnotation.length) for (i.quantizationAnnotation = [], p = 0; p < e.quantizationAnnotation.length; ++p) i.quantizationAnnotation[p] = s.onnx.TensorAnnotation.toObject(e.quantizationAnnotation[p], r);
            return i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h.TensorProto = (function() {
          function t(e) {
            if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.dims = c.emptyArray, t.prototype.dataType = 0, t.prototype.segment = null, t.prototype.floatData = c.emptyArray, t.prototype.int32Data = c.emptyArray, t.prototype.stringData = c.emptyArray, t.prototype.int64Data = c.emptyArray, t.prototype.name = "", t.prototype.docString = "", t.prototype.rawData = c.newBuffer([]), t.prototype.externalData = c.emptyArray, t.prototype.dataLocation = 0, t.prototype.doubleData = c.emptyArray, t.prototype.uint64Data = c.emptyArray, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.dims != null && e.dims.length) {
              r.uint32(10).fork();
              for (var i = 0; i < e.dims.length; ++i) r.int64(e.dims[i]);
              r.ldelim();
            }
            if (e.dataType != null && e.hasOwnProperty("dataType") && r.uint32(16).int32(e.dataType), e.segment != null && e.hasOwnProperty("segment") && s.onnx.TensorProto.Segment.encode(e.segment, r.uint32(26).fork()).ldelim(), e.floatData != null && e.floatData.length) {
              for (r.uint32(34).fork(), i = 0; i < e.floatData.length; ++i) r.float(e.floatData[i]);
              r.ldelim();
            }
            if (e.int32Data != null && e.int32Data.length) {
              for (r.uint32(42).fork(), i = 0; i < e.int32Data.length; ++i) r.int32(e.int32Data[i]);
              r.ldelim();
            }
            if (e.stringData != null && e.stringData.length) for (i = 0; i < e.stringData.length; ++i) r.uint32(50).bytes(e.stringData[i]);
            if (e.int64Data != null && e.int64Data.length) {
              for (r.uint32(58).fork(), i = 0; i < e.int64Data.length; ++i) r.int64(e.int64Data[i]);
              r.ldelim();
            }
            if (e.name != null && e.hasOwnProperty("name") && r.uint32(66).string(e.name), e.rawData != null && e.hasOwnProperty("rawData") && r.uint32(74).bytes(e.rawData), e.doubleData != null && e.doubleData.length) {
              for (r.uint32(82).fork(), i = 0; i < e.doubleData.length; ++i) r.double(e.doubleData[i]);
              r.ldelim();
            }
            if (e.uint64Data != null && e.uint64Data.length) {
              for (r.uint32(90).fork(), i = 0; i < e.uint64Data.length; ++i) r.uint64(e.uint64Data[i]);
              r.ldelim();
            }
            if (e.docString != null && e.hasOwnProperty("docString") && r.uint32(98).string(e.docString), e.externalData != null && e.externalData.length) for (i = 0; i < e.externalData.length; ++i) s.onnx.StringStringEntryProto.encode(e.externalData[i], r.uint32(106).fork()).ldelim();
            return e.dataLocation != null && e.hasOwnProperty("dataLocation") && r.uint32(112).int32(e.dataLocation), r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.TensorProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  if (p.dims && p.dims.length || (p.dims = []), (7 & m) == 2) for (var _ = e.uint32() + e.pos; e.pos < _; ) p.dims.push(e.int64());
                  else p.dims.push(e.int64());
                  break;
                case 2:
                  p.dataType = e.int32();
                  break;
                case 3:
                  p.segment = s.onnx.TensorProto.Segment.decode(e, e.uint32());
                  break;
                case 4:
                  if (p.floatData && p.floatData.length || (p.floatData = []), (7 & m) == 2) for (_ = e.uint32() + e.pos; e.pos < _; ) p.floatData.push(e.float());
                  else p.floatData.push(e.float());
                  break;
                case 5:
                  if (p.int32Data && p.int32Data.length || (p.int32Data = []), (7 & m) == 2) for (_ = e.uint32() + e.pos; e.pos < _; ) p.int32Data.push(e.int32());
                  else p.int32Data.push(e.int32());
                  break;
                case 6:
                  p.stringData && p.stringData.length || (p.stringData = []), p.stringData.push(e.bytes());
                  break;
                case 7:
                  if (p.int64Data && p.int64Data.length || (p.int64Data = []), (7 & m) == 2) for (_ = e.uint32() + e.pos; e.pos < _; ) p.int64Data.push(e.int64());
                  else p.int64Data.push(e.int64());
                  break;
                case 8:
                  p.name = e.string();
                  break;
                case 12:
                  p.docString = e.string();
                  break;
                case 9:
                  p.rawData = e.bytes();
                  break;
                case 13:
                  p.externalData && p.externalData.length || (p.externalData = []), p.externalData.push(s.onnx.StringStringEntryProto.decode(e, e.uint32()));
                  break;
                case 14:
                  p.dataLocation = e.int32();
                  break;
                case 10:
                  if (p.doubleData && p.doubleData.length || (p.doubleData = []), (7 & m) == 2) for (_ = e.uint32() + e.pos; e.pos < _; ) p.doubleData.push(e.double());
                  else p.doubleData.push(e.double());
                  break;
                case 11:
                  if (p.uint64Data && p.uint64Data.length || (p.uint64Data = []), (7 & m) == 2) for (_ = e.uint32() + e.pos; e.pos < _; ) p.uint64Data.push(e.uint64());
                  else p.uint64Data.push(e.uint64());
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.dims != null && e.hasOwnProperty("dims")) {
              if (!Array.isArray(e.dims)) return "dims: array expected";
              for (var r = 0; r < e.dims.length; ++r) if (!(c.isInteger(e.dims[r]) || e.dims[r] && c.isInteger(e.dims[r].low) && c.isInteger(e.dims[r].high))) return "dims: integer|Long[] expected";
            }
            if (e.dataType != null && e.hasOwnProperty("dataType") && !c.isInteger(e.dataType)) return "dataType: integer expected";
            if (e.segment != null && e.hasOwnProperty("segment") && (i = s.onnx.TensorProto.Segment.verify(e.segment))) return "segment." + i;
            if (e.floatData != null && e.hasOwnProperty("floatData")) {
              if (!Array.isArray(e.floatData)) return "floatData: array expected";
              for (r = 0; r < e.floatData.length; ++r) if (typeof e.floatData[r] != "number") return "floatData: number[] expected";
            }
            if (e.int32Data != null && e.hasOwnProperty("int32Data")) {
              if (!Array.isArray(e.int32Data)) return "int32Data: array expected";
              for (r = 0; r < e.int32Data.length; ++r) if (!c.isInteger(e.int32Data[r])) return "int32Data: integer[] expected";
            }
            if (e.stringData != null && e.hasOwnProperty("stringData")) {
              if (!Array.isArray(e.stringData)) return "stringData: array expected";
              for (r = 0; r < e.stringData.length; ++r) if (!(e.stringData[r] && typeof e.stringData[r].length == "number" || c.isString(e.stringData[r]))) return "stringData: buffer[] expected";
            }
            if (e.int64Data != null && e.hasOwnProperty("int64Data")) {
              if (!Array.isArray(e.int64Data)) return "int64Data: array expected";
              for (r = 0; r < e.int64Data.length; ++r) if (!(c.isInteger(e.int64Data[r]) || e.int64Data[r] && c.isInteger(e.int64Data[r].low) && c.isInteger(e.int64Data[r].high))) return "int64Data: integer|Long[] expected";
            }
            if (e.name != null && e.hasOwnProperty("name") && !c.isString(e.name)) return "name: string expected";
            if (e.docString != null && e.hasOwnProperty("docString") && !c.isString(e.docString)) return "docString: string expected";
            if (e.rawData != null && e.hasOwnProperty("rawData") && !(e.rawData && typeof e.rawData.length == "number" || c.isString(e.rawData))) return "rawData: buffer expected";
            if (e.externalData != null && e.hasOwnProperty("externalData")) {
              if (!Array.isArray(e.externalData)) return "externalData: array expected";
              for (r = 0; r < e.externalData.length; ++r) {
                var i;
                if (i = s.onnx.StringStringEntryProto.verify(e.externalData[r])) return "externalData." + i;
              }
            }
            if (e.dataLocation != null && e.hasOwnProperty("dataLocation")) switch (e.dataLocation) {
              default:
                return "dataLocation: enum value expected";
              case 0:
              case 1:
            }
            if (e.doubleData != null && e.hasOwnProperty("doubleData")) {
              if (!Array.isArray(e.doubleData)) return "doubleData: array expected";
              for (r = 0; r < e.doubleData.length; ++r) if (typeof e.doubleData[r] != "number") return "doubleData: number[] expected";
            }
            if (e.uint64Data != null && e.hasOwnProperty("uint64Data")) {
              if (!Array.isArray(e.uint64Data)) return "uint64Data: array expected";
              for (r = 0; r < e.uint64Data.length; ++r) if (!(c.isInteger(e.uint64Data[r]) || e.uint64Data[r] && c.isInteger(e.uint64Data[r].low) && c.isInteger(e.uint64Data[r].high))) return "uint64Data: integer|Long[] expected";
            }
            return null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.TensorProto) return e;
            var r = new s.onnx.TensorProto();
            if (e.dims) {
              if (!Array.isArray(e.dims)) throw TypeError(".onnx.TensorProto.dims: array expected");
              r.dims = [];
              for (var i = 0; i < e.dims.length; ++i) c.Long ? (r.dims[i] = c.Long.fromValue(e.dims[i])).unsigned = !1 : typeof e.dims[i] == "string" ? r.dims[i] = parseInt(e.dims[i], 10) : typeof e.dims[i] == "number" ? r.dims[i] = e.dims[i] : typeof e.dims[i] == "object" && (r.dims[i] = new c.LongBits(e.dims[i].low >>> 0, e.dims[i].high >>> 0).toNumber());
            }
            if (e.dataType != null && (r.dataType = 0 | e.dataType), e.segment != null) {
              if (typeof e.segment != "object") throw TypeError(".onnx.TensorProto.segment: object expected");
              r.segment = s.onnx.TensorProto.Segment.fromObject(e.segment);
            }
            if (e.floatData) {
              if (!Array.isArray(e.floatData)) throw TypeError(".onnx.TensorProto.floatData: array expected");
              for (r.floatData = [], i = 0; i < e.floatData.length; ++i) r.floatData[i] = Number(e.floatData[i]);
            }
            if (e.int32Data) {
              if (!Array.isArray(e.int32Data)) throw TypeError(".onnx.TensorProto.int32Data: array expected");
              for (r.int32Data = [], i = 0; i < e.int32Data.length; ++i) r.int32Data[i] = 0 | e.int32Data[i];
            }
            if (e.stringData) {
              if (!Array.isArray(e.stringData)) throw TypeError(".onnx.TensorProto.stringData: array expected");
              for (r.stringData = [], i = 0; i < e.stringData.length; ++i) typeof e.stringData[i] == "string" ? c.base64.decode(e.stringData[i], r.stringData[i] = c.newBuffer(c.base64.length(e.stringData[i])), 0) : e.stringData[i].length && (r.stringData[i] = e.stringData[i]);
            }
            if (e.int64Data) {
              if (!Array.isArray(e.int64Data)) throw TypeError(".onnx.TensorProto.int64Data: array expected");
              for (r.int64Data = [], i = 0; i < e.int64Data.length; ++i) c.Long ? (r.int64Data[i] = c.Long.fromValue(e.int64Data[i])).unsigned = !1 : typeof e.int64Data[i] == "string" ? r.int64Data[i] = parseInt(e.int64Data[i], 10) : typeof e.int64Data[i] == "number" ? r.int64Data[i] = e.int64Data[i] : typeof e.int64Data[i] == "object" && (r.int64Data[i] = new c.LongBits(e.int64Data[i].low >>> 0, e.int64Data[i].high >>> 0).toNumber());
            }
            if (e.name != null && (r.name = String(e.name)), e.docString != null && (r.docString = String(e.docString)), e.rawData != null && (typeof e.rawData == "string" ? c.base64.decode(e.rawData, r.rawData = c.newBuffer(c.base64.length(e.rawData)), 0) : e.rawData.length && (r.rawData = e.rawData)), e.externalData) {
              if (!Array.isArray(e.externalData)) throw TypeError(".onnx.TensorProto.externalData: array expected");
              for (r.externalData = [], i = 0; i < e.externalData.length; ++i) {
                if (typeof e.externalData[i] != "object") throw TypeError(".onnx.TensorProto.externalData: object expected");
                r.externalData[i] = s.onnx.StringStringEntryProto.fromObject(e.externalData[i]);
              }
            }
            switch (e.dataLocation) {
              case "DEFAULT":
              case 0:
                r.dataLocation = 0;
                break;
              case "EXTERNAL":
              case 1:
                r.dataLocation = 1;
            }
            if (e.doubleData) {
              if (!Array.isArray(e.doubleData)) throw TypeError(".onnx.TensorProto.doubleData: array expected");
              for (r.doubleData = [], i = 0; i < e.doubleData.length; ++i) r.doubleData[i] = Number(e.doubleData[i]);
            }
            if (e.uint64Data) {
              if (!Array.isArray(e.uint64Data)) throw TypeError(".onnx.TensorProto.uint64Data: array expected");
              for (r.uint64Data = [], i = 0; i < e.uint64Data.length; ++i) c.Long ? (r.uint64Data[i] = c.Long.fromValue(e.uint64Data[i])).unsigned = !0 : typeof e.uint64Data[i] == "string" ? r.uint64Data[i] = parseInt(e.uint64Data[i], 10) : typeof e.uint64Data[i] == "number" ? r.uint64Data[i] = e.uint64Data[i] : typeof e.uint64Data[i] == "object" && (r.uint64Data[i] = new c.LongBits(e.uint64Data[i].low >>> 0, e.uint64Data[i].high >>> 0).toNumber(!0));
            }
            return r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.dims = [], i.floatData = [], i.int32Data = [], i.stringData = [], i.int64Data = [], i.doubleData = [], i.uint64Data = [], i.externalData = []), r.defaults && (i.dataType = 0, i.segment = null, i.name = "", r.bytes === String ? i.rawData = "" : (i.rawData = [], r.bytes !== Array && (i.rawData = c.newBuffer(i.rawData))), i.docString = "", i.dataLocation = r.enums === String ? "DEFAULT" : 0), e.dims && e.dims.length) {
              i.dims = [];
              for (var p = 0; p < e.dims.length; ++p) typeof e.dims[p] == "number" ? i.dims[p] = r.longs === String ? String(e.dims[p]) : e.dims[p] : i.dims[p] = r.longs === String ? c.Long.prototype.toString.call(e.dims[p]) : r.longs === Number ? new c.LongBits(e.dims[p].low >>> 0, e.dims[p].high >>> 0).toNumber() : e.dims[p];
            }
            if (e.dataType != null && e.hasOwnProperty("dataType") && (i.dataType = e.dataType), e.segment != null && e.hasOwnProperty("segment") && (i.segment = s.onnx.TensorProto.Segment.toObject(e.segment, r)), e.floatData && e.floatData.length) for (i.floatData = [], p = 0; p < e.floatData.length; ++p) i.floatData[p] = r.json && !isFinite(e.floatData[p]) ? String(e.floatData[p]) : e.floatData[p];
            if (e.int32Data && e.int32Data.length) for (i.int32Data = [], p = 0; p < e.int32Data.length; ++p) i.int32Data[p] = e.int32Data[p];
            if (e.stringData && e.stringData.length) for (i.stringData = [], p = 0; p < e.stringData.length; ++p) i.stringData[p] = r.bytes === String ? c.base64.encode(e.stringData[p], 0, e.stringData[p].length) : r.bytes === Array ? Array.prototype.slice.call(e.stringData[p]) : e.stringData[p];
            if (e.int64Data && e.int64Data.length) for (i.int64Data = [], p = 0; p < e.int64Data.length; ++p) typeof e.int64Data[p] == "number" ? i.int64Data[p] = r.longs === String ? String(e.int64Data[p]) : e.int64Data[p] : i.int64Data[p] = r.longs === String ? c.Long.prototype.toString.call(e.int64Data[p]) : r.longs === Number ? new c.LongBits(e.int64Data[p].low >>> 0, e.int64Data[p].high >>> 0).toNumber() : e.int64Data[p];
            if (e.name != null && e.hasOwnProperty("name") && (i.name = e.name), e.rawData != null && e.hasOwnProperty("rawData") && (i.rawData = r.bytes === String ? c.base64.encode(e.rawData, 0, e.rawData.length) : r.bytes === Array ? Array.prototype.slice.call(e.rawData) : e.rawData), e.doubleData && e.doubleData.length) for (i.doubleData = [], p = 0; p < e.doubleData.length; ++p) i.doubleData[p] = r.json && !isFinite(e.doubleData[p]) ? String(e.doubleData[p]) : e.doubleData[p];
            if (e.uint64Data && e.uint64Data.length) for (i.uint64Data = [], p = 0; p < e.uint64Data.length; ++p) typeof e.uint64Data[p] == "number" ? i.uint64Data[p] = r.longs === String ? String(e.uint64Data[p]) : e.uint64Data[p] : i.uint64Data[p] = r.longs === String ? c.Long.prototype.toString.call(e.uint64Data[p]) : r.longs === Number ? new c.LongBits(e.uint64Data[p].low >>> 0, e.uint64Data[p].high >>> 0).toNumber(!0) : e.uint64Data[p];
            if (e.docString != null && e.hasOwnProperty("docString") && (i.docString = e.docString), e.externalData && e.externalData.length) for (i.externalData = [], p = 0; p < e.externalData.length; ++p) i.externalData[p] = s.onnx.StringStringEntryProto.toObject(e.externalData[p], r);
            return e.dataLocation != null && e.hasOwnProperty("dataLocation") && (i.dataLocation = r.enums === String ? s.onnx.TensorProto.DataLocation[e.dataLocation] : e.dataLocation), i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t.DataType = (function() {
            var e = {}, r = Object.create(e);
            return r[e[0] = "UNDEFINED"] = 0, r[e[1] = "FLOAT"] = 1, r[e[2] = "UINT8"] = 2, r[e[3] = "INT8"] = 3, r[e[4] = "UINT16"] = 4, r[e[5] = "INT16"] = 5, r[e[6] = "INT32"] = 6, r[e[7] = "INT64"] = 7, r[e[8] = "STRING"] = 8, r[e[9] = "BOOL"] = 9, r[e[10] = "FLOAT16"] = 10, r[e[11] = "DOUBLE"] = 11, r[e[12] = "UINT32"] = 12, r[e[13] = "UINT64"] = 13, r[e[14] = "COMPLEX64"] = 14, r[e[15] = "COMPLEX128"] = 15, r[e[16] = "BFLOAT16"] = 16, r;
          })(), t.Segment = (function() {
            function e(r) {
              if (r) for (var i = Object.keys(r), p = 0; p < i.length; ++p) r[i[p]] != null && (this[i[p]] = r[i[p]]);
            }
            return e.prototype.begin = c.Long ? c.Long.fromBits(0, 0, !1) : 0, e.prototype.end = c.Long ? c.Long.fromBits(0, 0, !1) : 0, e.create = function(r) {
              return new e(r);
            }, e.encode = function(r, i) {
              return i || (i = g.create()), r.begin != null && r.hasOwnProperty("begin") && i.uint32(8).int64(r.begin), r.end != null && r.hasOwnProperty("end") && i.uint32(16).int64(r.end), i;
            }, e.encodeDelimited = function(r, i) {
              return this.encode(r, i).ldelim();
            }, e.decode = function(r, i) {
              r instanceof f || (r = f.create(r));
              for (var p = i === void 0 ? r.len : r.pos + i, m = new s.onnx.TensorProto.Segment(); r.pos < p; ) {
                var _ = r.uint32();
                switch (_ >>> 3) {
                  case 1:
                    m.begin = r.int64();
                    break;
                  case 2:
                    m.end = r.int64();
                    break;
                  default:
                    r.skipType(7 & _);
                }
              }
              return m;
            }, e.decodeDelimited = function(r) {
              return r instanceof f || (r = new f(r)), this.decode(r, r.uint32());
            }, e.verify = function(r) {
              return typeof r != "object" || r === null ? "object expected" : r.begin != null && r.hasOwnProperty("begin") && !(c.isInteger(r.begin) || r.begin && c.isInteger(r.begin.low) && c.isInteger(r.begin.high)) ? "begin: integer|Long expected" : r.end != null && r.hasOwnProperty("end") && !(c.isInteger(r.end) || r.end && c.isInteger(r.end.low) && c.isInteger(r.end.high)) ? "end: integer|Long expected" : null;
            }, e.fromObject = function(r) {
              if (r instanceof s.onnx.TensorProto.Segment) return r;
              var i = new s.onnx.TensorProto.Segment();
              return r.begin != null && (c.Long ? (i.begin = c.Long.fromValue(r.begin)).unsigned = !1 : typeof r.begin == "string" ? i.begin = parseInt(r.begin, 10) : typeof r.begin == "number" ? i.begin = r.begin : typeof r.begin == "object" && (i.begin = new c.LongBits(r.begin.low >>> 0, r.begin.high >>> 0).toNumber())), r.end != null && (c.Long ? (i.end = c.Long.fromValue(r.end)).unsigned = !1 : typeof r.end == "string" ? i.end = parseInt(r.end, 10) : typeof r.end == "number" ? i.end = r.end : typeof r.end == "object" && (i.end = new c.LongBits(r.end.low >>> 0, r.end.high >>> 0).toNumber())), i;
            }, e.toObject = function(r, i) {
              i || (i = {});
              var p = {};
              if (i.defaults) {
                if (c.Long) {
                  var m = new c.Long(0, 0, !1);
                  p.begin = i.longs === String ? m.toString() : i.longs === Number ? m.toNumber() : m;
                } else p.begin = i.longs === String ? "0" : 0;
                c.Long ? (m = new c.Long(0, 0, !1), p.end = i.longs === String ? m.toString() : i.longs === Number ? m.toNumber() : m) : p.end = i.longs === String ? "0" : 0;
              }
              return r.begin != null && r.hasOwnProperty("begin") && (typeof r.begin == "number" ? p.begin = i.longs === String ? String(r.begin) : r.begin : p.begin = i.longs === String ? c.Long.prototype.toString.call(r.begin) : i.longs === Number ? new c.LongBits(r.begin.low >>> 0, r.begin.high >>> 0).toNumber() : r.begin), r.end != null && r.hasOwnProperty("end") && (typeof r.end == "number" ? p.end = i.longs === String ? String(r.end) : r.end : p.end = i.longs === String ? c.Long.prototype.toString.call(r.end) : i.longs === Number ? new c.LongBits(r.end.low >>> 0, r.end.high >>> 0).toNumber() : r.end), p;
            }, e.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, e;
          })(), t.DataLocation = (function() {
            var e = {}, r = Object.create(e);
            return r[e[0] = "DEFAULT"] = 0, r[e[1] = "EXTERNAL"] = 1, r;
          })(), t;
        })(), h.TensorShapeProto = (function() {
          function t(e) {
            if (this.dim = [], e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.dim = c.emptyArray, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            if (r || (r = g.create()), e.dim != null && e.dim.length) for (var i = 0; i < e.dim.length; ++i) s.onnx.TensorShapeProto.Dimension.encode(e.dim[i], r.uint32(10).fork()).ldelim();
            return r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.TensorShapeProto(); e.pos < i; ) {
              var m = e.uint32();
              m >>> 3 == 1 ? (p.dim && p.dim.length || (p.dim = []), p.dim.push(s.onnx.TensorShapeProto.Dimension.decode(e, e.uint32()))) : e.skipType(7 & m);
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            if (typeof e != "object" || e === null) return "object expected";
            if (e.dim != null && e.hasOwnProperty("dim")) {
              if (!Array.isArray(e.dim)) return "dim: array expected";
              for (var r = 0; r < e.dim.length; ++r) {
                var i = s.onnx.TensorShapeProto.Dimension.verify(e.dim[r]);
                if (i) return "dim." + i;
              }
            }
            return null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.TensorShapeProto) return e;
            var r = new s.onnx.TensorShapeProto();
            if (e.dim) {
              if (!Array.isArray(e.dim)) throw TypeError(".onnx.TensorShapeProto.dim: array expected");
              r.dim = [];
              for (var i = 0; i < e.dim.length; ++i) {
                if (typeof e.dim[i] != "object") throw TypeError(".onnx.TensorShapeProto.dim: object expected");
                r.dim[i] = s.onnx.TensorShapeProto.Dimension.fromObject(e.dim[i]);
              }
            }
            return r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if ((r.arrays || r.defaults) && (i.dim = []), e.dim && e.dim.length) {
              i.dim = [];
              for (var p = 0; p < e.dim.length; ++p) i.dim[p] = s.onnx.TensorShapeProto.Dimension.toObject(e.dim[p], r);
            }
            return i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t.Dimension = (function() {
            function e(i) {
              if (i) for (var p = Object.keys(i), m = 0; m < p.length; ++m) i[p[m]] != null && (this[p[m]] = i[p[m]]);
            }
            var r;
            return e.prototype.dimValue = c.Long ? c.Long.fromBits(0, 0, !1) : 0, e.prototype.dimParam = "", e.prototype.denotation = "", Object.defineProperty(e.prototype, "value", { get: c.oneOfGetter(r = ["dimValue", "dimParam"]), set: c.oneOfSetter(r) }), e.create = function(i) {
              return new e(i);
            }, e.encode = function(i, p) {
              return p || (p = g.create()), i.dimValue != null && i.hasOwnProperty("dimValue") && p.uint32(8).int64(i.dimValue), i.dimParam != null && i.hasOwnProperty("dimParam") && p.uint32(18).string(i.dimParam), i.denotation != null && i.hasOwnProperty("denotation") && p.uint32(26).string(i.denotation), p;
            }, e.encodeDelimited = function(i, p) {
              return this.encode(i, p).ldelim();
            }, e.decode = function(i, p) {
              i instanceof f || (i = f.create(i));
              for (var m = p === void 0 ? i.len : i.pos + p, _ = new s.onnx.TensorShapeProto.Dimension(); i.pos < m; ) {
                var b = i.uint32();
                switch (b >>> 3) {
                  case 1:
                    _.dimValue = i.int64();
                    break;
                  case 2:
                    _.dimParam = i.string();
                    break;
                  case 3:
                    _.denotation = i.string();
                    break;
                  default:
                    i.skipType(7 & b);
                }
              }
              return _;
            }, e.decodeDelimited = function(i) {
              return i instanceof f || (i = new f(i)), this.decode(i, i.uint32());
            }, e.verify = function(i) {
              if (typeof i != "object" || i === null) return "object expected";
              var p = {};
              if (i.dimValue != null && i.hasOwnProperty("dimValue") && (p.value = 1, !(c.isInteger(i.dimValue) || i.dimValue && c.isInteger(i.dimValue.low) && c.isInteger(i.dimValue.high)))) return "dimValue: integer|Long expected";
              if (i.dimParam != null && i.hasOwnProperty("dimParam")) {
                if (p.value === 1) return "value: multiple values";
                if (p.value = 1, !c.isString(i.dimParam)) return "dimParam: string expected";
              }
              return i.denotation != null && i.hasOwnProperty("denotation") && !c.isString(i.denotation) ? "denotation: string expected" : null;
            }, e.fromObject = function(i) {
              if (i instanceof s.onnx.TensorShapeProto.Dimension) return i;
              var p = new s.onnx.TensorShapeProto.Dimension();
              return i.dimValue != null && (c.Long ? (p.dimValue = c.Long.fromValue(i.dimValue)).unsigned = !1 : typeof i.dimValue == "string" ? p.dimValue = parseInt(i.dimValue, 10) : typeof i.dimValue == "number" ? p.dimValue = i.dimValue : typeof i.dimValue == "object" && (p.dimValue = new c.LongBits(i.dimValue.low >>> 0, i.dimValue.high >>> 0).toNumber())), i.dimParam != null && (p.dimParam = String(i.dimParam)), i.denotation != null && (p.denotation = String(i.denotation)), p;
            }, e.toObject = function(i, p) {
              p || (p = {});
              var m = {};
              return p.defaults && (m.denotation = ""), i.dimValue != null && i.hasOwnProperty("dimValue") && (typeof i.dimValue == "number" ? m.dimValue = p.longs === String ? String(i.dimValue) : i.dimValue : m.dimValue = p.longs === String ? c.Long.prototype.toString.call(i.dimValue) : p.longs === Number ? new c.LongBits(i.dimValue.low >>> 0, i.dimValue.high >>> 0).toNumber() : i.dimValue, p.oneofs && (m.value = "dimValue")), i.dimParam != null && i.hasOwnProperty("dimParam") && (m.dimParam = i.dimParam, p.oneofs && (m.value = "dimParam")), i.denotation != null && i.hasOwnProperty("denotation") && (m.denotation = i.denotation), m;
            }, e.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, e;
          })(), t;
        })(), h.TypeProto = (function() {
          function t(r) {
            if (r) for (var i = Object.keys(r), p = 0; p < i.length; ++p) r[i[p]] != null && (this[i[p]] = r[i[p]]);
          }
          var e;
          return t.prototype.tensorType = null, t.prototype.denotation = "", Object.defineProperty(t.prototype, "value", { get: c.oneOfGetter(e = ["tensorType"]), set: c.oneOfSetter(e) }), t.create = function(r) {
            return new t(r);
          }, t.encode = function(r, i) {
            return i || (i = g.create()), r.tensorType != null && r.hasOwnProperty("tensorType") && s.onnx.TypeProto.Tensor.encode(r.tensorType, i.uint32(10).fork()).ldelim(), r.denotation != null && r.hasOwnProperty("denotation") && i.uint32(50).string(r.denotation), i;
          }, t.encodeDelimited = function(r, i) {
            return this.encode(r, i).ldelim();
          }, t.decode = function(r, i) {
            r instanceof f || (r = f.create(r));
            for (var p = i === void 0 ? r.len : r.pos + i, m = new s.onnx.TypeProto(); r.pos < p; ) {
              var _ = r.uint32();
              switch (_ >>> 3) {
                case 1:
                  m.tensorType = s.onnx.TypeProto.Tensor.decode(r, r.uint32());
                  break;
                case 6:
                  m.denotation = r.string();
                  break;
                default:
                  r.skipType(7 & _);
              }
            }
            return m;
          }, t.decodeDelimited = function(r) {
            return r instanceof f || (r = new f(r)), this.decode(r, r.uint32());
          }, t.verify = function(r) {
            if (typeof r != "object" || r === null) return "object expected";
            if (r.tensorType != null && r.hasOwnProperty("tensorType")) {
              var i = s.onnx.TypeProto.Tensor.verify(r.tensorType);
              if (i) return "tensorType." + i;
            }
            return r.denotation != null && r.hasOwnProperty("denotation") && !c.isString(r.denotation) ? "denotation: string expected" : null;
          }, t.fromObject = function(r) {
            if (r instanceof s.onnx.TypeProto) return r;
            var i = new s.onnx.TypeProto();
            if (r.tensorType != null) {
              if (typeof r.tensorType != "object") throw TypeError(".onnx.TypeProto.tensorType: object expected");
              i.tensorType = s.onnx.TypeProto.Tensor.fromObject(r.tensorType);
            }
            return r.denotation != null && (i.denotation = String(r.denotation)), i;
          }, t.toObject = function(r, i) {
            i || (i = {});
            var p = {};
            return i.defaults && (p.denotation = ""), r.tensorType != null && r.hasOwnProperty("tensorType") && (p.tensorType = s.onnx.TypeProto.Tensor.toObject(r.tensorType, i), i.oneofs && (p.value = "tensorType")), r.denotation != null && r.hasOwnProperty("denotation") && (p.denotation = r.denotation), p;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t.Tensor = (function() {
            function r(i) {
              if (i) for (var p = Object.keys(i), m = 0; m < p.length; ++m) i[p[m]] != null && (this[p[m]] = i[p[m]]);
            }
            return r.prototype.elemType = 0, r.prototype.shape = null, r.create = function(i) {
              return new r(i);
            }, r.encode = function(i, p) {
              return p || (p = g.create()), i.elemType != null && i.hasOwnProperty("elemType") && p.uint32(8).int32(i.elemType), i.shape != null && i.hasOwnProperty("shape") && s.onnx.TensorShapeProto.encode(i.shape, p.uint32(18).fork()).ldelim(), p;
            }, r.encodeDelimited = function(i, p) {
              return this.encode(i, p).ldelim();
            }, r.decode = function(i, p) {
              i instanceof f || (i = f.create(i));
              for (var m = p === void 0 ? i.len : i.pos + p, _ = new s.onnx.TypeProto.Tensor(); i.pos < m; ) {
                var b = i.uint32();
                switch (b >>> 3) {
                  case 1:
                    _.elemType = i.int32();
                    break;
                  case 2:
                    _.shape = s.onnx.TensorShapeProto.decode(i, i.uint32());
                    break;
                  default:
                    i.skipType(7 & b);
                }
              }
              return _;
            }, r.decodeDelimited = function(i) {
              return i instanceof f || (i = new f(i)), this.decode(i, i.uint32());
            }, r.verify = function(i) {
              if (typeof i != "object" || i === null) return "object expected";
              if (i.elemType != null && i.hasOwnProperty("elemType") && !c.isInteger(i.elemType)) return "elemType: integer expected";
              if (i.shape != null && i.hasOwnProperty("shape")) {
                var p = s.onnx.TensorShapeProto.verify(i.shape);
                if (p) return "shape." + p;
              }
              return null;
            }, r.fromObject = function(i) {
              if (i instanceof s.onnx.TypeProto.Tensor) return i;
              var p = new s.onnx.TypeProto.Tensor();
              if (i.elemType != null && (p.elemType = 0 | i.elemType), i.shape != null) {
                if (typeof i.shape != "object") throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");
                p.shape = s.onnx.TensorShapeProto.fromObject(i.shape);
              }
              return p;
            }, r.toObject = function(i, p) {
              p || (p = {});
              var m = {};
              return p.defaults && (m.elemType = 0, m.shape = null), i.elemType != null && i.hasOwnProperty("elemType") && (m.elemType = i.elemType), i.shape != null && i.hasOwnProperty("shape") && (m.shape = s.onnx.TensorShapeProto.toObject(i.shape, p)), m;
            }, r.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, r;
          })(), t;
        })(), h.OperatorSetIdProto = (function() {
          function t(e) {
            if (e) for (var r = Object.keys(e), i = 0; i < r.length; ++i) e[r[i]] != null && (this[r[i]] = e[r[i]]);
          }
          return t.prototype.domain = "", t.prototype.version = c.Long ? c.Long.fromBits(0, 0, !1) : 0, t.create = function(e) {
            return new t(e);
          }, t.encode = function(e, r) {
            return r || (r = g.create()), e.domain != null && e.hasOwnProperty("domain") && r.uint32(10).string(e.domain), e.version != null && e.hasOwnProperty("version") && r.uint32(16).int64(e.version), r;
          }, t.encodeDelimited = function(e, r) {
            return this.encode(e, r).ldelim();
          }, t.decode = function(e, r) {
            e instanceof f || (e = f.create(e));
            for (var i = r === void 0 ? e.len : e.pos + r, p = new s.onnx.OperatorSetIdProto(); e.pos < i; ) {
              var m = e.uint32();
              switch (m >>> 3) {
                case 1:
                  p.domain = e.string();
                  break;
                case 2:
                  p.version = e.int64();
                  break;
                default:
                  e.skipType(7 & m);
              }
            }
            return p;
          }, t.decodeDelimited = function(e) {
            return e instanceof f || (e = new f(e)), this.decode(e, e.uint32());
          }, t.verify = function(e) {
            return typeof e != "object" || e === null ? "object expected" : e.domain != null && e.hasOwnProperty("domain") && !c.isString(e.domain) ? "domain: string expected" : e.version != null && e.hasOwnProperty("version") && !(c.isInteger(e.version) || e.version && c.isInteger(e.version.low) && c.isInteger(e.version.high)) ? "version: integer|Long expected" : null;
          }, t.fromObject = function(e) {
            if (e instanceof s.onnx.OperatorSetIdProto) return e;
            var r = new s.onnx.OperatorSetIdProto();
            return e.domain != null && (r.domain = String(e.domain)), e.version != null && (c.Long ? (r.version = c.Long.fromValue(e.version)).unsigned = !1 : typeof e.version == "string" ? r.version = parseInt(e.version, 10) : typeof e.version == "number" ? r.version = e.version : typeof e.version == "object" && (r.version = new c.LongBits(e.version.low >>> 0, e.version.high >>> 0).toNumber())), r;
          }, t.toObject = function(e, r) {
            r || (r = {});
            var i = {};
            if (r.defaults) if (i.domain = "", c.Long) {
              var p = new c.Long(0, 0, !1);
              i.version = r.longs === String ? p.toString() : r.longs === Number ? p.toNumber() : p;
            } else i.version = r.longs === String ? "0" : 0;
            return e.domain != null && e.hasOwnProperty("domain") && (i.domain = e.domain), e.version != null && e.hasOwnProperty("version") && (typeof e.version == "number" ? i.version = r.longs === String ? String(e.version) : e.version : i.version = r.longs === String ? c.Long.prototype.toString.call(e.version) : r.longs === Number ? new c.LongBits(e.version.low >>> 0, e.version.high >>> 0).toNumber() : e.version), i;
          }, t.prototype.toJSON = function() {
            return this.constructor.toObject(this, a.util.toJSONOptions);
          }, t;
        })(), h), d.exports = s;
      }, 2100: (d, n, o) => {
        d.exports = o(9482);
      }, 9482: (d, n, o) => {
        var u = n;
        function l() {
          u.util._configure(), u.Writer._configure(u.BufferWriter), u.Reader._configure(u.BufferReader);
        }
        u.build = "minimal", u.Writer = o(1173), u.BufferWriter = o(3155), u.Reader = o(1408), u.BufferReader = o(593), u.util = o(9693), u.rpc = o(5994), u.roots = o(5054), u.configure = l, l();
      }, 1408: (d, n, o) => {
        d.exports = g;
        var u, l = o(9693), h = l.LongBits, a = l.utf8;
        function f(p, m) {
          return RangeError("index out of range: " + p.pos + " + " + (m || 1) + " > " + p.len);
        }
        function g(p) {
          this.buf = p, this.pos = 0, this.len = p.length;
        }
        var c, s = typeof Uint8Array < "u" ? function(p) {
          if (p instanceof Uint8Array || Array.isArray(p)) return new g(p);
          throw Error("illegal buffer");
        } : function(p) {
          if (Array.isArray(p)) return new g(p);
          throw Error("illegal buffer");
        }, t = function() {
          return l.Buffer ? function(p) {
            return (g.create = function(m) {
              return l.Buffer.isBuffer(m) ? new u(m) : s(m);
            })(p);
          } : s;
        };
        function e() {
          var p = new h(0, 0), m = 0;
          if (!(this.len - this.pos > 4)) {
            for (; m < 3; ++m) {
              if (this.pos >= this.len) throw f(this);
              if (p.lo = (p.lo | (127 & this.buf[this.pos]) << 7 * m) >>> 0, this.buf[this.pos++] < 128) return p;
            }
            return p.lo = (p.lo | (127 & this.buf[this.pos++]) << 7 * m) >>> 0, p;
          }
          for (; m < 4; ++m) if (p.lo = (p.lo | (127 & this.buf[this.pos]) << 7 * m) >>> 0, this.buf[this.pos++] < 128) return p;
          if (p.lo = (p.lo | (127 & this.buf[this.pos]) << 28) >>> 0, p.hi = (p.hi | (127 & this.buf[this.pos]) >> 4) >>> 0, this.buf[this.pos++] < 128) return p;
          if (m = 0, this.len - this.pos > 4) {
            for (; m < 5; ++m) if (p.hi = (p.hi | (127 & this.buf[this.pos]) << 7 * m + 3) >>> 0, this.buf[this.pos++] < 128) return p;
          } else for (; m < 5; ++m) {
            if (this.pos >= this.len) throw f(this);
            if (p.hi = (p.hi | (127 & this.buf[this.pos]) << 7 * m + 3) >>> 0, this.buf[this.pos++] < 128) return p;
          }
          throw Error("invalid varint encoding");
        }
        function r(p, m) {
          return (p[m - 4] | p[m - 3] << 8 | p[m - 2] << 16 | p[m - 1] << 24) >>> 0;
        }
        function i() {
          if (this.pos + 8 > this.len) throw f(this, 8);
          return new h(r(this.buf, this.pos += 4), r(this.buf, this.pos += 4));
        }
        g.create = t(), g.prototype._slice = l.Array.prototype.subarray || l.Array.prototype.slice, g.prototype.uint32 = (c = 4294967295, function() {
          if (c = (127 & this.buf[this.pos]) >>> 0, this.buf[this.pos++] < 128 || (c = (c | (127 & this.buf[this.pos]) << 7) >>> 0, this.buf[this.pos++] < 128) || (c = (c | (127 & this.buf[this.pos]) << 14) >>> 0, this.buf[this.pos++] < 128) || (c = (c | (127 & this.buf[this.pos]) << 21) >>> 0, this.buf[this.pos++] < 128) || (c = (c | (15 & this.buf[this.pos]) << 28) >>> 0, this.buf[this.pos++] < 128)) return c;
          if ((this.pos += 5) > this.len) throw this.pos = this.len, f(this, 10);
          return c;
        }), g.prototype.int32 = function() {
          return 0 | this.uint32();
        }, g.prototype.sint32 = function() {
          var p = this.uint32();
          return p >>> 1 ^ -(1 & p) | 0;
        }, g.prototype.bool = function() {
          return this.uint32() !== 0;
        }, g.prototype.fixed32 = function() {
          if (this.pos + 4 > this.len) throw f(this, 4);
          return r(this.buf, this.pos += 4);
        }, g.prototype.sfixed32 = function() {
          if (this.pos + 4 > this.len) throw f(this, 4);
          return 0 | r(this.buf, this.pos += 4);
        }, g.prototype.float = function() {
          if (this.pos + 4 > this.len) throw f(this, 4);
          var p = l.float.readFloatLE(this.buf, this.pos);
          return this.pos += 4, p;
        }, g.prototype.double = function() {
          if (this.pos + 8 > this.len) throw f(this, 4);
          var p = l.float.readDoubleLE(this.buf, this.pos);
          return this.pos += 8, p;
        }, g.prototype.bytes = function() {
          var p = this.uint32(), m = this.pos, _ = this.pos + p;
          if (_ > this.len) throw f(this, p);
          return this.pos += p, Array.isArray(this.buf) ? this.buf.slice(m, _) : m === _ ? new this.buf.constructor(0) : this._slice.call(this.buf, m, _);
        }, g.prototype.string = function() {
          var p = this.bytes();
          return a.read(p, 0, p.length);
        }, g.prototype.skip = function(p) {
          if (typeof p == "number") {
            if (this.pos + p > this.len) throw f(this, p);
            this.pos += p;
          } else do
            if (this.pos >= this.len) throw f(this);
          while (128 & this.buf[this.pos++]);
          return this;
        }, g.prototype.skipType = function(p) {
          switch (p) {
            case 0:
              this.skip();
              break;
            case 1:
              this.skip(8);
              break;
            case 2:
              this.skip(this.uint32());
              break;
            case 3:
              for (; (p = 7 & this.uint32()) != 4; ) this.skipType(p);
              break;
            case 5:
              this.skip(4);
              break;
            default:
              throw Error("invalid wire type " + p + " at offset " + this.pos);
          }
          return this;
        }, g._configure = function(p) {
          u = p, g.create = t(), u._configure();
          var m = l.Long ? "toLong" : "toNumber";
          l.merge(g.prototype, { int64: function() {
            return e.call(this)[m](!1);
          }, uint64: function() {
            return e.call(this)[m](!0);
          }, sint64: function() {
            return e.call(this).zzDecode()[m](!1);
          }, fixed64: function() {
            return i.call(this)[m](!0);
          }, sfixed64: function() {
            return i.call(this)[m](!1);
          } });
        };
      }, 593: (d, n, o) => {
        d.exports = h;
        var u = o(1408);
        (h.prototype = Object.create(u.prototype)).constructor = h;
        var l = o(9693);
        function h(a) {
          u.call(this, a);
        }
        h._configure = function() {
          l.Buffer && (h.prototype._slice = l.Buffer.prototype.slice);
        }, h.prototype.string = function() {
          var a = this.uint32();
          return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + a, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + a, this.len));
        }, h._configure();
      }, 5054: (d) => {
        d.exports = {};
      }, 5994: (d, n, o) => {
        n.Service = o(7948);
      }, 7948: (d, n, o) => {
        d.exports = l;
        var u = o(9693);
        function l(h, a, f) {
          if (typeof h != "function") throw TypeError("rpcImpl must be a function");
          u.EventEmitter.call(this), this.rpcImpl = h, this.requestDelimited = !!a, this.responseDelimited = !!f;
        }
        (l.prototype = Object.create(u.EventEmitter.prototype)).constructor = l, l.prototype.rpcCall = function h(a, f, g, c, s) {
          if (!c) throw TypeError("request must be specified");
          var t = this;
          if (!s) return u.asPromise(h, t, a, f, g, c);
          if (t.rpcImpl) try {
            return t.rpcImpl(a, f[t.requestDelimited ? "encodeDelimited" : "encode"](c).finish(), (function(e, r) {
              if (e) return t.emit("error", e, a), s(e);
              if (r !== null) {
                if (!(r instanceof g)) try {
                  r = g[t.responseDelimited ? "decodeDelimited" : "decode"](r);
                } catch (i) {
                  return t.emit("error", i, a), s(i);
                }
                return t.emit("data", r, a), s(null, r);
              }
              t.end(!0);
            }));
          } catch (e) {
            return t.emit("error", e, a), void setTimeout((function() {
              s(e);
            }), 0);
          }
          else setTimeout((function() {
            s(Error("already ended"));
          }), 0);
        }, l.prototype.end = function(h) {
          return this.rpcImpl && (h || this.rpcImpl(null, null, null), this.rpcImpl = null, this.emit("end").off()), this;
        };
      }, 1945: (d, n, o) => {
        d.exports = l;
        var u = o(9693);
        function l(g, c) {
          this.lo = g >>> 0, this.hi = c >>> 0;
        }
        var h = l.zero = new l(0, 0);
        h.toNumber = function() {
          return 0;
        }, h.zzEncode = h.zzDecode = function() {
          return this;
        }, h.length = function() {
          return 1;
        };
        var a = l.zeroHash = "\0\0\0\0\0\0\0\0";
        l.fromNumber = function(g) {
          if (g === 0) return h;
          var c = g < 0;
          c && (g = -g);
          var s = g >>> 0, t = (g - s) / 4294967296 >>> 0;
          return c && (t = ~t >>> 0, s = ~s >>> 0, ++s > 4294967295 && (s = 0, ++t > 4294967295 && (t = 0))), new l(s, t);
        }, l.from = function(g) {
          if (typeof g == "number") return l.fromNumber(g);
          if (u.isString(g)) {
            if (!u.Long) return l.fromNumber(parseInt(g, 10));
            g = u.Long.fromString(g);
          }
          return g.low || g.high ? new l(g.low >>> 0, g.high >>> 0) : h;
        }, l.prototype.toNumber = function(g) {
          if (!g && this.hi >>> 31) {
            var c = 1 + ~this.lo >>> 0, s = ~this.hi >>> 0;
            return c || (s = s + 1 >>> 0), -(c + 4294967296 * s);
          }
          return this.lo + 4294967296 * this.hi;
        }, l.prototype.toLong = function(g) {
          return u.Long ? new u.Long(0 | this.lo, 0 | this.hi, !!g) : { low: 0 | this.lo, high: 0 | this.hi, unsigned: !!g };
        };
        var f = String.prototype.charCodeAt;
        l.fromHash = function(g) {
          return g === a ? h : new l((f.call(g, 0) | f.call(g, 1) << 8 | f.call(g, 2) << 16 | f.call(g, 3) << 24) >>> 0, (f.call(g, 4) | f.call(g, 5) << 8 | f.call(g, 6) << 16 | f.call(g, 7) << 24) >>> 0);
        }, l.prototype.toHash = function() {
          return String.fromCharCode(255 & this.lo, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, 255 & this.hi, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24);
        }, l.prototype.zzEncode = function() {
          var g = this.hi >> 31;
          return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ g) >>> 0, this.lo = (this.lo << 1 ^ g) >>> 0, this;
        }, l.prototype.zzDecode = function() {
          var g = -(1 & this.lo);
          return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ g) >>> 0, this.hi = (this.hi >>> 1 ^ g) >>> 0, this;
        }, l.prototype.length = function() {
          var g = this.lo, c = (this.lo >>> 28 | this.hi << 4) >>> 0, s = this.hi >>> 24;
          return s === 0 ? c === 0 ? g < 16384 ? g < 128 ? 1 : 2 : g < 2097152 ? 3 : 4 : c < 16384 ? c < 128 ? 5 : 6 : c < 2097152 ? 7 : 8 : s < 128 ? 9 : 10;
        };
      }, 9693: function(d, n, o) {
        var u = n;
        function l(a, f, g) {
          for (var c = Object.keys(f), s = 0; s < c.length; ++s) a[c[s]] !== void 0 && g || (a[c[s]] = f[c[s]]);
          return a;
        }
        function h(a) {
          function f(g, c) {
            if (!(this instanceof f)) return new f(g, c);
            Object.defineProperty(this, "message", { get: function() {
              return g;
            } }), Error.captureStackTrace ? Error.captureStackTrace(this, f) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), c && l(this, c);
          }
          return (f.prototype = Object.create(Error.prototype)).constructor = f, Object.defineProperty(f.prototype, "name", { get: function() {
            return a;
          } }), f.prototype.toString = function() {
            return this.name + ": " + this.message;
          }, f;
        }
        u.asPromise = o(4537), u.base64 = o(7419), u.EventEmitter = o(9211), u.float = o(945), u.inquire = o(7199), u.utf8 = o(4997), u.pool = o(6662), u.LongBits = o(1945), u.isNode = !!(o.g !== void 0 && o.g && o.g.process && o.g.process.versions && o.g.process.versions.node), u.global = u.isNode && o.g || typeof window < "u" && window || typeof self < "u" && self || this, u.emptyArray = Object.freeze ? Object.freeze([]) : [], u.emptyObject = Object.freeze ? Object.freeze({}) : {}, u.isInteger = Number.isInteger || function(a) {
          return typeof a == "number" && isFinite(a) && Math.floor(a) === a;
        }, u.isString = function(a) {
          return typeof a == "string" || a instanceof String;
        }, u.isObject = function(a) {
          return a && typeof a == "object";
        }, u.isset = u.isSet = function(a, f) {
          var g = a[f];
          return !(g == null || !a.hasOwnProperty(f)) && (typeof g != "object" || (Array.isArray(g) ? g.length : Object.keys(g).length) > 0);
        }, u.Buffer = (function() {
          try {
            var a = u.inquire("buffer").Buffer;
            return a.prototype.utf8Write ? a : null;
          } catch {
            return null;
          }
        })(), u._Buffer_from = null, u._Buffer_allocUnsafe = null, u.newBuffer = function(a) {
          return typeof a == "number" ? u.Buffer ? u._Buffer_allocUnsafe(a) : new u.Array(a) : u.Buffer ? u._Buffer_from(a) : typeof Uint8Array > "u" ? a : new Uint8Array(a);
        }, u.Array = typeof Uint8Array < "u" ? Uint8Array : Array, u.Long = u.global.dcodeIO && u.global.dcodeIO.Long || u.global.Long || u.inquire("long"), u.key2Re = /^true|false|0|1$/, u.key32Re = /^-?(?:0|[1-9][0-9]*)$/, u.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/, u.longToHash = function(a) {
          return a ? u.LongBits.from(a).toHash() : u.LongBits.zeroHash;
        }, u.longFromHash = function(a, f) {
          var g = u.LongBits.fromHash(a);
          return u.Long ? u.Long.fromBits(g.lo, g.hi, f) : g.toNumber(!!f);
        }, u.merge = l, u.lcFirst = function(a) {
          return a.charAt(0).toLowerCase() + a.substring(1);
        }, u.newError = h, u.ProtocolError = h("ProtocolError"), u.oneOfGetter = function(a) {
          for (var f = {}, g = 0; g < a.length; ++g) f[a[g]] = 1;
          return function() {
            for (var c = Object.keys(this), s = c.length - 1; s > -1; --s) if (f[c[s]] === 1 && this[c[s]] !== void 0 && this[c[s]] !== null) return c[s];
          };
        }, u.oneOfSetter = function(a) {
          return function(f) {
            for (var g = 0; g < a.length; ++g) a[g] !== f && delete this[a[g]];
          };
        }, u.toJSONOptions = { longs: String, enums: String, bytes: String, json: !0 }, u._configure = function() {
          var a = u.Buffer;
          a ? (u._Buffer_from = a.from !== Uint8Array.from && a.from || function(f, g) {
            return new a(f, g);
          }, u._Buffer_allocUnsafe = a.allocUnsafe || function(f) {
            return new a(f);
          }) : u._Buffer_from = u._Buffer_allocUnsafe = null;
        };
      }, 1173: (d, n, o) => {
        d.exports = t;
        var u, l = o(9693), h = l.LongBits, a = l.base64, f = l.utf8;
        function g(b, y, w) {
          this.fn = b, this.len = y, this.next = void 0, this.val = w;
        }
        function c() {
        }
        function s(b) {
          this.head = b.head, this.tail = b.tail, this.len = b.len, this.next = b.states;
        }
        function t() {
          this.len = 0, this.head = new g(c, 0, 0), this.tail = this.head, this.states = null;
        }
        var e = function() {
          return l.Buffer ? function() {
            return (t.create = function() {
              return new u();
            })();
          } : function() {
            return new t();
          };
        };
        function r(b, y, w) {
          y[w] = 255 & b;
        }
        function i(b, y) {
          this.len = b, this.next = void 0, this.val = y;
        }
        function p(b, y, w) {
          for (; b.hi; ) y[w++] = 127 & b.lo | 128, b.lo = (b.lo >>> 7 | b.hi << 25) >>> 0, b.hi >>>= 7;
          for (; b.lo > 127; ) y[w++] = 127 & b.lo | 128, b.lo = b.lo >>> 7;
          y[w++] = b.lo;
        }
        function m(b, y, w) {
          y[w] = 255 & b, y[w + 1] = b >>> 8 & 255, y[w + 2] = b >>> 16 & 255, y[w + 3] = b >>> 24;
        }
        t.create = e(), t.alloc = function(b) {
          return new l.Array(b);
        }, l.Array !== Array && (t.alloc = l.pool(t.alloc, l.Array.prototype.subarray)), t.prototype._push = function(b, y, w) {
          return this.tail = this.tail.next = new g(b, y, w), this.len += y, this;
        }, i.prototype = Object.create(g.prototype), i.prototype.fn = function(b, y, w) {
          for (; b > 127; ) y[w++] = 127 & b | 128, b >>>= 7;
          y[w] = b;
        }, t.prototype.uint32 = function(b) {
          return this.len += (this.tail = this.tail.next = new i((b >>>= 0) < 128 ? 1 : b < 16384 ? 2 : b < 2097152 ? 3 : b < 268435456 ? 4 : 5, b)).len, this;
        }, t.prototype.int32 = function(b) {
          return b < 0 ? this._push(p, 10, h.fromNumber(b)) : this.uint32(b);
        }, t.prototype.sint32 = function(b) {
          return this.uint32((b << 1 ^ b >> 31) >>> 0);
        }, t.prototype.uint64 = function(b) {
          var y = h.from(b);
          return this._push(p, y.length(), y);
        }, t.prototype.int64 = t.prototype.uint64, t.prototype.sint64 = function(b) {
          var y = h.from(b).zzEncode();
          return this._push(p, y.length(), y);
        }, t.prototype.bool = function(b) {
          return this._push(r, 1, b ? 1 : 0);
        }, t.prototype.fixed32 = function(b) {
          return this._push(m, 4, b >>> 0);
        }, t.prototype.sfixed32 = t.prototype.fixed32, t.prototype.fixed64 = function(b) {
          var y = h.from(b);
          return this._push(m, 4, y.lo)._push(m, 4, y.hi);
        }, t.prototype.sfixed64 = t.prototype.fixed64, t.prototype.float = function(b) {
          return this._push(l.float.writeFloatLE, 4, b);
        }, t.prototype.double = function(b) {
          return this._push(l.float.writeDoubleLE, 8, b);
        };
        var _ = l.Array.prototype.set ? function(b, y, w) {
          y.set(b, w);
        } : function(b, y, w) {
          for (var T = 0; T < b.length; ++T) y[w + T] = b[T];
        };
        t.prototype.bytes = function(b) {
          var y = b.length >>> 0;
          if (!y) return this._push(r, 1, 0);
          if (l.isString(b)) {
            var w = t.alloc(y = a.length(b));
            a.decode(b, w, 0), b = w;
          }
          return this.uint32(y)._push(_, y, b);
        }, t.prototype.string = function(b) {
          var y = f.length(b);
          return y ? this.uint32(y)._push(f.write, y, b) : this._push(r, 1, 0);
        }, t.prototype.fork = function() {
          return this.states = new s(this), this.head = this.tail = new g(c, 0, 0), this.len = 0, this;
        }, t.prototype.reset = function() {
          return this.states ? (this.head = this.states.head, this.tail = this.states.tail, this.len = this.states.len, this.states = this.states.next) : (this.head = this.tail = new g(c, 0, 0), this.len = 0), this;
        }, t.prototype.ldelim = function() {
          var b = this.head, y = this.tail, w = this.len;
          return this.reset().uint32(w), w && (this.tail.next = b.next, this.tail = y, this.len += w), this;
        }, t.prototype.finish = function() {
          for (var b = this.head.next, y = this.constructor.alloc(this.len), w = 0; b; ) b.fn(b.val, y, w), w += b.len, b = b.next;
          return y;
        }, t._configure = function(b) {
          u = b, t.create = e(), u._configure();
        };
      }, 3155: (d, n, o) => {
        d.exports = h;
        var u = o(1173);
        (h.prototype = Object.create(u.prototype)).constructor = h;
        var l = o(9693);
        function h() {
          u.call(this);
        }
        function a(f, g, c) {
          f.length < 40 ? l.utf8.write(f, g, c) : g.utf8Write ? g.utf8Write(f, c) : g.write(f, c);
        }
        h._configure = function() {
          h.alloc = l._Buffer_allocUnsafe, h.writeBytesBuffer = l.Buffer && l.Buffer.prototype instanceof Uint8Array && l.Buffer.prototype.set.name === "set" ? function(f, g, c) {
            g.set(f, c);
          } : function(f, g, c) {
            if (f.copy) f.copy(g, c, 0, f.length);
            else for (var s = 0; s < f.length; ) g[c++] = f[s++];
          };
        }, h.prototype.bytes = function(f) {
          l.isString(f) && (f = l._Buffer_from(f, "base64"));
          var g = f.length >>> 0;
          return this.uint32(g), g && this._push(h.writeBytesBuffer, g, f), this;
        }, h.prototype.string = function(f) {
          var g = l.Buffer.byteLength(f);
          return this.uint32(g), g && this._push(a, g, f), this;
        }, h._configure();
      }, 7714: (d, n, o) => {
        n.R = void 0;
        const u = o(6919), l = o(7448);
        n.R = new class {
          async init() {
          }
          async createSessionHandler(h, a) {
            const f = new u.Session(a);
            return await f.loadModel(h), new l.OnnxjsSessionHandler(f);
          }
        }();
      }, 4200: (d, n, o) => {
        n.c8 = n.rX = void 0;
        const u = o(1670), l = o(5381), h = o(2157), a = o(2306);
        n.rX = () => {
          if ((typeof u.env.wasm.initTimeout != "number" || u.env.wasm.initTimeout < 0) && (u.env.wasm.initTimeout = 0), typeof u.env.wasm.simd != "boolean" && (u.env.wasm.simd = !0), typeof u.env.wasm.proxy != "boolean" && (u.env.wasm.proxy = !1), typeof u.env.wasm.numThreads != "number" || !Number.isInteger(u.env.wasm.numThreads) || u.env.wasm.numThreads <= 0) {
            const f = typeof navigator > "u" ? (0, l.cpus)().length : navigator.hardwareConcurrency;
            u.env.wasm.numThreads = Math.min(4, Math.ceil((f || 1) / 2));
          }
        }, n.c8 = new class {
          async init() {
            (0, n.rX)(), await (0, h.initWasm)();
          }
          async createSessionHandler(f, g) {
            const c = new a.OnnxruntimeWebAssemblySessionHandler();
            return await c.loadModel(f, g), Promise.resolve(c);
          }
        }();
      }, 6018: function(d, n, o) {
        var u = this && this.__createBinding || (Object.create ? function(a, f, g, c) {
          c === void 0 && (c = g);
          var s = Object.getOwnPropertyDescriptor(f, g);
          s && !("get" in s ? !f.__esModule : s.writable || s.configurable) || (s = { enumerable: !0, get: function() {
            return f[g];
          } }), Object.defineProperty(a, c, s);
        } : function(a, f, g, c) {
          c === void 0 && (c = g), a[c] = f[g];
        }), l = this && this.__exportStar || function(a, f) {
          for (var g in a) g === "default" || Object.prototype.hasOwnProperty.call(f, g) || u(f, a, g);
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), l(o(1670), n);
        const h = o(1670);
        {
          const a = o(7714).R;
          (0, h.registerBackend)("webgl", a, -10);
        }
        {
          const a = o(4200).c8;
          (0, h.registerBackend)("cpu", a, 10), (0, h.registerBackend)("wasm", a, 10), (0, h.registerBackend)("xnnpack", a, 9);
        }
      }, 246: (d, n) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createAttributeWithCacheKey = void 0;
        class o {
          constructor(l) {
            Object.assign(this, l);
          }
          get cacheKey() {
            return this._cacheKey || (this._cacheKey = Object.getOwnPropertyNames(this).sort().map(((l) => `${this[l]}`)).join(";")), this._cacheKey;
          }
        }
        n.createAttributeWithCacheKey = (u) => new o(u);
      }, 7778: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.Attribute = void 0;
        const u = o(1446), l = o(9395), h = o(9162), a = o(2517);
        var f = l.onnxruntime.experimental.fbs;
        class g {
          constructor(s) {
            if (this._attributes = /* @__PURE__ */ new Map(), s != null) {
              for (const t of s) t instanceof u.onnx.AttributeProto ? this._attributes.set(t.name, [g.getValue(t), g.getType(t)]) : t instanceof f.Attribute && this._attributes.set(t.name(), [g.getValue(t), g.getType(t)]);
              if (this._attributes.size < s.length) throw new Error("duplicated attribute names");
            }
          }
          set(s, t, e) {
            this._attributes.set(s, [e, t]);
          }
          delete(s) {
            this._attributes.delete(s);
          }
          getFloat(s, t) {
            return this.get(s, "float", t);
          }
          getInt(s, t) {
            return this.get(s, "int", t);
          }
          getString(s, t) {
            return this.get(s, "string", t);
          }
          getTensor(s, t) {
            return this.get(s, "tensor", t);
          }
          getFloats(s, t) {
            return this.get(s, "floats", t);
          }
          getInts(s, t) {
            return this.get(s, "ints", t);
          }
          getStrings(s, t) {
            return this.get(s, "strings", t);
          }
          getTensors(s, t) {
            return this.get(s, "tensors", t);
          }
          get(s, t, e) {
            const r = this._attributes.get(s);
            if (r === void 0) {
              if (e !== void 0) return e;
              throw new Error(`required attribute not found: ${s}`);
            }
            if (r[1] !== t) throw new Error(`type mismatch: expected ${t} but got ${r[1]}`);
            return r[0];
          }
          static getType(s) {
            const t = s instanceof u.onnx.AttributeProto ? s.type : s.type();
            switch (t) {
              case u.onnx.AttributeProto.AttributeType.FLOAT:
                return "float";
              case u.onnx.AttributeProto.AttributeType.INT:
                return "int";
              case u.onnx.AttributeProto.AttributeType.STRING:
                return "string";
              case u.onnx.AttributeProto.AttributeType.TENSOR:
                return "tensor";
              case u.onnx.AttributeProto.AttributeType.FLOATS:
                return "floats";
              case u.onnx.AttributeProto.AttributeType.INTS:
                return "ints";
              case u.onnx.AttributeProto.AttributeType.STRINGS:
                return "strings";
              case u.onnx.AttributeProto.AttributeType.TENSORS:
                return "tensors";
              default:
                throw new Error(`attribute type is not supported yet: ${u.onnx.AttributeProto.AttributeType[t]}`);
            }
          }
          static getValue(s) {
            const t = s instanceof u.onnx.AttributeProto ? s.type : s.type();
            if (t === u.onnx.AttributeProto.AttributeType.GRAPH || t === u.onnx.AttributeProto.AttributeType.GRAPHS) throw new Error("graph attribute is not supported yet");
            const e = this.getValueNoCheck(s);
            if (t === u.onnx.AttributeProto.AttributeType.INT && a.LongUtil.isLong(e)) return a.LongUtil.longToNumber(e);
            if (t === u.onnx.AttributeProto.AttributeType.INTS) {
              const r = e, i = new Array(r.length);
              for (let p = 0; p < r.length; p++) {
                const m = r[p];
                i[p] = a.LongUtil.longToNumber(m);
              }
              return i;
            }
            if (t === u.onnx.AttributeProto.AttributeType.TENSOR) return s instanceof u.onnx.AttributeProto ? h.Tensor.fromProto(e) : h.Tensor.fromOrtTensor(e);
            if (t === u.onnx.AttributeProto.AttributeType.TENSORS) {
              if (s instanceof u.onnx.AttributeProto) return e.map(((r) => h.Tensor.fromProto(r)));
              if (s instanceof f.Attribute) return e.map(((r) => h.Tensor.fromOrtTensor(r)));
            }
            if (t === u.onnx.AttributeProto.AttributeType.STRING && s instanceof u.onnx.AttributeProto) {
              const r = e;
              return (0, a.decodeUtf8String)(r);
            }
            return t === u.onnx.AttributeProto.AttributeType.STRINGS && s instanceof u.onnx.AttributeProto ? e.map(a.decodeUtf8String) : e;
          }
          static getValueNoCheck(s) {
            return s instanceof u.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(s) : this.getValueNoCheckFromOrtFormat(s);
          }
          static getValueNoCheckFromOnnxFormat(s) {
            switch (s.type) {
              case u.onnx.AttributeProto.AttributeType.FLOAT:
                return s.f;
              case u.onnx.AttributeProto.AttributeType.INT:
                return s.i;
              case u.onnx.AttributeProto.AttributeType.STRING:
                return s.s;
              case u.onnx.AttributeProto.AttributeType.TENSOR:
                return s.t;
              case u.onnx.AttributeProto.AttributeType.GRAPH:
                return s.g;
              case u.onnx.AttributeProto.AttributeType.FLOATS:
                return s.floats;
              case u.onnx.AttributeProto.AttributeType.INTS:
                return s.ints;
              case u.onnx.AttributeProto.AttributeType.STRINGS:
                return s.strings;
              case u.onnx.AttributeProto.AttributeType.TENSORS:
                return s.tensors;
              case u.onnx.AttributeProto.AttributeType.GRAPHS:
                return s.graphs;
              default:
                throw new Error(`unsupported attribute type: ${u.onnx.AttributeProto.AttributeType[s.type]}`);
            }
          }
          static getValueNoCheckFromOrtFormat(s) {
            switch (s.type()) {
              case f.AttributeType.FLOAT:
                return s.f();
              case f.AttributeType.INT:
                return s.i();
              case f.AttributeType.STRING:
                return s.s();
              case f.AttributeType.TENSOR:
                return s.t();
              case f.AttributeType.GRAPH:
                return s.g();
              case f.AttributeType.FLOATS:
                return s.floatsArray();
              case f.AttributeType.INTS: {
                const t = [];
                for (let e = 0; e < s.intsLength(); e++) t.push(s.ints(e));
                return t;
              }
              case f.AttributeType.STRINGS: {
                const t = [];
                for (let e = 0; e < s.stringsLength(); e++) t.push(s.strings(e));
                return t;
              }
              case f.AttributeType.TENSORS: {
                const t = [];
                for (let e = 0; e < s.tensorsLength(); e++) t.push(s.tensors(e));
                return t;
              }
              default:
                throw new Error(`unsupported attribute type: ${f.AttributeType[s.type()]}`);
            }
          }
        }
        n.Attribute = g;
      }, 7091: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.resolveBackend = n.backend = void 0;
        const u = o(5038), l = /* @__PURE__ */ new Map();
        async function h(a) {
          const f = n.backend;
          if (f[a] !== void 0 && (function(g) {
            const c = g;
            return "initialize" in c && typeof c.initialize == "function" && "createSessionHandler" in c && typeof c.createSessionHandler == "function" && "dispose" in c && typeof c.dispose == "function";
          })(f[a])) {
            const g = f[a];
            let c = g.initialize();
            if (typeof c == "object" && "then" in c && (c = await c), c) return l.set(a, g), g;
          }
        }
        n.backend = { webgl: new u.WebGLBackend() }, n.resolveBackend = async function a(f) {
          if (!f) return a(["webgl"]);
          {
            const g = typeof f == "string" ? [f] : f;
            for (const c of g) {
              const s = l.get(c);
              if (s) return s;
              const t = await h(c);
              if (t) return t;
            }
          }
          throw new Error("no available backend to use");
        };
      }, 5038: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.WebGLBackend = void 0;
        const u = o(1670), l = o(6231), h = o(6416), a = o(7305);
        n.WebGLBackend = class {
          get contextId() {
            return u.env.webgl.contextId;
          }
          set contextId(f) {
            u.env.webgl.contextId = f;
          }
          get matmulMaxBatchSize() {
            return u.env.webgl.matmulMaxBatchSize;
          }
          set matmulMaxBatchSize(f) {
            u.env.webgl.matmulMaxBatchSize = f;
          }
          get textureCacheMode() {
            return u.env.webgl.textureCacheMode;
          }
          set textureCacheMode(f) {
            u.env.webgl.textureCacheMode = f;
          }
          get pack() {
            return u.env.webgl.pack;
          }
          set pack(f) {
            u.env.webgl.pack = f;
          }
          get async() {
            return u.env.webgl.async;
          }
          set async(f) {
            u.env.webgl.async = f;
          }
          initialize() {
            try {
              return this.glContext = (0, a.createWebGLContext)(this.contextId), typeof this.matmulMaxBatchSize != "number" && (this.matmulMaxBatchSize = 16), typeof this.textureCacheMode != "string" && (this.textureCacheMode = "full"), typeof this.pack != "boolean" && (this.pack = !1), typeof this.async != "boolean" && (this.async = !1), l.Logger.setWithEnv(u.env), l.Logger.verbose("WebGLBackend", `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`), !0;
            } catch (f) {
              return l.Logger.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${f}`), !1;
            }
          }
          createSessionHandler(f) {
            return new h.WebGLSessionHandler(this, f);
          }
          dispose() {
            this.glContext.dispose();
          }
        };
      }, 5107: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.CoordsGlslLib = void 0;
        const u = o(2517), l = o(8520), h = o(5060), a = o(7859), f = o(9390);
        class g extends l.GlslLib {
          constructor(s) {
            super(s);
          }
          getFunctions() {
            return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.offsetToCoords()), this.coordsToOffset()), this.toVec()), this.valueFrom()), this.getCommonUtilFuncs()), this.getInputsSamplingSnippets()), this.getOutputSamplingSnippet());
          }
          getCustomTypes() {
            return {};
          }
          offsetToCoords() {
            return { offsetToCoords: new l.GlslLibRoutine(`
      vec2 offsetToCoords(int offset, int width, int height) {
        int t = offset / width;
        int s = offset - t*width;
        vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);
        return coords;
      }
      `) };
          }
          coordsToOffset() {
            return { coordsToOffset: new l.GlslLibRoutine(`
      int coordsToOffset(vec2 coords, int width, int height) {
        float s = coords.s * float(width);
        float t = coords.t * float(height);
        int offset = int(t) * width + int(s);
        return offset;
      }
      `) };
          }
          getOutputSamplingSnippet() {
            const s = this.context.outputTextureLayout;
            return s.isPacked ? this.getPackedOutputSamplingSnippet(s) : this.getUnpackedOutputSamplingSnippet(s);
          }
          getPackedOutputSamplingSnippet(s) {
            const t = s.unpackedShape, e = [s.width, s.height], r = {}, i = "getOutputCoords";
            switch (t.length) {
              case 0:
                r[i] = this.getOutputScalarCoords();
                break;
              case 1:
                r[i] = this.getOutputPacked1DCoords(t, e);
                break;
              case 2:
                r[i] = this.getOutputPacked2DCoords(t, e);
                break;
              case 3:
                r[i] = this.getOutputPacked3DCoords(t, e);
                break;
              default:
                r[i] = this.getOutputPackedNDCoords(t, e);
            }
            const p = `
      void setOutput(vec4 val) {
        ${(0, h.getGlsl)(this.context.glContext.version).output} = val;
      }
    `;
            return r.floatTextureSetRGBA = new l.GlslLibRoutine(p), r;
          }
          getUnpackedOutputSamplingSnippet(s) {
            const t = s.unpackedShape, e = [s.width, s.height], r = {}, i = "getOutputCoords";
            switch (t.length) {
              case 0:
                r[i] = this.getOutputScalarCoords();
                break;
              case 1:
                r[i] = this.getOutputUnpacked1DCoords(t, e);
                break;
              case 2:
                r[i] = this.getOutputUnpacked2DCoords(t, e);
                break;
              case 3:
                r[i] = this.getOutputUnpacked3DCoords(t, e);
                break;
              case 4:
                r[i] = this.getOutputUnpacked4DCoords(t, e);
                break;
              case 5:
                r[i] = this.getOutputUnpacked5DCoords(t, e);
                break;
              case 6:
                r[i] = this.getOutputUnpacked6DCoords(t, e);
                break;
              default:
                throw new Error(`Unsupported output dimensionality: ${t.length}`);
            }
            const p = `
        void setOutput(float val) {
          ${(0, h.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);
        }
    `;
            return r.floatTextureSetR = new l.GlslLibRoutine(p), r;
          }
          getOutputScalarCoords() {
            return new l.GlslLibRoutine(`
      int getOutputCoords() {
        return 0;
      }
    `);
          }
          getOutputPacked1DCoords(s, t) {
            const e = t;
            let r = "";
            return e[0] === 1 ? (r = `
          int getOutputCoords() {
            return 2 * int(TexCoords.y * ${e[1]}.0);
          }
        `, new l.GlslLibRoutine(r)) : e[1] === 1 ? (r = `
          int getOutputCoords() {
            return 2 * int(TexCoords.x * ${e[0]}.0);
          }
        `, new l.GlslLibRoutine(r)) : (r = `
        int getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                 vec2(${e[0]}, ${e[1]}));
          return 2 * (resTexRC.y * ${e[0]} + resTexRC.x);
        }
      `, new l.GlslLibRoutine(r));
          }
          getOutputPacked2DCoords(s, t) {
            let e = "";
            if (u.ArrayUtil.arraysEqual(s, t)) return e = `
        ivec2 getOutputCoords() {
          return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]}));
        }
      `, new l.GlslLibRoutine(e);
            const r = t, i = Math.ceil(s[1] / 2);
            return e = `
        ivec2 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${r[0]}, ${r[1]}));

          int index = resTexRC.y * ${r[0]} + resTexRC.x;

          // reverse r and c order for packed texture
          int r = imod(index, ${i}) * 2;
          int c = 2 * (index / ${i});

          return ivec2(r, c);
        }
      `, new l.GlslLibRoutine(e);
          }
          getOutputPacked3DCoords(s, t) {
            const e = [t[0], t[1]], r = Math.ceil(s[2] / 2), i = r * Math.ceil(s[1] / 2), p = `
        ivec3 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${e[0]}, ${e[1]}));
          int index = resTexRC.y * ${e[0]} + resTexRC.x;

          int b = index / ${i};
          index -= b * ${i};

          // reverse r and c order for packed texture
          int r = imod(index, ${r}) * 2;
          int c = 2 * (index / ${r});

          return ivec3(b, r, c);
        }
      `;
            return new l.GlslLibRoutine(p);
          }
          getOutputPackedNDCoords(s, t) {
            const e = [t[0], t[1]], r = Math.ceil(s[s.length - 1] / 2), i = r * Math.ceil(s[s.length - 2] / 2);
            let p = i, m = "", _ = "b, r, c";
            for (let y = 2; y < s.length - 1; y++) p *= s[s.length - y - 1], m = `
      int b${y} = index / ${p};
      index -= b${y} * ${p};
    ` + m, _ = `b${y}, ` + _;
            const b = `
      ivec${s.length} getOutputCoords() {
        ivec2 resTexRC = ivec2(TexCoords.xy *
                              vec2(${e[0]}, ${e[1]}));
        int index = resTexRC.y * ${e[0]} + resTexRC.x;

        ${m}

        int b = index / ${i};
        index -= b * ${i};

        // reverse r and c order for packed texture
        int r = imod(index, ${r}) * 2;
        int c = 2 * (index / ${r});

        return ivec${s.length}(${_});
      }
    `;
            return new l.GlslLibRoutine(b);
          }
          getOutputUnpacked1DCoords(s, t) {
            const e = `
        int getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${t[0]}, ${t[1]}));
          return resTexRC.y * ${t[0]} + resTexRC.x;
        }
      `;
            return new l.GlslLibRoutine(e);
          }
          getOutputUnpacked2DCoords(s, t) {
            const e = `
        ivec2 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${t[0]}, ${t[1]}));
          int index = resTexRC.y * ${t[0]} + resTexRC.x;
          int r = index / ${s[1]};
          int c = index - r * ${s[1]};
          return ivec2(r, c);
        }
      `;
            return new l.GlslLibRoutine(e);
          }
          getOutputUnpacked3DCoords(s, t) {
            let e = "";
            const r = s.length;
            let i = null;
            r < 2 && (i = []), i = new Array(r - 1), i[r - 2] = s[r - 1];
            for (let _ = r - 3; _ >= 0; --_) i[_] = i[_ + 1] * s[_ + 1];
            const p = ["r", "c", "d"], m = i.map(((_, b) => `int ${p[b]} = index / ${_}; ${b === i.length - 1 ? `int ${p[b + 1]} = index - ${p[b]} * ${_}` : `index -= ${p[b]} * ${_}`};`)).join("");
            return e = `
        ivec3 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${t[0]}, ${t[1]}));
          int index = resTexRC.y * ${t[0]} + resTexRC.x;
          ${m}
          return ivec3(r, c, d);
        }
      `, new l.GlslLibRoutine(e);
          }
          getOutputUnpacked4DCoords(s, t) {
            let e = "";
            const r = s.length;
            let i = null;
            r < 2 && (i = []), i = new Array(r - 1), i[r - 2] = s[r - 1];
            for (let _ = r - 3; _ >= 0; --_) i[_] = i[_ + 1] * s[_ + 1];
            const p = ["r", "c", "d", "d2"], m = i.map(((_, b) => `int ${p[b]} = index / ${_}; ${b === i.length - 1 ? `int ${p[b + 1]} = index - ${p[b]} * ${_}` : `index -= ${p[b]} * ${_}`};`)).join("");
            return e = `
      ivec4 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${t[0]}, ${t[1]}));
          int index = resTexRC.y * ${t[0]} + resTexRC.x;
          ${m}
          return ivec4(r, c, d, d2);
        }
      `, new l.GlslLibRoutine(e);
          }
          getOutputUnpacked5DCoords(s, t) {
            let e = "";
            const r = s.length;
            let i = null;
            r < 2 && (i = []), i = new Array(r - 1), i[r - 2] = s[r - 1];
            for (let _ = r - 3; _ >= 0; --_) i[_] = i[_ + 1] * s[_ + 1];
            const p = ["r", "c", "d", "d2", "d3"], m = i.map(((_, b) => `int ${p[b]} = index / ${_}; ${b === i.length - 1 ? `int ${p[b + 1]} = index - ${p[b]} * ${_}` : `index -= ${p[b]} * ${_}`};`)).join("");
            return e = `
      ivec5 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${t[0]}, ${t[1]}));
          int index = resTexRC.y * ${t[0]} + resTexRC.x;
          ${m}
          return ivec5(r, c, d, d2, d3);
        }
      `, new l.GlslLibRoutine(e);
          }
          getOutputUnpacked6DCoords(s, t) {
            let e = "";
            const r = s.length;
            let i = null;
            r < 2 && (i = []), i = new Array(r - 1), i[r - 2] = s[r - 1];
            for (let _ = r - 3; _ >= 0; --_) i[_] = i[_ + 1] * s[_ + 1];
            const p = ["r", "c", "d", "d2", "d3", "d4"], m = i.map(((_, b) => `int ${p[b]} = index / ${_}; ${b === i.length - 1 ? `int ${p[b + 1]} = index - ${p[b]} * ${_}` : `index -= ${p[b]} * ${_}`};`)).join("");
            return e = `
     ivec6 getOutputCoords() {
         ivec2 resTexRC = ivec2(TexCoords.xy *
                               vec2(${t[0]}, ${t[1]}));
         int index = resTexRC.y * ${t[0]} + resTexRC.x;
         ${m}
         return ivec6(r, c, d, d2, d3, d4);
       }
     `, new l.GlslLibRoutine(e);
          }
          getCommonUtilFuncs() {
            const s = {};
            let t = "uvFromFlat";
            s[t] = new l.GlslLibRoutine(`
    vec2 uvFromFlat(int texNumR, int texNumC, int index) {
      int texC = index / texNumR;
      int texR = index - texC * texNumR;
      // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to
      //       v.
      return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);
    }
    `), t = "packedUVfrom1D", s[t] = new l.GlslLibRoutine(`
      vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
        int texelIndex = index / 2;
        int texR = texelIndex / texNumC;
        int texC = texelIndex - texR * texNumC;
        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
      }
      `), t = "packedUVfrom2D", s[t] = new l.GlslLibRoutine(`
      vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {
        int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
        int texR = texelIndex / texNumC;
        int texC = texelIndex - texR * texNumC;
        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
      }
      `), t = "packedUVfrom3D", s[t] = new l.GlslLibRoutine(`
      vec2 packedUVfrom3D(int texNumR, int texNumC,
          int texelsInBatch, int texelsInLogicalRow, int b,
          int row, int col) {
        int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
        int texR = index / texNumC;
        int texC = index - texR * texNumC;
        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
      }
      `), t = "sampleTexture";
            const e = (0, h.getGlsl)(this.context.glContext.version);
            return s[t] = new l.GlslLibRoutine(`
        float sampleTexture(sampler2D textureSampler, vec2 uv) {
            return ${e.texture2D}(textureSampler, uv).r;
        }`), s;
          }
          getInputsSamplingSnippets() {
            const s = {}, t = this.context.outputTextureLayout;
            return this.context.programInfo.inputNames.forEach(((e, r) => {
              const i = this.context.inputTextureLayouts[r], p = (0, f.generateShaderFuncNameFromInputSamplerName)(e);
              i.isPacked ? s[p] = this.getPackedSamplerFromInput(p, e, i) : s[p] = this.getUnpackedSamplerFromInput(p, e, i);
              const m = (0, f.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);
              i.unpackedShape.length <= t.unpackedShape.length && (i.isPacked ? s[m] = this.getPackedSamplerAtOutputCoords(m, i, t, e) : s[m] = this.getUnpackedSamplerAtOutputCoords(m, i, t, e));
            })), s;
          }
          getPackedSamplerAtOutputCoords(s, t, e, r) {
            const i = t.unpackedShape, p = e.unpackedShape, m = r, _ = (0, f.generateShaderFuncNameFromInputSamplerName)(m), b = i.length, y = p.length, w = u.BroadcastUtil.getBroadcastDims(i, p), T = (0, f.getCoordsDataType)(y), S = y - b;
            let E;
            const O = (0, f.getGlChannels)();
            E = b === 0 ? "" : y < 2 && w.length >= 1 ? "coords = 0;" : w.map(((F) => `coords.${O[F + S]} = 0;`)).join(`
`);
            let v = "";
            v = y < 2 && b > 0 ? "coords" : i.map(((F, D) => `coords.${O[D + S]}`)).join(", ");
            let A = "return outputValue;";
            const L = u.ShapeUtil.size(i) === 1, j = u.ShapeUtil.size(p) === 1;
            if (b !== 1 || L || j) {
              if (L && !j) A = y === 1 ? `
          return vec4(outputValue.x, outputValue.x, 0., 0.);
        ` : `
          return vec4(outputValue.x);
        `;
              else if (w.length) {
                const F = b - 2, D = b - 1;
                w.indexOf(F) > -1 && w.indexOf(D) > -1 ? A = "return vec4(outputValue.x);" : w.indexOf(F) > -1 ? A = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : w.indexOf(D) > -1 && (A = "return vec4(outputValue.xx, outputValue.zz);");
              }
            } else A = `
        return vec4(outputValue.xy, outputValue.xy);
      `;
            const B = `
      vec4 ${s}() {
        ${T} coords = getOutputCoords();
        
        int lastDim = coords.${O[y - 1]};
        coords.${O[y - 1]} = coords.${O[y - 2]};
        coords.${O[y - 2]} = lastDim;
      
        ${E}
        vec4 outputValue = ${_}(${v});
        ${A}
      }
    `;
            return new l.GlslLibRoutine(B, ["coordinates.getOutputCoords"]);
          }
          getUnpackedSamplerAtOutputCoords(s, t, e, r) {
            const i = [e.width, e.height], p = [t.width, t.height], m = t.unpackedShape.length, _ = e.unpackedShape.length, b = t.unpackedShape, y = e.unpackedShape, w = (0, f.generateShaderFuncNameFromInputSamplerName)(r);
            if (m === _ && u.ArrayUtil.arraysEqual(p, i)) {
              const j = `
          float ${s}() {
            return sampleTexture(${r}, TexCoords);
          }
        `;
              return new l.GlslLibRoutine(j, ["coordinates.sampleTexture"]);
            }
            const T = (0, f.getCoordsDataType)(_), S = u.BroadcastUtil.getBroadcastDims(b, y), E = _ - m;
            let O;
            const v = (0, f.getGlChannels)();
            O = m === 0 ? "" : _ < 2 && S.length >= 1 ? "coords = 0;" : S.map(((j) => `coords.${v[j + E]} = 0;`)).join(`
`);
            let A = "";
            A = _ < 2 && m > 0 ? "coords" : t.unpackedShape.map(((j, B) => `coords.${v[B + E]}`)).join(", ");
            const L = `
        float ${s}() {
          ${T} coords = getOutputCoords();
          ${O}
          return ${w}(${A});
        }
      `;
            return new l.GlslLibRoutine(L, ["coordinates.getOutputCoords"]);
          }
          getPackedSamplerFromInput(s, t, e) {
            switch (e.unpackedShape.length) {
              case 0:
                return this.getPackedSamplerScalar(s, t);
              case 1:
                return this.getPackedSampler1D(s, t, e);
              case 2:
                return this.getPackedSampler2D(s, t, e);
              case 3:
                return this.getPackedSampler3D(s, t, e);
              default:
                return this.getPackedSamplerND(s, t, e);
            }
          }
          getUnpackedSamplerFromInput(s, t, e) {
            const r = e.unpackedShape;
            switch (r.length) {
              case 0:
                return this.getUnpackedSamplerScalar(s, t, e);
              case 1:
                return this.getUnpackedSampler1D(s, t, e);
              case 2:
                return this.getUnpackedSampler2D(s, t, e);
              case 3:
                return this.getUnpackedSampler3D(s, t, e);
              case 4:
                return this.getUnpackedSampler4D(s, t, e);
              case 5:
                return this.getUnpackedSampler5D(s, t, e);
              case 6:
                return this.getUnpackedSampler6D(s, t, e);
              default:
                throw new Error(`Unsupported dimension ${r.length}-D`);
            }
          }
          getPackedSamplerScalar(s, t) {
            const e = `
          vec4 ${s}() {
            return ${(0, h.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR);
          }
        `;
            return new l.GlslLibRoutine(e);
          }
          getPackedSampler1D(s, t, e) {
            const r = [e.width, e.height], i = [r[1], r[0]], p = (0, h.getGlsl)(this.context.glContext.version), m = `vec4 ${s}(int index) {
      vec2 uv = packedUVfrom1D(
      ${i[0]}, ${i[1]}, index);
      return ${p.texture2D}(${t}, uv);
    }`;
            return new l.GlslLibRoutine(m, ["coordinates.packedUVfrom1D"]);
          }
          getPackedSampler2D(s, t, e) {
            const r = e.unpackedShape, i = [e.width, e.height], p = (0, h.getGlsl)(this.context.glContext.version), m = i[0], _ = i[1];
            if (i != null && u.ArrayUtil.arraysEqual(r, i)) {
              const T = `vec4 ${s}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${_}.0, ${m}.0);
        return ${p.texture2D}(${t}, uv);
      }`;
              return new l.GlslLibRoutine(T);
            }
            const b = i, y = Math.ceil(r[1] / 2), w = `vec4 ${s}(int row, int col) {
      vec2 uv = packedUVfrom2D(${b[1]}, ${b[0]}, ${y}, row, col);
      return ${p.texture2D}(${t}, uv);
    }`;
            return new l.GlslLibRoutine(w, ["coordinates.packedUVfrom2D"]);
          }
          getPackedSampler3D(s, t, e) {
            const r = e.unpackedShape, i = [e.width, e.height], p = [i[0], i[1]], m = (0, h.getGlsl)(this.context.glContext.version);
            if (r[0] === 1) {
              const T = r.slice(1), S = [1, 2], E = (0, f.squeezeInputShape)(r, T), O = ["b", "row", "col"], v = JSON.parse(JSON.stringify(e));
              v.unpackedShape = E;
              const A = this.getPackedSamplerFromInput(s, t, v), L = `${A.routineBody}
      vec4 ${s}(int b, int row, int col) {
        return ${s}(${(0, f.getSqueezedParams)(O, S)});
      } `;
              return new l.GlslLibRoutine(L, A.dependencies);
            }
            const _ = p[0], b = p[1], y = Math.ceil(r[2] / 2), w = `vec4 ${s}(int b, int row, int col) {
      vec2 uv = packedUVfrom3D(
        ${b}, ${_}, ${y * Math.ceil(r[1] / 2)}, ${y}, b, row, col);
      return ${m.texture2D}(${t}, uv);}`;
            return new l.GlslLibRoutine(w, ["coordinates.packedUVfrom3D"]);
          }
          getPackedSamplerND(s, t, e) {
            const r = e.unpackedShape, i = r.length, p = [e.width, e.height], m = (0, h.getGlsl)(this.context.glContext.version), _ = [p[0], p[1]], b = _[1], y = _[0], w = Math.ceil(r[i - 1] / 2);
            let T = w * Math.ceil(r[i - 2] / 2), S = "int b, int row, int col", E = `b * ${T} + (row / 2) * ${w} + (col / 2)`;
            for (let v = 2; v < i - 1; v++) S = `int b${v}, ` + S, T *= r[i - v - 1], E = `b${v} * ${T} + ` + E;
            const O = `vec4 ${s}(${S}) {
      int index = ${E};
      int texR = index / ${y};
      int texC = index - texR * ${y};
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${y}, ${b});
      return ${m.texture2D}(${t}, uv);
    }`;
            return new l.GlslLibRoutine(O);
          }
          getUnpackedSamplerScalar(s, t, e) {
            const [r, i] = [e.width, e.height];
            if (r === 1 && i === 1) {
              const m = `
          float ${s}() {
            return sampleTexture(${t}, halfCR);
          }
        `;
              return new l.GlslLibRoutine(m, ["coordinates.sampleTexture"]);
            }
            const p = `
        float ${s}() {
          int offset_${t} = coordsToOffset(TexCoords, ${r}, ${i});
          vec2 uv = uvFromFlat(${r}, ${i}, offset_${t});
          return sampleTexture(${t}, uv);
        }
      `;
            return new l.GlslLibRoutine(p, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
          }
          getUnpackedSampler1D(s, t, e) {
            const r = e.width, i = e.height;
            if (i === 1 && r === 1) {
              const m = `
        float ${s}(int index) {
          return sampleTexture(${t}, halfCR);
        }
      `;
              return new l.GlslLibRoutine(m, ["coordinates.sampleTexture"]);
            }
            if (i === 1) {
              const m = `
          float ${s}(int index) {
            vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5);
            return sampleTexture(${t}, uv);
          }
        `;
              return new l.GlslLibRoutine(m, ["coordinates.sampleTexture"]);
            }
            if (r === 1) {
              const m = `
          float ${s}(int index) {
            vec2 uv = vec2(0.5, (float(index) + 0.5) / ${i}.0);
            return sampleTexture(${t}, uv);
          }
        `;
              return new l.GlslLibRoutine(m, ["coordinates.sampleTexture"]);
            }
            const p = `
        float ${s}(int index) {
          vec2 uv = uvFromFlat(${r}, ${i}, index);
          return sampleTexture(${t}, uv);
        }
      `;
            return new l.GlslLibRoutine(p, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
          }
          getUnpackedSampler2D(s, t, e) {
            const r = e.unpackedShape, i = [e.height, e.width];
            if (i != null && u.ArrayUtil.arraysEqual(r, i)) {
              const T = `
          float ${s}(int row, int col) {
            vec2 uv = (vec2(row, col) + halfCR) / vec2(${i[1]}.0, ${i[0]}.0);
            return sampleTexture(${t}, uv);
          }
        `;
              return new l.GlslLibRoutine(T, ["coordinates.sampleTexture"]);
            }
            const { newShape: p, keptDims: m } = (0, a.squeezeShape)(r), _ = p;
            if (_.length < r.length) {
              const T = (0, f.squeezeInputShape)(r, _), S = JSON.parse(JSON.stringify(e));
              S.unpackedShape = T;
              const E = ["col", "row"], O = `
          ${this.getUnpackedSamplerFromInput(s, t, S).routineBody}
          float ${s}(int row, int col) {
            return ${s}(${(0, f.getSqueezedParams)(E, m)});
          }
        `;
              return new l.GlslLibRoutine(O, ["coordinates.sampleTexture"]);
            }
            const b = i[1], y = i[0];
            if (y === 1) {
              const T = `
          float ${s}(int row, int col) {
            int offset_${t} = coordsToOffset(TexCoords, ${b}, ${y});
            float index = dot(vec3(row, col, offset_${t}), vec3(${r[1]}, 1, 1));
            vec2 uv = vec2(0.5, (index + 0.5) / ${b}.0);
            return sampleTexture(${t}, uv);
          }
        `;
              return new l.GlslLibRoutine(T, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
            }
            if (b === 1) {
              const T = `
          float ${s}(int row, int col) {
            int offset_${t} = coordsToOffset(TexCoords, ${b}, ${y});
            float index = dot(vec3(row, col, offset_${t}), vec3(${r[1]}, 1, 1));
            vec2 uv = vec2((index + 0.5) / ${y}.0, 0.5);
            return sampleTexture(${t}, uv);
          }
        `;
              return new l.GlslLibRoutine(T, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
            }
            const w = `
        float ${s}(int row, int col) {
          int index = col * ${r[1]} + row;
          vec2 uv = uvFromFlat(${b}, ${y}, index);
          return sampleTexture(${t}, uv);
        }
      `;
            return new l.GlslLibRoutine(w, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
          }
          getUnpackedSampler3D(s, t, e) {
            const r = e.unpackedShape, i = r[1] * r[2], p = r[2], { newShape: m, keptDims: _ } = (0, a.squeezeShape)(r), b = m;
            if (b.length < r.length) {
              const w = (0, f.squeezeInputShape)(r, b), T = ["batch", "col", "row"], S = JSON.parse(JSON.stringify(e));
              S.unpackedShape = w;
              const E = this.getUnpackedSamplerFromInput(s, t, S), O = _.reverse(), v = `
          ${E.routineBody}
          float ${s}(int batch, int row, int col) {
            return ${s}(${(0, f.getSqueezedParams)(T, O)});
          }
        `;
              return new l.GlslLibRoutine(v, E.dependencies);
            }
            const y = `
          float ${s}(int depth, int row, int col) {
            // Explicitly use integer operations as dot() only works on floats.
            int index = depth * ${i} + col * ${p} + row;
            vec2 uv = uvFromFlat(${e.width}, ${e.height}, index);
            return sampleTexture(${t}, uv);
          }
      `;
            return new l.GlslLibRoutine(y, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
          }
          getUnpackedSampler4D(s, t, e) {
            const r = e.unpackedShape, i = r[3], p = r[2] * i, m = `
        float ${s}(int row, int col, int depth, int depth2) {
          int index = row * ${r[1] * p} + col * ${p} +
              depth2 * ${i} + depth;
          vec2 uv = uvFromFlat(${e.width}, ${e.height}, index);
          return sampleTexture(${t}, uv);
        }
      `;
            return new l.GlslLibRoutine(m, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
          }
          getUnpackedSampler5D(s, t, e) {
            const r = e.unpackedShape, i = r[4], p = r[3] * i, m = r[2] * p, _ = r[1] * m, { newShape: b, keptDims: y } = (0, a.squeezeShape)(r);
            if (b.length < r.length) {
              const T = (0, f.squeezeInputShape)(r, b), S = ["row", "col", "depth", "depth2", "depth3"], E = JSON.parse(JSON.stringify(e));
              E.unpackedShape = T;
              const O = `
          ${this.getUnpackedSamplerFromInput(s, t, E).routineBody}
          float ${s}(int row, int col, int depth, int depth2, int depth3) {
            return ${s}(${(0, f.getSqueezedParams)(S, y)});
          }
        `;
              return new l.GlslLibRoutine(O, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
            }
            const w = `
        float ${s}(int row, int col, int depth, int depth2, int depth3) {
          int index = row * ${_} + col * ${m} + depth * ${p} +
          depth3 * ${i} + depth2;
          vec2 uv = uvFromFlat(${e.width}, ${e.height}, index);
          return sampleTexture(${t}, uv);
        }
      `;
            return new l.GlslLibRoutine(w, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
          }
          getUnpackedSampler6D(s, t, e) {
            const r = e.unpackedShape, i = r[5], p = r[4] * i, m = r[3] * p, _ = r[2] * m, b = r[1] * _, { newShape: y, keptDims: w } = (0, a.squeezeShape)(r);
            if (y.length < r.length) {
              const S = (0, f.squeezeInputShape)(r, y), E = ["row", "col", "depth", "depth2", "depth3", "depth4"], O = JSON.parse(JSON.stringify(e));
              O.unpackedShape = S;
              const v = `
            ${this.getUnpackedSamplerFromInput(s, t, O).routineBody}
            float ${s}(int row, int col, int depth,
              int depth2, int depth3, int depth4) {
              return ${s}(${(0, f.getSqueezedParams)(E, w)});
            }
          `;
              return new l.GlslLibRoutine(v, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
            }
            const T = `
          float ${s}(int row, int col, int depth,
            int depth2, int depth3, int depth4) {
            int index = row * ${b} + col * ${_} + depth * ${m} +
            depth2 * ${p} + depth3 * ${i} + depth4;
            vec2 uv = uvFromFlat(${e.width}, ${e.height}, index);
            return sampleTexture(${t}, uv);
          }
        `;
            return new l.GlslLibRoutine(T, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
          }
          toVec() {
            const s = this.context.outputTextureLayout, t = s.shape.length, e = s.strides, r = s.width, i = s.height, p = [];
            for (let _ = 0; _ < t - 1; ++_) p.push(`
        c[${_}] = offset / ${e[_]};`), p.push(`
        offset -= c[${_}] * ${e[_]};`);
            p.push(`
        c[${t - 1}] = offset;`);
            const m = `
      void toVec(vec2 texCoords, out int c[${t}]) {
        int offset = coordsToOffset(texCoords, ${r}, ${i});
        ${p.join("")}
      }
      void toVec(int offset, out int c[${t}]) {
        ${p.join("")}
      }
    `;
            return { toVec: new l.GlslLibRoutine(m, ["coordinates.coordsToOffset"]) };
          }
          valueFrom() {
            const s = {};
            return this.context.programInfo.inputNames.forEach(((t, e) => {
              const r = this.context.inputTextureLayouts[e], i = (r.unpackedShape.length > 0 ? r.unpackedShape : r.shape).length;
              let p = `_${t}`;
              s[p] = new l.GlslLibRoutine(this.getValueFromSingle(t, i, r.width, r.height, !1), [`shapeUtils.indicesToOffset${p}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), p += "_T", s[p] = new l.GlslLibRoutine(this.getValueFromSingle(t, i, r.width, r.height, !0), [`shapeUtils.indicesToOffset${p}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]);
            })), s;
          }
          getValueFromSingle(s, t, e, r, i) {
            let p = `_${s}`;
            return i && (p += "_T"), `
        float ${p}(int m[${t}]) {
          int offset = indicesToOffset${p}(m);
          vec2 coords = offsetToCoords(offset, ${e}, ${r});
          float value = getColorAsFloat(${(0, h.getGlsl)(this.context.glContext.version).texture2D}(${s}, coords));
          return value;
        }
        `;
          }
          getPackedValueFrom(s, t, e, r, i) {
            let p = `_${s}_Pack`;
            return i && (p += "_T"), `
        vec4 ${p}(int m[${t}]) {
          int offset = indicesToOffset_${s}(m);
          vec2 coords = offsetToCoords(offset, ${e}, ${r});
          return ${(0, h.getGlsl)(this.context.glContext.version).texture2D}(${s}, coords);
        }
        `;
          }
        }
        n.CoordsGlslLib = g;
      }, 8520: (d, n) => {
        var o;
        Object.defineProperty(n, "__esModule", { value: !0 }), n.TopologicalSortGlslRoutines = n.GlslLibRoutineNode = n.GlslLibRoutine = n.GlslLib = n.GlslContext = n.FunctionType = void 0, (o = n.FunctionType || (n.FunctionType = {}))[o.ValueBased = 0] = "ValueBased", o[o.Positional = 1] = "Positional", n.GlslContext = class {
          constructor(u, l, h, a) {
            this.glContext = u, this.programInfo = l, this.inputTextureLayouts = h, this.outputTextureLayout = a;
          }
        }, n.GlslLib = class {
          constructor(u) {
            this.context = u;
          }
        }, n.GlslLibRoutine = class {
          constructor(u, l) {
            this.routineBody = u, this.dependencies = l;
          }
        }, n.GlslLibRoutineNode = class {
          constructor(u, l, h) {
            this.name = u, this.dependencies = h || [], l && (this.routineBody = l);
          }
          addDependency(u) {
            u && this.dependencies.push(u);
          }
        }, n.TopologicalSortGlslRoutines = class {
          static returnOrderedNodes(u) {
            if (!u || u.length === 0) return [];
            if (u.length === 1) return u;
            const l = /* @__PURE__ */ new Set(), h = /* @__PURE__ */ new Set(), a = new Array();
            return this.createOrderedNodes(u, l, h, a), a;
          }
          static createOrderedNodes(u, l, h, a) {
            for (let f = 0; f < u.length; ++f) this.dfsTraverse(u[f], l, h, a);
          }
          static dfsTraverse(u, l, h, a) {
            if (!u || h.has(u.name)) return;
            if (l.has(u.name)) throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");
            l.add(u.name);
            const f = u.dependencies;
            if (f && f.length > 0) for (let g = 0; g < f.length; ++g) this.dfsTraverse(f[g], l, h, a);
            a.push(u), h.add(u.name), l.delete(u.name);
          }
        };
      }, 7341: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.EncodingGlslLib = void 0;
        const u = o(8520);
        class l extends u.GlslLib {
          constructor(a) {
            super(a);
          }
          getFunctions() {
            return Object.assign(Object.assign({}, this.encodeFloat32()), this.decodeFloat32());
          }
          getCustomTypes() {
            return {};
          }
          encodeFloat32() {
            return { encode: new u.GlslLibRoutine(`highp vec4 encode(highp float f) {
        return vec4(f, 0.0, 0.0, 0.0);
      }
        `) };
          }
          decodeFloat32() {
            return { decode: new u.GlslLibRoutine(`highp float decode(highp vec4 rgba) {
        return rgba.r;
      }
        `) };
          }
          encodeUint8() {
            const a = l.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : "";
            return { encode: new u.GlslLibRoutine(`
      highp vec4 encode(highp float f) {
        highp float F = abs(f);
        highp float Sign = step(0.0,-f);
        highp float Exponent = floor(log2(F));
        highp float Mantissa = (exp2(- Exponent) * F);
        Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));
        highp vec4 rgba;
        rgba[0] = 128.0 * Sign  + floor(Exponent*exp2(-1.0));
        rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);
        rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));
        rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));
        ${a}
        rgba = rgba / 255.0; // values need to be normalized to [0,1]
        return rgba;
    }
        `) };
          }
          decodeUint8() {
            const a = l.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : "";
            return { decode: new u.GlslLibRoutine(`
        highp float decode(highp vec4 rgba) {
          rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]
          ${a}
          highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;
          highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;
          highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);
          highp float Result =  Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));
          return Result;
      }
        `) };
          }
          static isLittleEndian() {
            const a = new ArrayBuffer(4), f = new Uint32Array(a), g = new Uint8Array(a);
            if (f[0] = 3735928559, g[0] === 239) return !0;
            if (g[0] === 222) return !1;
            throw new Error("unknown endianness");
          }
        }
        n.EncodingGlslLib = l;
      }, 9894: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.FragColorGlslLib = void 0;
        const u = o(8520), l = o(5060);
        class h extends u.GlslLib {
          constructor(f) {
            super(f);
          }
          getFunctions() {
            return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat());
          }
          getCustomTypes() {
            return {};
          }
          setFragColor() {
            const f = (0, l.getGlsl)(this.context.glContext.version);
            return { setFragColor: new u.GlslLibRoutine(`
        void setFragColor(float value) {
            ${f.output} = encode(value);
        }
        `, ["encoding.encode"]) };
          }
          getColorAsFloat() {
            return { getColorAsFloat: new u.GlslLibRoutine(`
        float getColorAsFloat(vec4 color) {
            return decode(color);
        }
        `, ["encoding.decode"]) };
          }
        }
        n.FragColorGlslLib = h;
      }, 2848: (d, n) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.replaceInlines = void 0;
        const o = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;
        n.replaceInlines = function(u) {
          const l = {};
          let h;
          for (; (h = o.exec(u)) !== null; ) {
            const a = h[3].split(",").map(((f) => {
              const g = f.trim().split(" ");
              return g && g.length === 2 ? { type: g[0], name: g[1] } : null;
            })).filter(((f) => f !== null));
            l[h[2]] = { params: a, body: h[4] };
          }
          for (const a in l) {
            const f = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__", a), g = new RegExp(f, "gm");
            for (; (h = g.exec(u)) !== null; ) {
              const c = h[1], s = h[2], t = h[3].split(","), e = c ? `${c} ${s};` : "";
              let r = l[a].body, i = "";
              l[a].params.forEach(((m, _) => {
                m && (i += `${m.type} ${m.name} = ${t[_]};
`);
              })), r = `${i}
 ${r}`, r = r.replace("return", `${s} = `);
              const p = `
      ${e}
      {
        ${r}
      }
      `;
              u = u.replace(h[0], p);
            }
          }
          return u.replace(o, "");
        };
      }, 8879: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.GlslPreprocessor = void 0;
        const u = o(8520), l = o(2848), h = o(5483), a = o(5060);
        n.GlslPreprocessor = class {
          constructor(f, g, c, s) {
            this.libs = {}, this.glslLibRoutineDependencyGraph = {}, this.context = new u.GlslContext(f, g, c, s), Object.keys(h.glslRegistry).forEach(((e) => {
              const r = new h.glslRegistry[e](this.context);
              this.libs[e] = r;
            }));
            const t = this.glslLibRoutineDependencyGraph;
            for (const e in this.libs) {
              const r = this.libs[e].getFunctions();
              for (const i in r) {
                const p = e + "." + i;
                let m;
                t[p] ? (m = t[p], m.routineBody = r[i].routineBody) : (m = new u.GlslLibRoutineNode(p, r[i].routineBody), t[p] = m);
                const _ = r[i].dependencies;
                if (_) for (let b = 0; b < _.length; ++b) if (t[_[b]]) m.addDependency(t[_[b]]);
                else {
                  const y = new u.GlslLibRoutineNode(_[b]);
                  t[_[b]] = y, m.addDependency(y);
                }
              }
            }
          }
          preprocess() {
            const f = this.context.programInfo;
            let g = f.shaderSource;
            return this.context.programInfo.hasMain || (g = `${g}
      ${(0, a.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), g = (0, l.replaceInlines)(g), `${(0, a.getFragShaderPreamble)(this.context.glContext.version)}
    ${this.getUniforms(f.inputNames, f.variables)}
    ${this.getImports(g)}
    ${g}`;
          }
          getImports(f) {
            const g = this.selectGlslLibRoutinesToBeIncluded(f);
            if (g.length === 0) return "";
            let c = "";
            for (let s = 0; s < g.length; ++s) {
              if (!g[s].routineBody) throw new Error(`Missing body for the Glsl Library routine: ${g[s].name}`);
              c += g[s].routineBody + `
`;
            }
            return c;
          }
          selectGlslLibRoutinesToBeIncluded(f) {
            const g = [];
            return Object.keys(this.glslLibRoutineDependencyGraph).forEach(((c) => {
              const s = c.split(".")[1];
              f.indexOf(s) !== -1 && g.push(this.glslLibRoutineDependencyGraph[c]);
            })), u.TopologicalSortGlslRoutines.returnOrderedNodes(g);
          }
          getUniforms(f, g) {
            const c = [];
            if (f) for (const s of f) c.push(`uniform sampler2D ${s};`);
            if (g) for (const s of g) c.push(`uniform ${s.type} ${s.name}${s.arrayLength ? `[${s.arrayLength}]` : ""};`);
            return c.join(`
`);
          }
        };
      }, 5483: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.glslRegistry = void 0;
        const u = o(5107), l = o(7341), h = o(9894), a = o(2655), f = o(3891);
        n.glslRegistry = { encoding: l.EncodingGlslLib, fragcolor: h.FragColorGlslLib, vec: f.VecGlslLib, shapeUtils: a.ShapeUtilsGlslLib, coordinates: u.CoordsGlslLib };
      }, 2655: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.ShapeUtilsGlslLib = void 0;
        const u = o(8520);
        class l extends u.GlslLib {
          constructor(a) {
            super(a);
          }
          getFunctions() {
            return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.bcastIndex()), this.bcastMatmulIndex()), this.offsetToIndices()), this.indicesToOffset()), this.incrementIndices());
          }
          getCustomTypes() {
            return {};
          }
          bcastIndex() {
            const a = this.context.outputTextureLayout.shape.length, f = {};
            return this.context.programInfo.inputNames.forEach(((g, c) => {
              const s = this.context.inputTextureLayouts[c].unpackedShape;
              if (s.length <= a) {
                const t = s.length, e = a - t, r = `bcastIndices_${g}`;
                let i = "";
                for (let m = 0; m < t; ++m) i += `
          realIndices[${m}] = int( mod(float(bcastedIndices[${e + m}]), ${s[m]}.0) );
          `;
                const p = `
        void ${r} (int bcastedIndices[${a}], out int realIndices[${t}]) {
          ${i}
        }
        `;
                f[r] = new u.GlslLibRoutine(p);
              }
            })), f;
          }
          bcastMatmulIndex() {
            const a = this.context.outputTextureLayout.shape.length, f = {};
            return this.context.programInfo.inputNames.forEach(((g, c) => {
              const s = this.context.inputTextureLayouts[c].shape;
              if (!(s.length < 2 || s.length > a)) {
                const t = s.length, e = a - t, r = `bcastMatmulIndices_${g}`;
                let i = "";
                for (let m = 0; m < t - 2; ++m) i += `
          realIndices[${m}] = int( mod(float(bcastedIndices[${e + m}]), ${s[m]}.0) );
          `;
                const p = `
        void ${r}(int bcastedIndices[${a}], out int realIndices[${t}]) {
          ${i}
          realIndices[${t - 1}] = bcastedIndices[${a - 1}];
          realIndices[${t - 2}] = bcastedIndices[${a - 2}];
        }
        `;
                f[r] = new u.GlslLibRoutine(p);
              }
            })), f;
          }
          indicesToOffset() {
            const a = {};
            return this.context.programInfo.inputNames.forEach(((f, g) => {
              const c = this.context.inputTextureLayouts[g].shape, s = this.context.inputTextureLayouts[g].strides, t = c.length;
              let e = `indicesToOffset_${f}`;
              a[e] = new u.GlslLibRoutine(l.indexToOffsetSingle(e, t, s)), e = `indicesToOffset_${f}_T`, a[e] = new u.GlslLibRoutine(l.indexToOffsetSingle(e, t, s.slice().reverse()));
            })), a;
          }
          static indexToOffsetSingle(a, f, g) {
            let c = "";
            for (let s = f - 1; s >= 0; --s) c += `
        offset += indices[${s}] * ${g[s]};
        `;
            return `
      int ${a}(int indices[${f}]) {
        int offset = 0;
        ${c}
        return offset;
      }
      `;
          }
          offsetToIndices() {
            const a = {};
            return this.context.programInfo.inputNames.forEach(((f, g) => {
              const c = this.context.inputTextureLayouts[g].shape, s = this.context.inputTextureLayouts[g].strides, t = c.length;
              let e = `offsetToIndices_${f}`;
              a[e] = new u.GlslLibRoutine(l.offsetToIndicesSingle(e, t, s)), e = `offsetToIndices_${f}_T`, a[e] = new u.GlslLibRoutine(l.offsetToIndicesSingle(e, t, s.slice().reverse()));
            })), a;
          }
          static offsetToIndicesSingle(a, f, g) {
            const c = [];
            for (let s = 0; s < f - 1; ++s) c.push(`
      indices[${s}] = offset / ${g[s]};`), c.push(`
        offset -= indices[${s}] * ${g[s]};`);
            return c.push(`
      indices[${f - 1}] = offset;`), `
      void ${a}(int offset, out int indices[${f}]) {
        ${c.join("")}
      }
      `;
          }
          incrementIndices() {
            const a = {};
            return this.context.programInfo.inputNames.forEach(((f, g) => {
              const c = this.context.inputTextureLayouts[g].shape, s = c.length, t = `incrementIndices_${f}`;
              let e = "";
              for (let i = 0; i < s; ++i) e += `
        shape[${i}] = ${c[i]};`;
              const r = `
        void ${t}(int axis, out int indices[${s}]) {
          int shape[${s}];
          ${e};
          for(int i = ${s} -1 ; i >= 0; --i) {
            if(i > axis) continue;
            indices[i] += 1;
            if(indices[i] < shape[i]) {
              break;
            }
            indices[i] = 0;
          }
        }
        `;
              a[t] = new u.GlslLibRoutine(r);
            })), a;
          }
        }
        n.ShapeUtilsGlslLib = l;
      }, 5060: (d, n) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.getDefaultFragShaderMain = n.getFragShaderPreamble = n.getVertexShaderSource = n.getGlsl = void 0;
        const o = { version: "", attribute: "attribute", varyingVertex: "varying", varyingFrag: "varying", texture2D: "texture2D", output: "gl_FragColor", outputDeclaration: "" }, u = { version: "#version 300 es", attribute: "in", varyingVertex: "out", varyingFrag: "in", texture2D: "texture", output: "outputColor", outputDeclaration: "out vec4 outputColor;" };
        function l(h) {
          return h === 1 ? o : u;
        }
        n.getGlsl = l, n.getVertexShaderSource = function(h) {
          const a = l(h);
          return `${a.version}
      precision highp float;
      ${a.attribute} vec3 position;
      ${a.attribute} vec2 textureCoord;

      ${a.varyingVertex} vec2 TexCoords;

      void main()
      {
          gl_Position = vec4(position, 1.0);
          TexCoords = textureCoord;
      }`;
        }, n.getFragShaderPreamble = function(h) {
          const a = l(h);
          return `${a.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${a.varyingFrag} vec2 TexCoords;
    ${a.outputDeclaration}
    const vec2 halfCR = vec2(0.5, 0.5);

    // Custom vector types to handle higher dimenalities.
    struct ivec5
    {
      int x;
      int y;
      int z;
      int w;
      int u;
    };

    struct ivec6
    {
      int x;
      int y;
      int z;
      int w;
      int u;
      int v;
    };

    int imod(int x, int y) {
      return x - y * (x / y);
    }

    `;
        }, n.getDefaultFragShaderMain = function(h, a) {
          return `
  void main() {
    int indices[${a}];
    toVec(TexCoords, indices);
    vec4 result = vec4(process(indices));
    ${l(h).output} = result;
  }
  `;
        };
      }, 3891: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.VecGlslLib = void 0;
        const u = o(8520);
        class l extends u.GlslLib {
          constructor(a) {
            super(a);
          }
          getCustomTypes() {
            return {};
          }
          getFunctions() {
            return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem());
          }
          binaryVecFunctions() {
            const a = this.context.outputTextureLayout.shape.length, f = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, g = {};
            for (const c in f) {
              const s = `${c}Vec`;
              let t = "";
              for (let r = 0; r < a; ++r) t += `
          dest[${r}] ${f[c]} src[${r}];
          `;
              const e = `
        void ${s}(int src[${a}], out int dest[${a}]) {
          ${t}
        }
        `;
              g[s] = new u.GlslLibRoutine(e);
            }
            return g;
          }
          copyVec() {
            const a = this.context.outputTextureLayout.shape.length;
            let f = "";
            for (let c = 0; c < a; ++c) f += `
        dest[${c}] = src[${c}];
        `;
            const g = `
      void copyVec(int src[${a}], out int dest[${a}]) {
        ${f}
      }
      `;
            return { copyVec: new u.GlslLibRoutine(g) };
          }
          setVecItem() {
            const a = this.context.outputTextureLayout.shape.length;
            let f = `
        if(index < 0)
            index =${a} + index;
        if (index == 0)
            m[0] = value;
        `;
            for (let c = 1; c < a - 1; ++c) f += `
        else if (index == ${c})
            m[${c}] = value;
            `;
            f += `
        else
            m[${a - 1}] = value;
        `;
            const g = `
      void setVecItem(out int m[${a}], int index, int value) {
        ${f}
      }
        `;
            return { setVecItem: new u.GlslLibRoutine(g) };
          }
          getVecItem() {
            const a = this.context.outputTextureLayout.shape.length;
            let f = `
        if(index < 0)
            index = ${a} + index;
        if (index == 0)
            return m[0];
      `;
            for (let c = 1; c < a - 1; ++c) f += `
        else if (index == ${c})
            return m[${c}];
      `;
            f += `
        else
            return m[${a - 1}];
        `;
            const g = `
      int getVecItem(int m[${a}], int index) {
        ${f}
      }
    `;
            return { getVecItem: new u.GlslLibRoutine(g) };
          }
        }
        n.VecGlslLib = l;
      }, 8316: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.WebGLInferenceHandler = void 0;
        const u = o(6231), l = o(9162), h = o(2517), a = o(2403), f = o(7019), g = o(8710), c = o(5611), s = o(4057), t = o(2039);
        n.WebGLInferenceHandler = class {
          constructor(e) {
            this.session = e, this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
          }
          calculateTextureWidthAndHeight(e, r) {
            return (0, s.calculateTextureWidthAndHeight)(this.session.layoutStrategy, e, r);
          }
          executeProgram(e, r) {
            if (r.length < e.inputNames.length) throw new Error(`Input size mustn't be less than ${e.inputNames.length}.`);
            if (e.inputNames.length !== e.inputTypes.length) throw new Error("input names size does not match input types");
            const i = [];
            for (let w = 0; w < e.inputNames.length; ++w) i[w] = this.getOrCreateTextureData(r[w], e.inputTypes[w]);
            const p = ((w, T) => {
              const S = T.map(((O) => `${O.unpackedShape.join(",")};${O.width}x${O.height}`)).join("_");
              let E = w.name;
              return w.cacheHint && (E += "[" + w.cacheHint + "]"), E += ":" + S, E;
            })(e, i);
            let m = this.session.programManager.getArtifact(p);
            const _ = m ? m.programInfo : typeof e.get == "function" ? e.get() : e, b = (0, s.createTextureLayoutFromTextureType)(this.session.layoutStrategy, _.output.dims, _.output.textureType), y = this.createTextureData(b, _.output.type);
            return m || (m = this.session.programManager.build(_, i, y), this.session.programManager.setArtifact(p, m)), this.runProgram(m, i, y), y;
          }
          run(e, r) {
            return this.executeProgram(e, r).tensor;
          }
          runProgram(e, r, i) {
            for (let p = 0; p < r.length; ++p) if (!!r[p].isPacked != (e.programInfo.inputTypes[p] === t.TextureType.packed)) throw new Error(`input[${p}] property packed inconsistent`);
            if (!!i.isPacked != (e.programInfo.output.textureType === t.TextureType.packed)) throw new Error("output property packed inconsistent");
            this.session.programManager.run(e, r, i);
          }
          getOrCreateTextureData(e, r) {
            let i = this.getTextureData(e.dataId, r === t.TextureType.packed);
            if (!i && (i = this.getTextureData(e.dataId, r !== t.TextureType.packed), i)) return r === t.TextureType.packed ? this.pack(i) : this.unpack(i);
            if (!i) {
              const p = (0, s.createTextureLayoutFromTextureType)(this.session.layoutStrategy, e.dims, r);
              if (r === t.TextureType.packedLastDimension) {
                const b = e.dims;
                if (b.length === 4) {
                  const y = [b[0], Math.ceil(b[1] * b[2] * b[3] / 4)], w = (0, s.createTextureLayoutFromTextureType)(this.session.layoutStrategy, y, r);
                  let T = e.numberData;
                  if (b[1] * b[2] * b[3] % 4 != 0) {
                    const S = b[0], E = b[1] * b[2] * b[3], O = Math.ceil(E * 1 / 4) * 4;
                    T = new Float32Array(S * O);
                    for (let v = 0; v < S; ++v) {
                      const A = v * E, L = v * O + v % 1 * E;
                      T.set(e.numberData.subarray(A, A + E), L);
                    }
                  }
                  return this.createTextureData(w, e.type, T, e, 1);
                }
              }
              if (r === t.TextureType.packed) {
                const m = (0, s.createTextureLayoutFromShape)(this.session.layoutStrategy, e.dims, 1, [], { reverseWH: !0 }), _ = this.createTextureData(m, e.type, e.numberData, e, 1);
                i = this.pack(_);
              } else i = this.createTextureData(p, e.type, e.numberData, e, 1);
            }
            return i;
          }
          createTextureDataFromLayoutBindTensor(e, r, i, p) {
            return this.createTextureData(e, r, i, p, 1);
          }
          createTextureData(e, r, i, p, m) {
            u.Logger.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(e)}]`);
            const _ = this.session.textureManager.createTextureFromLayout(r, e, i, m);
            return this.createTextureDataFromTexture(e, r, _, p);
          }
          reshapeUnpacked(e, r) {
            const i = this.getOrCreateTextureData(e, t.TextureType.unpacked), p = { channels: i.channels, height: i.height, width: i.width, shape: r.length !== 0 ? r : [1], strides: h.ShapeUtil.computeStrides(r), unpackedShape: r };
            return this.createTextureDataFromTexture(p, e.type, i.texture).tensor;
          }
          reshapePacked(e, r) {
            const i = this.getOrCreateTextureData(e, t.TextureType.packed);
            if ((0, f.isReshapeCheap)(e.dims, r)) {
              const y = { channels: i.channels, height: i.height, width: i.width, shape: r.length !== 0 ? r : [1], strides: h.ShapeUtil.computeStrides(r), unpackedShape: r, isPacked: !0 };
              return this.createTextureDataFromTexture(y, e.type, i.texture).tensor;
            }
            const p = (0, f.processDims3D)(e.dims), m = (0, f.processDims3D)(r), _ = this.reshapePacked(e, p), b = this.run((0, f.createPackedReshape3DProgramInfoLoader)(this, _, m), [_]);
            return this.reshapePacked(b, r);
          }
          cast(e, r) {
            const i = this.getOrCreateTextureData(e, t.TextureType.unpacked);
            return this.createTextureDataFromTexture(i, r, i.texture).tensor;
          }
          createTextureDataFromTexture(e, r, i, p, m) {
            const _ = Object.assign(Object.assign({}, e), { tensor: p || new l.Tensor(e.unpackedShape, r, ((b) => this.readTexture(_)), (async (b) => this.readTextureAsync(_)), void 0, m), texture: i });
            return this.setTextureData(_.tensor.dataId, _, e.isPacked), _;
          }
          getTextureData(e, r = !1) {
            return this.session.isInitializer(e) ? this.session.getTextureData(e, r) : r ? this.packedTextureDataCache.get(e) : this.unpackedTextureDataCache.get(e);
          }
          setTextureData(e, r, i = !1) {
            this.session.isInitializer(e) ? this.session.setTextureData(e, r, i) : (i ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(e, r);
          }
          isTextureLayoutCached(e, r = !1) {
            return !!this.getTextureData(e.dataId, r);
          }
          dispose() {
            this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach(((e) => this.session.textureManager.releaseTexture(e))), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach(((e) => this.session.textureManager.releaseTexture(e))), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
          }
          readTexture(e) {
            return e.isPacked ? this.readTexture(this.unpack(e)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(e, e.tensor.type, e.channels) : this.session.textureManager.readUint8TextureAsFloat((0, g.encodeAsUint8)(this, e));
          }
          async readTextureAsync(e) {
            return e.isPacked ? this.readTextureAsync(this.unpack(e)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(e, e.tensor.type, e.channels) : this.session.textureManager.readUint8TextureAsFloat((0, g.encodeAsUint8)(this, e));
          }
          pack(e) {
            return this.executeProgram((0, a.createPackProgramInfoLoader)(this, e.tensor), [e.tensor]);
          }
          unpack(e) {
            return this.executeProgram((0, c.createUnpackProgramInfoLoader)(this, e.tensor), [e.tensor]);
          }
        };
      }, 1640: function(d, n, o) {
        var u = this && this.__createBinding || (Object.create ? function(Y, te, ne, me) {
          me === void 0 && (me = ne);
          var Ae = Object.getOwnPropertyDescriptor(te, ne);
          Ae && !("get" in Ae ? !te.__esModule : Ae.writable || Ae.configurable) || (Ae = { enumerable: !0, get: function() {
            return te[ne];
          } }), Object.defineProperty(Y, me, Ae);
        } : function(Y, te, ne, me) {
          me === void 0 && (me = ne), Y[me] = te[ne];
        }), l = this && this.__setModuleDefault || (Object.create ? function(Y, te) {
          Object.defineProperty(Y, "default", { enumerable: !0, value: te });
        } : function(Y, te) {
          Y.default = te;
        }), h = this && this.__importStar || function(Y) {
          if (Y && Y.__esModule) return Y;
          var te = {};
          if (Y != null) for (var ne in Y) ne !== "default" && Object.prototype.hasOwnProperty.call(Y, ne) && u(te, Y, ne);
          return l(te, Y), te;
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), n.WEBGL_OP_RESOLVE_RULES = void 0;
        const a = o(2898), f = h(o(7839)), g = o(4196), c = o(2069), s = o(8138), t = o(9663), e = o(5193), r = o(7992), i = o(1253), p = o(4776), m = o(6572), _ = o(3346), b = o(5623), y = o(2870), w = o(2143), T = o(4939), S = o(718), E = o(2268), O = o(8117), v = o(2278), A = o(5524), L = o(5975), j = o(3933), B = o(6558), F = o(5723), D = o(3738), I = h(o(4909)), $ = o(8428), Q = o(9793);
        n.WEBGL_OP_RESOLVE_RULES = [["Abs", "", "6+", I.abs], ["Acos", "", "7+", I.acos], ["Add", "", "7+", f.add], ["And", "", "7+", f.and], ["Asin", "", "7+", I.asin], ["Atan", "", "7+", I.atan], ["AveragePool", "", "7+", w.averagePool, w.parseAveragePoolAttributes], ["BatchNormalization", "", "7+", a.batchNormalization, a.parseBatchNormalizationAttributes], ["Cast", "", "6+", g.cast, g.parseCastAttributes], ["Ceil", "", "6+", I.ceil], ["Clip", "", "6-10", I.clip, I.parseClipAttributes], ["Clip", "", "11+", I.clipV11], ["Concat", "", "4+", c.concat, c.parseConcatAttributes], ["Conv", "", "1+", s.conv, s.parseConvAttributes], ["ConvTranspose", "", "1+", t.convTranspose, t.parseConvTransposeAttributes], ["Cos", "", "7+", I.cos], ["Div", "", "7+", f.div], ["Dropout", "", "7+", I.identity], ["DepthToSpace", "", "1+", e.depthToSpace, e.parseDepthToSpaceAttributes], ["Equal", "", "7+", f.equal], ["Elu", "", "6+", I.elu, I.parseEluAttributes], ["Exp", "", "6+", I.exp], ["Flatten", "", "1+", r.flatten, r.parseFlattenAttributes], ["Floor", "", "6+", I.floor], ["FusedConv", "com.microsoft", "1+", s.conv, s.parseConvAttributes], ["Gather", "", "1+", i.gather, i.parseGatherAttributes], ["Gemm", "", "7-10", p.gemm, p.parseGemmAttributesV7], ["Gemm", "", "11+", p.gemm, p.parseGemmAttributesV11], ["GlobalAveragePool", "", "1+", w.globalAveragePool, w.parseGlobalAveragePoolAttributes], ["GlobalMaxPool", "", "1+", w.globalMaxPool], ["Greater", "", "7+", f.greater], ["Identity", "", "1+", I.identity], ["ImageScaler", "", "1+", m.imageScaler, m.parseImageScalerAttributes], ["InstanceNormalization", "", "6+", _.instanceNormalization, _.parseInstanceNormalizationAttributes], ["LeakyRelu", "", "6+", I.leakyRelu, I.parseLeakyReluAttributes], ["Less", "", "7+", f.less], ["Log", "", "6+", I.log], ["MatMul", "", "1+", b.matMul, b.parseMatMulAttributes], ["MaxPool", "", "1+", w.maxPool, w.parseMaxPoolAttributes], ["Mul", "", "7+", f.mul], ["Neg", "", "6+", I.neg], ["Not", "", "1+", I.not], ["Or", "", "7+", f.or], ["Pad", "", "2-10", y.padV2, y.parsePadAttributesV2], ["Pad", "", "11+", y.padV11, y.parsePadAttributesV11], ["Pow", "", "7+", f.pow], ["PRelu", "", "7+", f.pRelu], ["ReduceLogSum", "", "1+", T.reduceLogSum, T.parseReduceAttributes], ["ReduceMax", "", "1+", T.reduceMax, T.parseReduceAttributes], ["ReduceMean", "", "1+", T.reduceMean, T.parseReduceAttributes], ["ReduceMin", "", "1+", T.reduceMin, T.parseReduceAttributes], ["ReduceProd", "", "1+", T.reduceProd, T.parseReduceAttributes], ["ReduceSum", "", "1-12", T.reduceSum, T.parseReduceAttributes], ["ReduceSumSquare", "", "1+", T.reduceLogSumSquare, T.parseReduceAttributes], ["Relu", "", "6+", I.relu], ["Reshape", "", "5+", S.reshape], ["Resize", "", "10", E.resize, E.parseResizeAttributesV10], ["Resize", "", "11+", E.resize, E.parseResizeAttributesV11], ["Shape", "", "1+", O.shape], ["Sigmoid", "", "6+", I.sigmoid], ["Sin", "", "7+", I.sin], ["Slice", "", "10+", v.sliceV10], ["Slice", "", "1-9", v.slice, v.parseSliceAttributes], ["Softmax", "", "1-12", A.softmax, A.parseSoftmaxAttributes], ["Softmax", "", "13+", A.softmaxV13, A.parseSoftmaxAttributesV13], ["Split", "", "2-12", L.split, L.parseSplitAttributes], ["Sqrt", "", "6+", I.sqrt], ["Squeeze", "", "1-12", j.squeeze, j.parseSqueezeAttributes], ["Squeeze", "", "13+", j.squeezeV13], ["Sub", "", "7+", f.sub], ["Sum", "", "6+", B.sum], ["Tan", "", "7+", I.tan], ["Tanh", "", "6+", I.tanh], ["Tile", "", "6+", F.tile], ["Transpose", "", "1+", D.transpose, D.parseTransposeAttributes], ["Upsample", "", "7-8", Q.upsample, Q.parseUpsampleAttributesV7], ["Upsample", "", "9", Q.upsample, Q.parseUpsampleAttributesV9], ["Unsqueeze", "", "1-12", $.unsqueeze, $.parseUnsqueezeAttributes], ["Unsqueeze", "", "13+", $.unsqueezeV13], ["Xor", "", "7+", f.xor]];
      }, 2898: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseBatchNormalizationAttributes = n.batchNormalization = void 0;
        const u = o(246), l = o(5060), h = o(2039), a = { name: "BatchNormalization", inputNames: ["A", "Scale", "B", "Mean", "Variance"], inputTypes: [h.TextureType.unpacked, h.TextureType.unpacked, h.TextureType.unpacked, h.TextureType.unpacked, h.TextureType.unpacked] };
        n.batchNormalization = (c, s, t) => (g(s), [c.run(Object.assign(Object.assign({}, a), { cacheHint: t.cacheKey, get: () => f(c, s, t) }), s)]), n.parseBatchNormalizationAttributes = (c) => {
          const s = c.attributes.getFloat("epsilon", 1e-5), t = c.attributes.getFloat("momentum", 0.9), e = c.attributes.getInt("spatial", 1);
          return (0, u.createAttributeWithCacheKey)({ epsilon: s, momentum: t, spatial: e });
        };
        const f = (c, s, t) => {
          const e = (0, l.getGlsl)(c.session.backend.glContext.version), r = s[0].dims.length, [i, p] = c.calculateTextureWidthAndHeight(s[1].dims, h.TextureType.unpacked), m = `
  float process(int[${r}] indices) {
    vec2 position = offsetToCoords(indices[1], ${i}, ${p});
    float scale = getColorAsFloat(${e.texture2D}(Scale, position));
    float mean = getColorAsFloat(${e.texture2D}(Mean, position));
    float variance = getColorAsFloat(${e.texture2D}(Variance, position));
    float b = getColorAsFloat(${e.texture2D}(B, position));

    return scale * ( (_A(indices) - mean) / sqrt(variance + float(${t.epsilon})) ) + b;
  }`;
          return Object.assign(Object.assign({}, a), { output: { dims: s[0].dims, type: s[0].type, textureType: h.TextureType.unpacked }, shaderSource: m });
        }, g = (c) => {
          if (!c || c.length !== 5) throw new Error("BatchNormalization requires 5 inputs.");
          const s = c[0], t = c[1], e = c[2], r = c[3], i = c[4];
          if (s.dims.length < 3 || t.dims.length !== 1 || e.dims.length !== 1 || r.dims.length !== 1 || i.dims.length !== 1) throw new Error("invalid input shape.");
          if (t.dims[0] !== s.dims[1] || e.dims[0] !== s.dims[1] || r.dims[0] !== s.dims[1] || i.dims[0] !== s.dims[1]) throw new Error("invalid input shape.");
          if (s.type !== "float32" && s.type !== "float64" || t.type !== "float32" && t.type !== "float64" || e.type !== "float32" && e.type !== "float64" || r.type !== "float32" && r.type !== "float64" || i.type !== "float32" && i.type !== "float64") throw new Error("invalid input tensor types.");
        };
      }, 7839: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.xor = n.sub = n.pRelu = n.pow = n.or = n.mul = n.less = n.greater = n.equal = n.div = n.and = n.add = n.glslPRelu = n.glslPow = n.glslXor = n.glslOr = n.glslAnd = n.glslLess = n.glslGreater = n.glslEqual = n.glslSub = n.glslMul = n.glslDiv = n.glslAdd = void 0;
        const u = o(2517), l = o(8520), h = o(5060), a = o(2039);
        function f() {
          const T = "add_";
          return { body: `
  float ${T}(float a, float b) {
    return a + b;
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return v1 + v2;
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function g() {
          const T = "div_";
          return { body: `
  float ${T}(float a, float b) {
    return a / b;
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return v1 / v2;
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function c() {
          const T = "mul_";
          return { body: `
  float ${T}(float a, float b) {
    return a * b;
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return v1 * v2;
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function s() {
          const T = "sub_";
          return { body: `
  float ${T}(float a, float b) {
    return a - b;
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return v1 - v2;
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function t() {
          const T = "equal_";
          return { body: `
  float ${T}(float a, float b) {
    return float(a == b);
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return vec4(equal(v1, v2));
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function e() {
          const T = "greater_";
          return { body: `
  float ${T}(float a, float b) {
    return float(a > b);
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return vec4( v1.r > v2.r ,
      v1.g > v2.g,
      v1.b > v2.b,
      v1.a > v2.a );
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function r() {
          const T = "less_";
          return { body: `
  float ${T}(float a, float b) {
    return float(a < b);
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return vec4( v1.r < v2.r ,
                v1.g < v2.g,
                v1.b < v2.b,
                v1.a < v2.a );
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function i() {
          const T = "and_";
          return { body: `
  float ${T}(float a, float b) {
    return float( bool(a) && bool(b) );
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    bvec4 b1 = bvec4(v1);
    bvec4 b2 = bvec4(v2);
    return vec4( b1.r && b2.r ,
                b1.g && b2.g,
                b1.b && b2.b,
                b1.a && b2.a );
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function p() {
          return { body: `
  float or_(float a, float b) {
    return float( bool(a) || bool(b) );
  }
  vec4 or_(vec4 v1, vec4 v2) {
    bvec4 b1 = bvec4(v1);
    bvec4 b2 = bvec4(v2);
    return vec4( b1.r || b2.r ,
                b1.g || b2.g,
                b1.b || b2.b,
                b1.a || b2.a );
  }
  `, name: "or_", type: l.FunctionType.ValueBased };
        }
        function m() {
          const T = "xor_";
          return { body: `
  float ${T}(float a, float b) {
    return float( bool(a) ^^ bool(b) );
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    bvec4 b1 = bvec4(v1);
    bvec4 b2 = bvec4(v2);
    return vec4( b1.r ^^ b2.r ,
                b1.g ^^ b2.g,
                b1.b ^^ b2.b,
                b1.a ^^ b2.a );
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        function _() {
          return (function(T) {
            const S = `${T}_`;
            return { body: `
  float ${S}(float a, float b) {
    return ${T}(a, b);
  }
  vec4 ${S}(vec4 v1, vec4 v2) {
    return ${T}(v1, v2);
  }
  `, name: S, type: l.FunctionType.ValueBased };
          })("pow");
        }
        function b() {
          const T = "prelu_";
          return { body: `
  float ${T}(float a, float b) {
    return a < 0.0 ? a * b: a;
  }
  vec4 ${T}(vec4 v1, vec4 v2) {
    return vec4(
      v1.r < 0.0 ? v1.r * v2.r: v1.r,
      v1.g < 0.0 ? v1.g * v2.g: v1.g,
      v1.b < 0.0 ? v1.b * v2.b: v1.b,
      v1.a < 0.0 ? v1.a * v2.a: v1.a
      );
  }
  `, name: T, type: l.FunctionType.ValueBased };
        }
        n.glslAdd = f, n.glslDiv = g, n.glslMul = c, n.glslSub = s, n.glslEqual = t, n.glslGreater = e, n.glslLess = r, n.glslAnd = i, n.glslOr = p, n.glslXor = m, n.glslPow = _, n.glslPRelu = b;
        const y = (T, S, E, O = S[0].type, v) => {
          const A = T.session.pack ? a.TextureType.packed : a.TextureType.unpacked;
          return { name: E.name, inputNames: ["A", "B"], inputTypes: [A, A], cacheHint: v, get: () => w(T, S, E, O) };
        }, w = (T, S, E, O = S[0].type) => {
          const v = T.session.pack ? a.TextureType.packed : a.TextureType.unpacked, A = !u.ShapeUtil.areEqual(S[0].dims, S[1].dims);
          let L = S[0].dims;
          const j = T.session.pack;
          if (A) {
            const D = u.BroadcastUtil.calcShape(S[0].dims, S[1].dims, !1);
            if (!D) throw new Error("Can't perform binary op on the given tensors");
            L = D;
            const I = L.length, $ = S[0].dims.length !== 0 ? S[0].dims.length : 1, Q = S[1].dims.length !== 0 ? S[1].dims.length : 1, Y = S[0].dims.length !== 0 ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", te = S[1].dims.length !== 0 ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", ne = (0, h.getGlsl)(T.session.backend.glContext.version), me = j ? `
      ${E.body}
      void main() {
        vec4 a = getAAtOutCoords();
        vec4 b = getBAtOutCoords();
        vec4 result = ${E.name}(a, b);
        ${ne.output} = result;
      }` : `
      ${E.body}
      float process(int indices[${I}]) {
        int aindices[${$}];
        int bindices[${Q}];
        ${Y}
        ${te}
        return ${E.name}(_A(aindices), _B(bindices));
      }`;
            return { name: E.name, inputNames: ["A", "B"], inputTypes: [v, v], output: { dims: L, type: O, textureType: v }, shaderSource: me, hasMain: j };
          }
          const B = (0, h.getGlsl)(T.session.backend.glContext.version), F = `
    ${E.body}
    void main() {
      vec4 v1 = ${B.texture2D}(A, TexCoords);
      vec4 v2 = ${B.texture2D}(B, TexCoords);
      vec4 result = ${E.name}(v1, v2);
      ${B.output} = result;
    }
    `;
          return { name: E.name, inputNames: ["A", "B"], inputTypes: [v, v], output: { dims: S[0].dims, type: O, textureType: v }, shaderSource: F, hasMain: !0 };
        };
        n.add = (T, S) => [T.run(y(T, S, f()), S)], n.and = (T, S) => [T.run(y(T, S, i(), "bool"), S)], n.div = (T, S) => [T.run(y(T, S, g()), S)], n.equal = (T, S) => [T.run(y(T, S, t(), "bool"), S)], n.greater = (T, S) => [T.run(y(T, S, e(), "bool"), S)], n.less = (T, S) => [T.run(y(T, S, r(), "bool"), S)], n.mul = (T, S) => [T.run(y(T, S, c()), S)], n.or = (T, S) => [T.run(y(T, S, p(), "bool"), S)], n.pow = (T, S) => [T.run(y(T, S, _()), S)], n.pRelu = (T, S) => [T.run(y(T, S, b()), S)], n.sub = (T, S) => [T.run(y(T, S, s()), S)], n.xor = (T, S) => [T.run(y(T, S, m(), "bool"), S)];
      }, 4196: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseCastAttributes = n.cast = void 0;
        const u = o(2517);
        n.cast = (h, a, f) => (l(a), [h.cast(a[0], f)]), n.parseCastAttributes = (h) => u.ProtoUtil.tensorDataTypeFromProto(h.attributes.getInt("to"));
        const l = (h) => {
          if (!h || h.length !== 1) throw new Error("Cast requires 1 input.");
          if (h[0].type === "string") throw new Error("Invalid input type.");
        };
      }, 1163: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createPackedConcatProgramInfoLoader = void 0;
        const u = o(5060), l = o(2039), h = o(9390), a = o(2827);
        n.createPackedConcatProgramInfoLoader = (g, c, s) => {
          const t = (e = c.length, r = s.cacheKey, { name: "Concat (packed)", inputNames: Array.from({ length: e }, ((i, p) => `X${p}`)), inputTypes: Array(e).fill(l.TextureType.packed), cacheHint: r });
          var e, r;
          return Object.assign(Object.assign({}, t), { get: () => ((i, p, m, _) => {
            const b = m[0].dims.slice();
            if (_ >= b.length || _ < -1 * b.length) throw new Error("axis specified for concat doesn't match input dimensionality");
            _ < 0 && (_ = b.length + _);
            const y = b.slice(0);
            for (let Y = 1; Y < m.length; Y++) {
              const te = m[Y].dims.slice();
              for (let ne = 0; ne < b.length; ne++) if (ne === _) y[_] += te[ne];
              else if (b[ne] !== te[ne]) throw new Error("non concat dimensions must match");
            }
            const w = y.length, T = (0, a.getChannels)("coords", w), S = (0, h.getCoordsDataType)(w), E = (0, a.unpackFromChannel)(), O = m.map(((Y) => Y.dims)), v = (0, h.getGlChannels)(w), A = new Array(O.length - 1);
            A[0] = O[0][_];
            for (let Y = 1; Y < A.length; Y++) A[Y] = A[Y - 1] + O[Y][_];
            const L = v[_], j = v.slice(-2), B = v.join();
            let F = `if (${L} < ${A[0]}) {
        return getChannel(
            getX0(${B}), vec2(${j.join()}));
        }`;
            for (let Y = 1; Y < A.length; Y++) {
              const te = A[Y - 1];
              F += `
            if (${L} < ${A[Y]}  && ${L} >= ${A[Y - 1]}) {
              return getChannel(
                getX${Y}(${f(v, L, te)}),
                vec2(${f(j, L, te)}));
            }`;
            }
            const D = A.length, I = A[A.length - 1];
            F += `
            return getChannel(
              getX${D}(${f(v, L, I)}),
              vec2(${f(j, L, I)}));`;
            const $ = (0, u.getGlsl)(i.session.backend.glContext.version), Q = `
          ${E}
          float getValue(${v.map(((Y) => "int " + Y))}) {
            ${F}
          }

          void main() {
            ${S} coords = getOutputCoords();
            int lastDim = coords.${v[w - 1]};
            coords.${v[w - 1]} = coords.${v[w - 2]};
            coords.${v[w - 2]} = lastDim;

            vec4 result = vec4(getValue(${T}), 0., 0., 0.);

            ${T[w - 1]} = ${T[w - 1]} + 1;
            if (${T[w - 1]} < ${y[w - 1]}) {
              result.g = getValue(${T});
            }

            ${T[w - 2]} = ${T[w - 2]} + 1;
            if (${T[w - 2]} < ${y[w - 2]}) {
              result.a = getValue(${T});
            }

            ${T[w - 1]} = ${T[w - 1]} - 1;
            if (${T[w - 2]} < ${y[w - 2]} &&
                ${T[w - 1]} < ${y[w - 1]}) {
              result.b = getValue(${T});
            }
            ${$.output} = result;
          }
        `;
            return Object.assign(Object.assign({}, p), { output: { dims: y, type: m[0].type, textureType: l.TextureType.packed }, shaderSource: Q, hasMain: !0 });
          })(g, t, c, s.axis) });
        };
        const f = (g, c, s) => {
          const t = g.indexOf(c);
          return g.map(((e, r) => r === t ? `${e} - ${s}` : e)).join();
        };
      }, 2069: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseConcatAttributes = n.concat = void 0;
        const u = o(246), l = o(2039), h = o(1163);
        n.concat = (e, r, i) => (t(r), e.session.pack && r[0].dims.length > 1 ? [e.run((0, h.createPackedConcatProgramInfoLoader)(e, r, i), r)] : [e.run(a(e, r, i), r)]);
        const a = (e, r, i) => {
          const p = (m = r.length, _ = i.cacheKey, { name: "Concat", inputNames: Array.from({ length: m }, ((b, y) => `X${y}`)), inputTypes: Array(m).fill(l.TextureType.unpacked), cacheHint: _ });
          var m, _;
          return Object.assign(Object.assign({}, p), { get: () => ((b, y, w, T) => {
            const S = w[0].dims.slice();
            if (T >= S.length || T < -1 * S.length) throw new Error("axis specified for concat doesn't match input dimensionality");
            T < 0 && (T = S.length + T);
            const E = S.slice(0);
            for (let B = 1; B < w.length; B++) {
              const F = w[B].dims.slice();
              for (let D = 0; D < S.length; D++) if (D === T) E[T] += F[D];
              else if (S[D] !== F[D]) throw new Error("non concat dimensions must match");
            }
            const O = E.length, v = new Array(w.length);
            let A = 0;
            for (let B = 0; B < v.length; ++B) A += w[B].dims[T], v[B] = A;
            let L = "";
            L = w.length < 5 ? f(v) : g(v);
            const j = `
        ${c(w.length, O)}
        ${s(v)}
        ${L}
        float process(int indices[${O}]) {
          int textureIndex = getTextureWhereDataResides (indices[${T}]);

          if(textureIndex != 0) {
            indices[${T}] = indices[${T}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));
          }

          return fetchDataFromCorrectTexture(textureIndex, indices);
        }`;
            return Object.assign(Object.assign({}, y), { output: { dims: E, type: w[0].type, textureType: l.TextureType.unpacked }, shaderSource: j });
          })(0, p, r, i.axis) });
        }, f = (e) => `int getTextureWhereDataResides(int index) {
      ${e.map(((r, i) => `if(index<${r}) {return ${i};}
`)).join("")}
    }`, g = (e) => f(e), c = (e, r) => {
          const i = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${r}]) {`];
          for (let p = 0; p < e; ++p) p === 0 ? i.push(`	if (textureIndex == ${p}) { return _X${p}(indices); }`) : p === e - 1 ? i.push(`	else { return _X${p}(indices); }`) : i.push(`	else if (textureIndex == ${p}) { return _X${p}(indices); }`);
          return i.push("	}"), i.join(`
`);
        }, s = (e) => {
          const r = ["int getSizeInConcatAxisValueFromIndex(int index) {"];
          for (let i = 0; i < e.length; ++i) i === 0 ? r.push(`	if (index == ${i}) { return ${e[i]}; }`) : i === e.length - 1 ? r.push(`	else { return ${e[i]}; }`) : r.push(`	else if (index == ${i}) { return ${e[i]}; }`);
          return r.push("	}"), r.join(`
`);
        };
        n.parseConcatAttributes = (e) => (0, u.createAttributeWithCacheKey)({ axis: e.attributes.getInt("axis") });
        const t = (e) => {
          if (!e || e.length < 1) throw new Error("too few inputs");
          const r = e[0].type, i = e[0].dims.length;
          if (r === "string") throw new Error("string tensor is not supported yet");
          for (const p of e) {
            if (p.type !== r) throw new Error("input tensors should be one type");
            if (p.dims.length !== i) throw new Error("input tensors should have the same shape");
          }
        };
      }, 4770: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createUnpackedGroupedConvProgramInfoLoader = void 0;
        const u = o(6231), l = o(5060), h = o(2039), a = o(8138), f = o(2823);
        n.createUnpackedGroupedConvProgramInfoLoader = (g, c, s) => {
          const t = (e = c.length > 2, r = s.cacheKey, { name: "GroupedConv", inputNames: e ? ["X", "W", "Bias"] : ["X", "W"], inputTypes: e ? [h.TextureType.unpacked, h.TextureType.unpacked, h.TextureType.unpacked] : [h.TextureType.unpacked, h.TextureType.unpacked], cacheHint: r });
          var e, r;
          return Object.assign(Object.assign({}, t), { get: () => ((i, p, m, _) => {
            const b = p.length > 2 ? "value += getBias(output_channel);" : "", y = p[0].dims.slice(), w = p[1].dims.slice(), T = w[0] / _.group;
            u.Logger.verbose("GroupedConv", `autpPad:${_.autoPad}, dilations:${_.dilations}, group:${_.group}, kernelShape:${_.kernelShape}, pads:${_.pads}, strides:${_.strides}`);
            const S = (0, a.calculateOutputShape)(y, w, _.dilations, _.pads, _.strides), E = (0, l.getGlsl)(i.session.backend.glContext.version), { activationFunction: O, applyActivation: v } = (0, f.getActivationSnippet)(_), A = `
  const ivec2 strides = ivec2(${_.strides[0]}, ${_.strides[1]});
  const ivec2 pads = ivec2(${_.pads[0]}, ${_.pads[1]});
  ${O}
  void main() {
    ivec4 coords = getOutputCoords();
    int batch = coords.x;
    int output_channel = coords.y;
    ivec2 xRCCorner = coords.zw * strides - pads;
    int group_id = output_channel / ${T};

    float value = 0.0;
    for (int wInChannel = 0; wInChannel < ${w[1]}; wInChannel++) {
      int input_channel = group_id * ${w[1]} + wInChannel;
      for (int wHeight = 0; wHeight < ${w[2]}; wHeight++) {
        int xHeight = xRCCorner.x + wHeight * ${_.dilations[0]};

        if (xHeight < 0 || xHeight >= ${y[2]}) {
          continue;
        }

        for (int wWidth = 0; wWidth < ${w[3]}; wWidth++) {
          int xWidth = xRCCorner.y + wWidth * ${_.dilations[1]};
          if (xWidth < 0 || xWidth >= ${y[3]}) {
            continue;
          }

          float xVal = getX(batch, input_channel, xWidth, xHeight);
          float wVal = getW(output_channel, wInChannel, wWidth, wHeight);
          value += xVal*wVal;
        }
      }
    }
    ${b}
    ${v}
    ${E.output} = vec4(value, .0, .0, .0);
  }
`;
            return Object.assign(Object.assign({}, m), { output: { dims: S, type: p[0].type, textureType: h.TextureType.unpacked }, shaderSource: A, hasMain: !0 });
          })(g, c, t, s) });
        };
      }, 1386: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.conv2DPacked = n.conv2DPackedPointwise = void 0;
        const u = o(8138), l = o(8555), h = o(708);
        n.conv2DPackedPointwise = (a, f, g) => {
          const c = f[0].dims, s = f[1].dims, t = (0, u.calculateOutputShape)(c, s, g.dilations, g.pads, g.strides), e = a.reshapePacked(f[0], [c[1], c[2] * c[3]]), r = a.reshapePacked(f[1], [s[0], s[1]]), i = f.length > 2 ? [r, e, f[2]] : [r, e], p = a.run((0, h.createPackedMatmulProgramInfoLoader)(a, i, g), i);
          return a.reshapePacked(p, t);
        }, n.conv2DPacked = (a, f, g) => {
          const c = f[0].dims, s = f[1].dims, t = (0, u.calculateOutputShape)(c, s, g.dilations, g.pads, g.strides), e = a.run((0, l.createPackedIm2ColProgramInfoLoader)(a, f[0], f[1], t, g), [f[0]]), r = a.reshapePacked(f[1], [s[0], s[1] * s[2] * s[3]]), i = f.length === 3 ? [r, e, f[2]] : [r, e], p = a.run((0, h.createPackedMatmulProgramInfoLoader)(a, i, g), i);
          return a.reshapePacked(p, t);
        };
      }, 9663: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseConvTransposeAttributes = n.convTranspose = void 0;
        const u = o(246), l = o(5060), h = o(2039), a = o(2823), f = (r, i, p, m, _, b) => (r - 1) * i + p + (m - 1) * _ + 1 - b, g = (r, i, p, m, _) => {
          const b = Math.floor(r / 2);
          i === "SAME_UPPER" ? (p[m] = b, p[_] = r - b) : i === "SAME_LOWER" && (p[m] = r - b, p[_] = b);
        };
        n.convTranspose = (r, i, p) => (e(i, p), c(r, i, p));
        const c = (r, i, p) => {
          const m = t(p, i);
          return [s(r, i, m)];
        }, s = (r, i, p) => r.run(((m, _, b) => {
          const y = (w = _.length > 2, T = b.cacheKey, { name: "ConvTranspose", inputNames: w ? ["X", "W", "B"] : ["X", "W"], inputTypes: w ? [h.TextureType.unpacked, h.TextureType.unpacked, h.TextureType.unpacked] : [h.TextureType.unpacked, h.TextureType.unpacked], cacheHint: T });
          var w, T;
          return Object.assign(Object.assign({}, y), { get: () => ((S, E, O, v) => {
            const A = E.length > 2 ? "getB(output_channel)" : "0.0", L = E[0].dims, j = E[1].dims, B = j[1], F = j[0] / v.group, D = [E[0].dims[0], E[1].dims[1] * v.group, ...v.outputShape], I = (0, l.getGlsl)(S.session.backend.glContext.version), { activationFunction: $, applyActivation: Q } = (0, a.getActivationSnippet)(v), Y = `
  const ivec2 strides = ivec2(${v.strides[0]}, ${v.strides[1]});
  const ivec2 pads = ivec2(${v.pads[0]}, ${v.pads[1]});
  ${$}
  void main() {
    ivec4 coords = getOutputCoords();
    int batch = coords.x;
    int output_channel = coords.y;

    ivec2 loc = coords.zw + pads;

    int group_id = output_channel / ${B};
    int wOutChannel = output_channel - group_id * ${B};

    float value = ${A};
    for (int inChannelOffset = 0; inChannelOffset < ${F}; inChannelOffset++) {
      int input_channel = group_id * ${F} + inChannelOffset;
      for (int wWOff = 0; wWOff < ${j[2]}; wWOff++) {
        for (int wHOff = 0; wHOff < ${j[3]}; wHOff++) {
          ivec2 wOff = ivec2(wWOff * ${v.dilations[0]}, wHOff * ${v.dilations[1]});
          ivec2 wLoc = loc - wOff;
          ivec2 wLocIn = wLoc / strides;
          if (
            wLocIn * strides == wLoc &&
            wLocIn.x >= 0 && wLocIn.x < ${L[2]} &&
            wLocIn.y >= 0 && wLocIn.y < ${L[3]}
          ) {
            float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);
            float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);
            value += xVal * wVal;
          }
        }
      }
    }
    ${Q}
    ${I.output} = vec4(value, .0, .0, .0);
  }
`;
            return Object.assign(Object.assign({}, O), { output: { dims: D, type: E[0].type, textureType: h.TextureType.unpacked }, shaderSource: Y, hasMain: !0 });
          })(m, _, y, b) });
        })(r, i, p), i), t = (r, i) => {
          const p = r.kernelShape.slice();
          if (r.kernelShape.length === 0) for (let y = 2; y < i[1].dims.length; ++y) p.push(i[1].dims[y]);
          const m = r.pads.slice(), _ = r.outputShape.slice();
          ((y, w, T, S, E, O, v, A) => {
            const L = y.length - 2, j = A.length === 0;
            for (let B = 0; B < L; ++B) {
              const F = j ? y[B + 2] * O[B] : A[B], D = f(y[B + 2], O[B], E[B], w[B], T[B], F);
              g(D, S, E, B, B + L), j && A.push(O[B] * (y[B + 2] - 1) + v[B] + (w[B] - 1) * T[B] + 1 - E[B] - E[B + L]);
            }
          })(i[0].dims, p, r.dilations, r.autoPad, m, r.strides, r.outputPadding, _);
          const b = Object.assign({}, r);
          return Object.assign(b, { kernelShape: p, pads: m, outputShape: _, cacheKey: r.cacheKey }), b;
        };
        n.parseConvTransposeAttributes = (r) => {
          const i = r.attributes, p = (0, a.parseInternalActivationAttributes)(i), m = i.getString("auto_pad", "NOTSET"), _ = i.getInts("dilations", [1, 1]), b = i.getInt("group", 1), y = i.getInts("kernel_shape", []), w = i.getInts("output_padding", [0, 0]), T = i.getInts("output_shape", []), S = i.getInts("pads", [0, 0, 0, 0]), E = i.getInts("strides", [1, 1]);
          return (0, u.createAttributeWithCacheKey)(Object.assign({ autoPad: m, dilations: _, group: b, kernelShape: y, outputPadding: w, outputShape: T, pads: S, strides: E }, p));
        };
        const e = (r, i) => {
          if (!r || r.length !== 2 && r.length !== 3) throw new Error("Conv requires 2 or 3 inputs");
          if (r[0].dims.length !== 4 || r[1].dims.length !== 4) throw new Error("currently only support 2-dimensional conv");
          if (r[0].dims[1] !== r[1].dims[0]) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
          const p = r[1].dims[1] * i.group;
          if (r.length === 3 && (r[2].dims.length !== 1 || r[2].dims[0] !== p)) throw new Error("invalid bias");
          const m = r[0].dims.length - 2;
          if (i.dilations.length !== m) throw new Error(`dilations should be ${m}D`);
          if (i.strides.length !== m) throw new Error(`strides should be ${m}D`);
          if (i.pads.length !== 2 * m) throw new Error(`pads should be ${2 * m}D`);
          if (i.outputPadding.length !== m) throw new Error(`output_padding should be ${m}D`);
          if (i.kernelShape.length !== 0 && i.kernelShape.length !== r[1].dims.length - 2) throw new Error("invalid kernel shape");
          if (i.outputShape.length !== 0 && i.outputShape.length !== r[0].dims.length - 2) throw new Error("invalid output shape");
          if (r[0].type !== "float32" || r[1].type !== "float32") throw new Error("ConvTranspose input(X,W) should be float tensor");
          if (r.length === 3 && r[2].type !== "float32") throw new Error("ConvTranspose input(bias) should be float tensor");
        };
      }, 8138: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseConvAttributes = n.conv = n.calculateOutputShape = void 0;
        const u = o(246), l = o(2517), h = o(4770), a = o(1386), f = o(9828), g = o(2823), c = o(3248), s = o(5623);
        n.calculateOutputShape = (m, _, b, y, w) => {
          const T = m[0], S = m.slice(2), E = S.length, O = _[0], v = _.slice(2).map(((L, j) => L + (L - 1) * (b[j] - 1))), A = S.map(((L, j) => L + y[j] + y[j + E])).map(((L, j) => Math.floor((L - v[j] + w[j]) / w[j])));
          return [T, O].concat(...A);
        }, n.conv = (m, _, b) => (p(_, b), t(m, _, b));
        const t = (m, _, b) => {
          const y = i(b, _), w = m.session.pack, T = y.kernelShape[0] === 1 && y.kernelShape[1] === 1;
          return y.group > 1 ? [m.run((0, h.createUnpackedGroupedConvProgramInfoLoader)(m, _, y), _)] : T && w ? [e(m, _, y)] : w && _[0].dims.length === 4 && _[0].dims[0] === 1 && !T ? [(0, a.conv2DPacked)(m, _, y)] : [r(m, _, y)];
        }, e = (m, _, b) => {
          const y = _[0].dims, w = _[1].dims, T = (0, n.calculateOutputShape)(y, w, b.dilations, b.pads, b.strides), S = m.reshapeUnpacked(_[0], [y[1], y[2] * y[3]]), E = m.reshapeUnpacked(_[1], [w[0], w[1]]), O = _.length > 2 ? [E, S, _[2]] : [E, S], v = m.run((0, s.createMatmulProgramInfoLoader)(O, b), O);
          return m.reshapeUnpacked(v, T);
        }, r = (m, _, b) => {
          const y = _[0].dims, w = _[1].dims, T = (0, n.calculateOutputShape)(y, w, b.dilations, b.pads, b.strides), S = m.run((0, c.createIm2ColProgramInfoLoader)(m, _[0], _[1], T, b), [_[0]]), E = _.length === 3 ? [S, _[1], _[2]] : [S, _[1]];
          return m.run((0, f.createDotProductProgramInfoLoader)(m, _, T, b), E);
        }, i = (m, _) => {
          const b = m.kernelShape.slice();
          if (m.kernelShape.length === 0) for (let T = 2; T < _[1].dims.length; ++T) b.push(_[1].dims[T]);
          const y = m.pads.slice();
          l.PoolConvUtil.adjustPadsBasedOnAutoPad(_[0].dims, m.strides, m.dilations, b, y, m.autoPad);
          const w = Object.assign({}, m);
          return Object.assign(w, { kernelShape: b, pads: y, cacheKey: m.cacheKey }), w;
        };
        n.parseConvAttributes = (m) => {
          const _ = m.attributes, b = (0, g.parseInternalActivationAttributes)(_), y = _.getString("auto_pad", "NOTSET"), w = _.getInts("dilations", [1, 1]), T = _.getInt("group", 1), S = _.getInts("kernel_shape", []), E = _.getInts("pads", [0, 0, 0, 0]), O = _.getInts("strides", [1, 1]);
          return (0, u.createAttributeWithCacheKey)(Object.assign({ autoPad: y, dilations: w, group: T, kernelShape: S, pads: E, strides: O }, b));
        };
        const p = (m, _) => {
          if (!m || m.length !== 2 && m.length !== 3) throw new Error("Conv requires 2 or 3 inputs");
          if (m[0].dims.length !== 4 || m[1].dims.length !== 4) throw new Error("currently only support 2-dimensional conv");
          if (m[0].dims[1] !== m[1].dims[1] * _.group) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
          if (m.length === 3 && (m[2].dims.length !== 1 || m[1].dims[0] !== m[2].dims[0])) throw new Error("invalid bias");
          const b = m[0].dims.length - 2;
          if (_.dilations.length !== b) throw new Error(`dilations should be ${b}D`);
          if (_.strides.length !== b) throw new Error(`strides should be ${b}D`);
          if (_.pads.length !== 2 * b) throw new Error(`pads should be ${2 * b}D`);
          if (_.kernelShape.length !== 0 && _.kernelShape.length !== m[1].dims.length - 2) throw new Error("invalid kernel shape");
          if (m[0].type !== "float32" || m[1].type !== "float32") throw new Error("Conv input(X,W) should be float tensor");
          if (m.length === 3 && m[2].type !== "float32") throw new Error("Conv input(bias) should be float tensor");
        };
      }, 5193: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseDepthToSpaceAttributes = n.depthToSpace = void 0;
        const u = o(3738);
        n.depthToSpace = (h, a, f) => {
          l(a);
          const g = f.blocksize, c = g * g, s = f.mode === "DCR" ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], t = f.mode === "DCR" ? [a[0].dims[0], g, g, a[0].dims[1] / c, a[0].dims[2], a[0].dims[3]] : [a[0].dims[0], a[0].dims[1] / c, g, g, a[0].dims[2], a[0].dims[3]], e = h.reshapeUnpacked(a[0], t), r = { perm: s, cacheKey: `${s}` }, [i] = (0, u.transpose)(h, [e], r), p = [a[0].dims[0], a[0].dims[1] / c, a[0].dims[2] * g, a[0].dims[3] * g];
          return [h.reshapeUnpacked(i, p)];
        }, n.parseDepthToSpaceAttributes = (h) => {
          const a = h.attributes.getInt("blocksize");
          if (a < 1) throw new Error(`blocksize must be >= 1, but got : ${a} for DepthToSpace`);
          const f = h.attributes.getString("mode", "DCR");
          if (f !== "DCR" && f !== "CRD") throw new Error(`unrecognized mode: ${f} for DepthToSpace`);
          return { mode: f, blocksize: a };
        };
        const l = (h) => {
          if (h.length !== 1) throw new Error(`DepthToSpace expect 1 inputs, but got ${h.length}`);
          if (h[0].type === "string" || h[0].dims.length !== 4) throw new TypeError("DepthToSpace input should be a 4-D numeric tensor");
        };
      }, 9828: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createDotProductProgramInfoLoader = void 0;
        const u = o(2517), l = o(5060), h = o(2039), a = o(2823), f = o(3248);
        n.createDotProductProgramInfoLoader = (g, c, s, t) => {
          const e = ((r, i) => ({ name: "ConvDotProduct", inputNames: r ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: r ? [h.TextureType.unpacked, h.TextureType.packedLastDimension, h.TextureType.unpacked] : [h.TextureType.unpacked, h.TextureType.packedLastDimension], cacheKey: i.activationCacheKey }))(c.length > 2, t);
          return Object.assign(Object.assign({}, e), { get: () => ((r, i, p, m, _) => {
            const b = p[0].dims, y = p[1].dims, w = [y[0], Math.ceil(b[1] * y[2] * y[3] / 4)], T = (0, f.calculateIm2ColDims)(b, y, m), [S, E] = r.calculateTextureWidthAndHeight(w, h.TextureType.packedLastDimension), O = u.ShapeUtil.computeStrides(T), [v, A] = r.calculateTextureWidthAndHeight(T, h.TextureType.packedLastDimension), L = m.length, j = p.length < 3 ? "0.0" : "_B(b)", B = Math.ceil(b[1] * y[2] * y[3] / 4), { activationFunction: F, applyActivation: D } = (0, a.getActivationSnippet)(_), I = (0, l.getGlsl)(r.session.backend.glContext.version), $ = `
${F}
float process(int indices[${L}]) {
  int b[1];
  b[0] = indices[1];
  int im2col[4];
  im2col[0] = indices[0];
  im2col[1] = indices[2];
  im2col[2] = indices[3];
  int im2colOffset = im2col[0] * ${O[0]} + im2col[1] * ${O[1]} + im2col[2] * ${O[2]};
  int kernelOffset = indices[1] * ${w[1]};
  float value = ${j};
  for (int i = 0; i < ${B}; ++i) {
    vec2 im2colCoords = offsetToCoords(im2colOffset, ${v}, ${A});
    vec2 kernelCoords = offsetToCoords(kernelOffset, ${S}, ${E});
    value += dot(${I.texture2D}(Im2Col, im2colCoords), ${I.texture2D}(K, kernelCoords));
    ++im2colOffset;
    ++kernelOffset;
  }
  ${D}
  return value;
}`;
            return Object.assign(Object.assign({}, i), { output: { dims: m, type: p[0].type, textureType: h.TextureType.unpacked }, shaderSource: $ });
          })(g, e, c, s, t) });
        };
      }, 7992: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseFlattenAttributes = n.flatten = void 0;
        const u = o(2517);
        n.flatten = (h, a, f) => {
          l(a, f);
          const g = u.ShapeUtil.flattenShape(a[0].dims, f);
          return [h.reshapeUnpacked(a[0], g)];
        }, n.parseFlattenAttributes = (h) => h.attributes.getInt("axis", 1);
        const l = (h, a) => {
          if (!h || h.length !== 1) throw new Error("Flatten requires 1 input.");
          const f = h[0].dims.length;
          if (f === 0) throw new Error("scalar tensor is not supported.");
          if (a < -f || a > f) throw new Error("Invalid axis");
          if (h[0].type === "string") throw new Error("string tensor is not supported.");
        };
      }, 2823: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseInternalActivationAttributes = n.getActivationSnippet = void 0;
        const u = o(2517), l = o(4909);
        n.getActivationSnippet = function(h) {
          let a;
          switch (h.activation) {
            case "Relu":
              a = (0, l.glslRelu)();
              break;
            case "Sigmoid":
              a = (0, l.glslSigmoid)();
              break;
            case "Clip":
              a = (0, l.glslClip)(h.clipMin, h.clipMax);
              break;
            default:
              return { activationFunction: "", applyActivation: "" };
          }
          const f = a.name;
          return { activationFunction: a.body, applyActivation: `value = ${f}_(value);` };
        }, n.parseInternalActivationAttributes = (h) => {
          const a = h.getString("activation", "");
          if (a === "Clip") {
            const [f, g] = h.getFloats("activation_params", [u.MIN_CLIP, u.MAX_CLIP]);
            return { activation: a, clipMax: g, clipMin: f, activationCacheKey: `${a}:${f},${g}` };
          }
          return { activation: a, activationCacheKey: a };
        };
      }, 1253: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseGatherAttributes = n.gather = void 0;
        const u = o(246), l = o(782), h = o(2517), a = o(2039);
        n.gather = (s, t, e) => (c(t, e.axis), [s.run(g(s, t, e), t)]), n.parseGatherAttributes = (s) => (0, u.createAttributeWithCacheKey)({ axis: s.attributes.getInt("axis", 0) });
        const f = { name: "Gather", inputNames: ["A", "B"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, g = (s, t, e) => {
          const r = Object.assign(Object.assign({}, f), { cacheHint: e.cacheKey });
          return Object.assign(Object.assign({}, r), { get: () => ((i, p, m, _) => {
            const b = m[0].dims.slice(), y = m[1].dims.slice(), w = new Array(b.length + y.length - 1);
            _ = h.ShapeUtil.normalizeAxis(_, b.length);
            const T = [];
            for (let E = 0; E < w.length; E++) E < _ ? (w[E] = b[E], T.push(`inputIdx[${E}] = outputIdx[${E}];`)) : E < _ + y.length ? (w[E] = y[E - _], T.push(`indexDataIdx[${E - _}] = outputIdx[${E}];`)) : (w[E] = b[E - y.length + 1], T.push(`inputIdx[${E - y.length + 1}] = outputIdx[${E}];`));
            const S = `
      float process(int outputIdx[${w.length || 1}]) {
        int inputIdx[${b.length}];
        int indexDataIdx[${y.length || 1}];
        indexDataIdx[0] = 0;
        ${T.join(`
        `)}
        int idx = int(_B(indexDataIdx));
        inputIdx[${_}] = idx < 0 ? idx + ${b[_]} : idx;
        return _A(inputIdx);
      }`;
            return Object.assign(Object.assign({}, p), { output: { dims: w, type: m[0].type, textureType: a.TextureType.unpacked }, shaderSource: S });
          })(0, r, t, e.axis) });
        }, c = (s, t) => {
          if (!s || s.length !== 2) throw new Error("Gather requires 2 inputs.");
          const e = s[0].dims.length;
          if (e < 1) throw new Error("Invalid input shape.");
          if (t < -e || t > e - 1) throw new Error("Invalid axis.");
          if (l.NUMBER_TYPES.indexOf(s[0].type) === -1) throw new Error("Invaid input type.");
          if (s[1].type !== "int32" && s[1].type !== "int16") throw new Error("Invaid input type.");
        };
      }, 4776: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseGemmAttributesV11 = n.parseGemmAttributesV7 = n.gemm = void 0;
        const u = o(246), l = o(2517), h = o(2039);
        n.gemm = (s, t, e) => (c(t, e), [s.run(f(t, e), t)]);
        const a = (s, t) => {
          const e = s.attributes.getInt("transA", 0) !== 0, r = s.attributes.getInt("transB", 0) !== 0, i = s.attributes.getFloat("alpha", 1), p = s.attributes.getFloat("beta", 1);
          return (0, u.createAttributeWithCacheKey)({ transA: e, transB: r, alpha: i, beta: p, isOptionalC: t });
        };
        n.parseGemmAttributesV7 = (s) => a(s, !1), n.parseGemmAttributesV11 = (s) => a(s, !0);
        const f = (s, t) => {
          const e = { name: "Gemm", inputNames: s.length === 3 ? ["A", "B", "C"] : ["A", "B"], inputTypes: s.length === 3 ? [h.TextureType.unpacked, h.TextureType.unpacked, h.TextureType.unpacked] : [h.TextureType.unpacked, h.TextureType.unpacked], key: t.cacheKey };
          return Object.assign(Object.assign({}, e), { get: () => g(e, s, t) });
        }, g = (s, t, e) => {
          const r = t[0].dims.slice(), i = t[1].dims.slice(), [p, m] = l.GemmUtil.getShapeOfGemmResult(r, e.transA, i, e.transB, t.length === 3 ? t[2].dims : void 0), _ = [p, m];
          if (!_) throw new Error("Can't use gemm on the given tensors");
          let b = r[r.length - 1], y = "";
          e.transA && (b = r[0]), e.transA && e.transB ? y = "value += _A_T(a) * _B_T(b);" : e.transA && !e.transB ? y = "value += _A_T(a) * _B(b);" : !e.transA && e.transB ? y = "value += _A(a) * _B_T(b);" : e.transA || e.transB || (y = "value += _A(a) * _B(b);");
          const w = _.length, T = `
      float process(int indices[${w}]) {
          int a[${w}];
          int b[${w}];
          ${t.length === 3 ? `int c[${t[2].dims.length}];` : ""}

          copyVec(indices, a);
          copyVec(indices, b);
          ${t.length === 3 ? "bcastIndices_C(indices, c);" : ""}

          float value = 0.0;
          for (int k=0; k<${b}; ++k) {
              a[${w - 1}] = k;
              b[${w - 2}] = k;
              ${y}
          }

          value = value * alpha;
          ${t.length === 3 ? "value += beta * _C(c);" : ""}
          return value;
      }`;
          return Object.assign(Object.assign({}, s), { output: { dims: _, type: t[0].type, textureType: h.TextureType.unpacked }, variables: [{ name: "alpha", type: "float", data: e.alpha }, { name: "beta", type: "float", data: e.beta }], shaderSource: T });
        }, c = (s, t) => {
          if (!s) throw new Error("Input is missing");
          if (t.isOptionalC && (s.length < 2 || s.length > 3)) throw new Error("Invaid input shape.");
          if (!t.isOptionalC && s.length !== 3) throw new Error("Gemm requires 3 inputs");
          if (s.length === 3 && s[2].dims.length !== 1 && s[2].dims.length !== 2) throw new Error("Invalid input shape of C");
          if (s[0].type !== "float32" && s[0].type !== "float64" || s[1].type !== "float32" && s[1].type !== "float64" || s.length === 3 && s[2].type !== "float32" && s[2].type !== "float64") throw new Error("Invalid input type.");
          if (s[0].type !== s[1].type || s.length === 3 && s[0].type !== s[2].type) throw new Error("Input types are mismatched");
        };
      }, 8555: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createPackedIm2ColProgramInfoLoader = void 0;
        const u = o(5060), l = o(2039), h = o(2827);
        n.createPackedIm2ColProgramInfoLoader = (a, f, g, c, s) => {
          const t = (e = s.cacheKey, { name: "Im2Col (packed)", inputNames: ["A"], inputTypes: [l.TextureType.packed], cacheHint: e });
          var e;
          return Object.assign(Object.assign({}, t), { get: () => ((r, i, p, m, _, b) => {
            const y = p.dims, w = m.dims, T = _.length, S = [w[1] * w[2] * w[3], _[2] * _[3]], E = w[2] * w[3], O = (0, h.unpackFromChannel)(), v = (0, u.getGlsl)(r.session.backend.glContext.version);
            let A = "";
            for (let j = 0; j <= 1; j++) for (let B = 0; B <= 1; B++) A += `
            blockIndex = rc.x + ${B};
            pos = rc.y + ${j};

            if(blockIndex < ${S[1]} && pos < ${S[0]}) {
              offsetY = int(blockIndex / (${_[T - 1]})) * ${b.strides[0]} -
                ${b.pads[0]};
              d0 = offsetY + ${b.dilations[0]} * (imod(pos, ${E}) / ${w[2]});

              if(d0 < ${y[2]} && d0 >= 0) {
                offsetX = imod(blockIndex, ${_[T - 1]}) * ${b.strides[1]} -
                  ${b.pads[1]};
                d1 = offsetX + ${b.dilations[1]} * imod(imod(pos, ${E}), ${w[2]});

                if(d1 < ${y[3]} && d1 >= 0) {

                  ch = int(float(pos)/ ${E}.);
                    innerDims = vec2(d0, d1);
                    result[${2 * j + B}] = getChannel(
                      getA(0, ch, int(innerDims.x),
                      int(innerDims.y)), innerDims);
                }
              }
            }

          `;
            const L = `
      ${O}

      void main() {
        ivec2 rc = getOutputCoords();
          vec4 result = vec4(0.0);
          int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
          vec2 innerDims;
          ${A}
          ${v.output} = result;
      }
            `;
            return Object.assign(Object.assign({}, i), { output: { dims: S, type: p.type, textureType: l.TextureType.packed }, shaderSource: L, hasMain: !0 });
          })(a, t, f, g, c, s) });
        };
      }, 3248: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.calculateIm2ColDims = n.createIm2ColProgramInfoLoader = void 0;
        const u = o(2039);
        n.createIm2ColProgramInfoLoader = (l, h, a, f, g) => {
          const c = (s = g.cacheKey, { name: "Im2Col", inputNames: ["X"], inputTypes: [u.TextureType.unpacked], cacheHint: s });
          var s;
          return Object.assign(Object.assign({}, c), { get: () => ((t, e, r, i, p, m) => {
            const _ = r.dims, b = i.dims, y = p.length, w = (0, n.calculateIm2ColDims)(_, b, p, 4), T = `
        const int XC = ${_[1]};
        const int XH = ${_[2]};
        const int XW = ${_[3]};
        const int KH = ${m.kernelShape[0]};
        const int KW = ${m.kernelShape[1]};
        const int dilationH = ${m.dilations[0]};
        const int dilationW = ${m.dilations[1]};
        const int strideH = ${m.strides[0]};
        const int strideW = ${m.strides[1]};
        const int padH = ${m.pads[0]};
        const int padW = ${m.pads[1]};
        const int KHKW = KH*KW;
        const int XCKHKW = XC * KHKW;
        const int outputChannels = 4;
        vec4 process(int indices[${y}]) {
          int b  = indices[0]; // batch size
          int oh = indices[1] * strideH - padH; //output height
          int ow = indices[2] * strideW - padW; //output width
          int p = indices[3] * outputChannels; //patch
          vec4 value = vec4(0.0);
          for(int i=0; i < outputChannels; ++i) {
            if(p < XCKHKW) {
              int patchC = p / KHKW;
              int patchH = (p - patchC*KHKW) / KW;
              int patchW = (p - patchC*KHKW) - patchH * KW;
              int xh2 = oh + patchH * dilationH;
              int xw2 = ow + patchW * dilationW;
              int x[${_.length}];
              x[0] = b;
              x[1] = patchC;
              x[2] = xh2;
              x[3] = xw2;
              if(xh2 >= 0 &&
                  xh2 < XH &&
                  xw2 >= 0 &&
                  xw2 < XW) {
                value[i] = _X(x);
              }
            }
            ++p;
          }
          return value;
        }
        `;
            return Object.assign(Object.assign({}, e), { output: { dims: w, type: r.type, textureType: u.TextureType.packedLastDimension }, shaderSource: T });
          })(0, c, h, a, f, g) });
        }, n.calculateIm2ColDims = (l, h, a, f = 4) => [a[0], a[2], a[3], Math.ceil(l[1] * h[2] * h[3] / f)];
      }, 6572: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseImageScalerAttributes = n.imageScaler = void 0;
        const u = o(246), l = o(2039);
        n.imageScaler = (c, s, t) => (g(s), [c.run(a(c, s, t), s)]), n.parseImageScalerAttributes = (c) => {
          const s = c.attributes.getFloat("scale"), t = c.attributes.getFloats("bias");
          return (0, u.createAttributeWithCacheKey)({ scale: s, bias: t });
        };
        const h = { name: "ImageScaler", inputNames: ["X"], inputTypes: [l.TextureType.unpacked] }, a = (c, s, t) => {
          const e = Object.assign(Object.assign({}, h), { cacheHint: t.cacheKey });
          return Object.assign(Object.assign({}, e), { get: () => ((r, i, p, m) => {
            const _ = p[0].dims.slice(), b = _.length, y = `
      ${f(m.bias.length)}
      float process(int indices[${b}]) {
        return _X(indices) * scale + getBias(bias, indices[1]);
      }`;
            return Object.assign(Object.assign({}, i), { output: { dims: _, type: p[0].type, textureType: l.TextureType.unpacked }, variables: [{ name: "bias", type: "float", arrayLength: m.bias.length, data: m.bias }, { name: "scale", type: "float", data: m.scale }], shaderSource: y });
          })(0, e, s, t) });
        }, f = (c) => {
          const s = [`float getBias(float bias[${c}], int channel) {`];
          for (let t = 0; t < c; ++t) t === 0 ? s.push(`	if (channel == ${t}) { return bias[${t}]; }`) : t === c - 1 ? s.push(`	else { return bias[${t}]; }`) : s.push(`	else if (channel == ${t}) { return bias[${t}]; }`);
          return s.push("	}"), s.join(`
`);
        }, g = (c) => {
          if (!c || c.length !== 1) throw new Error("ImageScaler requires 1 input.");
          if (c[0].dims.length !== 4) throw new Error("Invalid input shape.");
          if (c[0].type !== "float32" && c[0].type !== "float64") throw new Error("Invalid input type.");
        };
      }, 3346: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseInstanceNormalizationAttributes = n.instanceNormalization = void 0;
        const u = o(5060), l = o(2039);
        n.instanceNormalization = (s, t, e) => {
          c(t);
          const r = s.run(a(t[0]), t);
          return [s.run(g(s, t[0], e, r.dims), [t[0], r, t[1], t[2]])];
        }, n.parseInstanceNormalizationAttributes = (s) => s.attributes.getFloat("epsilon", 1e-5);
        const h = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [l.TextureType.unpacked] }, a = (s) => Object.assign(Object.assign({}, h), { get: () => ((t, e) => {
          const r = e.dims.slice(), i = r[1], p = r[2] * r[3], m = [r[0], i], _ = `
      vec4 process(int[2] indices) {
        vec4 v = vec4(0.0);
        int a[4];
        a[0] = indices[0];
        a[1] = indices[1];
        float temp = 0.0;
        for(int a2=0; a2<${r[2]}; a2++) {
          a[2] = a2;
          for(int a3=0; a3<${r[3]}; a3++) {
            a[3] = a3;
            float x = _X(a);
            temp += x;
          }
        }
        float mean = temp / float(${p});
        temp = 0.0;
        for(int a2=0; a2<${r[2]}; a2++) {
          a[2] = a2;
          for(int a3=0; a3<${r[3]}; a3++) {
            a[3] = a3;
            float x = _X(a);
            temp += (x - mean) * (x - mean);
          }
        }
        v.r = mean;
        v.g = temp / float(${p});

        return v;
      }`;
          return Object.assign(Object.assign({}, t), { output: { dims: m, type: e.type, textureType: l.TextureType.packedLastDimension }, shaderSource: _ });
        })(h, s) }), f = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [l.TextureType.unpacked, l.TextureType.packedLastDimension, l.TextureType.unpacked, l.TextureType.unpacked] }, g = (s, t, e, r) => {
          const i = Object.assign(Object.assign({}, f), { cacheHint: `${e}` });
          return Object.assign(Object.assign({}, i), { get: () => ((p, m, _, b, y) => {
            const w = (0, u.getGlsl)(p.session.backend.glContext.version), [T, S] = p.calculateTextureWidthAndHeight(y, l.TextureType.packedLastDimension), [E, O] = [T / 4, S], v = `
      vec4 get_MeanAndVariance(int[2] mv) {
        int offset = indicesToOffset_MeanAndVariance(mv);
        vec2 coords = offsetToCoords(offset, ${E}, ${O});
        return ${w.texture2D}(MeanAndVariance, coords);
      }

      float process(int[4] indices) {
        int mv[2];
        mv[0] = indices[0];
        mv[1] = indices[1];
        vec4 mean_and_variance = get_MeanAndVariance(mv);
        float mean = mean_and_variance.r;
        float variance = mean_and_variance.g;

        int sb[1];
        sb[0] = indices[1];
        float scale = _Scale(sb);
        float b = _B(sb);

        return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;
      }`;
            return Object.assign(Object.assign({}, m), { output: { dims: _.dims, type: _.type, textureType: l.TextureType.unpacked }, variables: [{ name: "epsilon", type: "float", data: b }], shaderSource: v });
          })(s, i, t, e, r) });
        }, c = (s) => {
          if (!s || s.length !== 3) throw new Error("InstanceNormalization requires 3 inputs.");
          const t = s[0], e = s[1], r = s[2];
          if (t.dims.length < 3 || e.dims.length !== 1 || r.dims.length !== 1) throw new Error("Invalid input shape.");
          if (e.dims[0] !== t.dims[1] || r.dims[0] !== t.dims[1]) throw new Error("Input shapes are mismatched.");
          if (t.type !== "float32" && t.type !== "float64" || e.type !== "float32" && e.type !== "float64" || r.type !== "float32" && r.type !== "float64") throw new Error("Invalid input type.");
          if (s[0].dims.length !== 4) throw new Error("Only support 4-D input shape.");
        };
      }, 708: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createPackedMatmulProgramInfoLoader = void 0;
        const u = o(2517), l = o(5060), h = o(2039), a = o(9390), f = o(2823), g = o(5623);
        n.createPackedMatmulProgramInfoLoader = (c, s, t) => {
          const e = (r = s.length > 2, i = t.activationCacheKey, { name: "MatMul (packed)", inputNames: r ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: r ? [h.TextureType.packed, h.TextureType.packed, h.TextureType.packed] : [h.TextureType.packed, h.TextureType.packed], cacheHint: i });
          var r, i;
          return Object.assign(Object.assign({}, e), { get: () => ((p, m, _, b) => {
            const y = _.length > 2, w = y ? "value += getBiasForMatmul();" : "", T = _[0].dims, S = _[1].dims, E = u.BroadcastUtil.calcShape(T, S, !0), O = !u.ShapeUtil.areEqual(_[0].dims, _[1].dims);
            if (!E) throw new Error("Can't use matmul on the given tensors");
            const v = T[T.length - 1], A = Math.ceil(v / 2), L = T.length, j = S.length, B = (0, l.getGlsl)(p.session.backend.glContext.version), F = (0, a.getCoordsDataType)(E.length), D = E.length, I = (0, a.getGlChannels)(), { activationFunction: $, applyActivation: Q } = (0, f.getActivationSnippet)(b), Y = y ? `${(0, g.getBiasForMatmul)(F, I, _[2].dims, E, !0)}` : "", te = O ? `${(function(Ee, ce, ve, ye) {
              let Le = [], We = [];
              const Oe = ve[0].dims, Ne = ve[1].dims, Ce = Oe.length, Pe = Ne.length, Te = ye.length, Be = Te - Ce, Ve = Te - Pe;
              Le = Oe.map(((Se, $e) => `coords.${ce[$e + Be]}`)), Le[Ce - 1] = "i*2", Le.join(", "), We = Ne.map(((Se, $e) => `coords.${ce[$e + Ve]}`)), We[Pe - 2] = "i*2", We.join(", ");
              const ze = u.BroadcastUtil.getBroadcastDims(Oe, ye), He = u.BroadcastUtil.getBroadcastDims(Ne, ye), Xe = ze.map(((Se) => `coords.${ce[Se + Be]} = 0;`)).join(`
`), Ue = He.map(((Se) => `coords.${ce[Se + Ve]} = 0;`)).join(`
`), je = `int lastDim = coords.${ce[Te - 1]};
  coords.${ce[Te - 1]} = coords.${ce[Te - 2]};
  coords.${ce[Te - 2]} = lastDim;`;
              return `
vec4 getAAtOutCoordsMatmul(int i) {
  ${Ee} coords = getOutputCoords();
  ${je}
  ${Xe}
  vec4 outputValue = getA(${Le});
  return outputValue;
}

vec4 getBAtOutCoordsMatmul(int i) {
  ${Ee} coords = getOutputCoords();
  ${je}
  ${Ue}
  vec4 outputValue = getB(${We});
  return outputValue;
}`;
            })(F, I, _, E)}` : "", ne = O ? "getAAtOutCoordsMatmul(i)" : `getA(${(function(Ee, ce) {
              let ve = "";
              for (let ye = 0; ye < ce - 2; ye++) ve += `rc.${Ee[ye]}, `;
              return ve += `rc.${Ee[ce - 2]}, i*2`, ve;
            })(I, L)})`, me = O ? "getBAtOutCoordsMatmul(i)" : `getB(${(function(Ee, ce) {
              let ve = "";
              for (let ye = 0; ye < ce - 2; ye++) ve += `rc.${Ee[ye]}, `;
              return ve += `i*2, rc.${Ee[ce - 1]}`, ve;
            })(I, j)})`, Ae = `
            ${te}
            ${Y}
            ${$}
            void main() {
              ${O ? "" : `${F} rc =
          getOutputCoords(); int lastDim = rc.${I[D - 1]}; rc.${I[D - 1]} =
          rc.${I[D - 2]}; rc.${I[D - 2]} = lastDim;
      `}

              vec4 value = vec4(0);
              for (int i = 0; i < ${A}; i++) {
                vec4 a = ${ne};
                vec4 b = ${me};

                value += (a.rrbb * b.rgrg);
                value += (a.ggaa * b.baba);
              }
              ${w}
              ${Q}
              ${B.output} = value;
            }`;
            return Object.assign(Object.assign({}, m), { output: { dims: E, type: _[0].type, textureType: h.TextureType.packed }, shaderSource: Ae, hasMain: !0 });
          })(c, e, s, t) });
        };
      }, 5623: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.getBiasForMatmul = n.createMatmulProgramInfoLoader = n.parseMatMulAttributes = n.matMul = void 0;
        const u = o(2517), l = o(2039), h = o(9390), a = o(2823), f = o(708);
        function g(t, e) {
          const r = (i = t.length > 2, p = e.activationCacheKey, { name: "MatMul", inputNames: i ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: i ? [l.TextureType.unpacked, l.TextureType.unpacked, l.TextureType.unpacked] : [l.TextureType.unpacked, l.TextureType.unpacked], cacheHint: p });
          var i, p;
          return Object.assign(Object.assign({}, r), { get: () => (function(m, _, b) {
            const y = _[0].dims, w = _[1].dims, T = u.BroadcastUtil.calcShape(y, w, !0);
            if (!T) throw new Error("Can't use matmul on the given tensors");
            const S = (0, h.getCoordsDataType)(T.length), E = (0, h.getGlChannels)(), { activationFunction: O, applyActivation: v } = (0, a.getActivationSnippet)(b), A = _.length > 2, L = A ? "value += getBiasForMatmul();" : "", j = A ? `${s(S, E, _[2].dims, T, !1)}` : "", B = T.length, F = y.length, D = w.length, I = `
    ${O}
    ${j}
    float process(int indices[${B}]) {
        int a[${F}];
        int b[${D}];
        bcastMatmulIndices_A(indices, a);
        bcastMatmulIndices_B(indices, b);

        float value;
        for (int k=0; k<${y[y.length - 1]}; ++k) {
            a[${F - 1}] = k;
            b[${D - 2}] = k;
            value += _A(a) * _B(b);
        }
        ${L}
        ${v}
        return value;
    }`;
            return Object.assign(Object.assign({}, m), { output: { dims: T, type: _[0].type, textureType: l.TextureType.unpacked }, shaderSource: I });
          })(r, t, e) });
        }
        n.matMul = (t, e, r) => (c(e), t.session.pack ? [t.run((0, f.createPackedMatmulProgramInfoLoader)(t, e, r), e)] : [t.run(g(e, r), e)]), n.parseMatMulAttributes = (t) => (0, a.parseInternalActivationAttributes)(t.attributes), n.createMatmulProgramInfoLoader = g;
        const c = (t) => {
          if (!t || t.length !== 2) throw new Error("MatMul requires 2 inputs.");
          if (t[0].dims[t[0].dims.length - 1] !== t[1].dims[t[1].dims.length - 2]) throw new Error("shared dimension does not match.");
          if (t[0].type !== "float32" && t[0].type !== "float64" || t[1].type !== "float32" && t[1].type !== "float64") throw new Error("inputs should be float type");
          if (t[0].type !== t[1].type) throw new Error("inputs types should match");
        };
        function s(t, e, r, i, p) {
          let m = "";
          const _ = r.length, b = i.length, y = b - _;
          m = b < 2 && _ > 0 ? "coords" : r.map(((S, E) => `coords.${e[E + y]}`)).join(", ");
          const w = u.BroadcastUtil.getBroadcastDims(r, i).map(((S) => `coords.${e[S + y]} = 0;`)).join(`
`);
          let T = "vec4(outputValue.xx, outputValue.yy)";
          return u.ShapeUtil.size(r) === 1 && (T = "vec4(outputValue.x)"), p ? `
vec4 getBiasForMatmul() {
  ${t} coords = getOutputCoords();
  ${w}
  vec4 outputValue = getBias(${m});
  return ${T};
}` : `
float getBiasForMatmul() {
  ${t} coords = getOutputCoords();
  ${w}
  return getBias(coords.x);
}`;
        }
        n.getBiasForMatmul = s;
      }, 2403: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createPackProgramInfoLoader = void 0;
        const u = o(5060), l = o(2039), h = o(9390), a = o(2827), f = { name: "pack", inputNames: ["A"], inputTypes: [l.TextureType.unpackedReversed] };
        n.createPackProgramInfoLoader = (g, c) => Object.assign(Object.assign({}, f), { get: () => ((s, t) => {
          const e = (0, u.getGlsl)(s.session.backend.glContext.version), r = t.dims, i = r.length, p = t.dims.length, m = (0, h.getCoordsDataType)(p), _ = (0, a.getChannels)("rc", p), b = (y = p, w = _, T = r[r.length - 2], S = r[r.length - 1], y === 0 || y === 1 ? "" : `
    int r = ${w[y - 2]};
    int c = ${w[y - 1]};
    int rp1 = ${w[y - 2]} + 1;
    int cp1 = ${w[y - 1]} + 1;
    bool rEdge = rp1 >= ${S};
    bool cEdge = cp1 >= ${T};
    `);
          var y, w, T, S;
          let E;
          E = i === 0 ? [1, 1] : i === 1 ? [r[0], 1] : [r[p - 1], r[p - 2]];
          const O = (function(L, j, B) {
            if (L === 0) return "false";
            if (L === 1) return `rc > ${j[0]}`;
            let F = "";
            for (let D = L - 2; D < L; D++) F += `${B[D]} >= ${j[D - L + 2]}`, D < L - 1 && (F += "||");
            return F;
          })(p, E, _), v = (function(L, j) {
            const B = L.length;
            if (B === 0) return "getA(), 0, 0, 0";
            if (B === 1) return `getA(rc),
            rc + 1 >= ${L[0]} ? 0. : getA(rc + 1),
            0, 0`;
            let F = "";
            if (B > 2) for (let D = 0; D < B - 2; ++D) F += `${j[D]},`;
            return `getA(${F}r, c),
          rEdge ? 0. : getA(${F}rp1, c),
          cEdge ? 0. : getA(${F}r, cp1),
          rEdge || cEdge ? 0. : getA(${F}rp1, cp1)`;
          })(r, _), A = `
        void main() {
          ${m} rc = getOutputCoords();

          if(${O}) {
            ${e.output} = vec4(0);
          } else {
            ${b}

            ${e.output} = vec4(${v});
          }
        }
      `;
          return Object.assign(Object.assign({}, f), { hasMain: !0, output: { dims: t.dims, type: t.type, textureType: l.TextureType.packed }, shaderSource: A });
        })(g, c) });
      }, 2827: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.unpackFromChannel = n.getChannels = n.getVecChannels = void 0;
        const u = o(9390);
        function l(h, a) {
          return (0, u.getGlChannels)(a).map(((f) => `${h}.${f}`));
        }
        n.getVecChannels = l, n.getChannels = function(h, a) {
          return a === 1 ? [h] : l(h, a);
        }, n.unpackFromChannel = function() {
          return `
    float getChannel(vec4 frag, int dim) {
      int modCoord = imod(dim, 2);
      return modCoord == 0 ? frag.r : frag.g;
    }

    float getChannel(vec4 frag, vec2 innerDims) {
      vec2 modCoord = mod(innerDims, 2.);
      return modCoord.x == 0. ?
        (modCoord.y == 0. ? frag.r : frag.g) :
        (modCoord.y == 0. ? frag.b : frag.a);
    }
  `;
        };
      }, 2870: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parsePadAttributesV11 = n.padV11 = n.parsePadAttributesV2 = n.padV2 = void 0;
        const u = o(246), l = o(2517), h = o(5060), a = o(2039), f = { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
        n.padV2 = (m, _, b) => (s(_), [m.run(Object.assign(Object.assign({}, f), { cacheHint: b.cacheKey, get: () => c(m, _[0], b) }), _)]), n.parsePadAttributesV2 = (m) => {
          const _ = m.attributes.getString("mode", "constant"), b = m.attributes.getFloat("value", 0), y = m.attributes.getInts("pads");
          return (0, u.createAttributeWithCacheKey)({ mode: _, value: b, pads: y });
        }, n.padV11 = (m, _, b) => {
          t(_);
          const y = g(m, _, b);
          return (0, n.padV2)(m, [_[0]], y);
        }, n.parsePadAttributesV11 = (m) => m.attributes.getString("mode", "constant");
        const g = (m, _, b) => {
          if (!m.session.isInitializer(_[1].dataId) || _.length >= 3 && !m.session.isInitializer(_[2].dataId)) throw new Error("dynamic pad attributes are not allowed");
          const y = Array.from(_[1].integerData), w = _.length >= 3 ? _[2].floatData[0] : 0;
          return (0, u.createAttributeWithCacheKey)({ mode: b, pads: y, value: w });
        }, c = (m, _, b) => {
          const y = l.ShapeUtil.padShape(_.dims.slice(), b.pads), w = y.length, T = `
      ${e(m, _, b)}
      float process(int[${w}] indices) {
          return padA(indices);
      }`;
          return { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked], output: { dims: y, type: _.type, textureType: a.TextureType.unpacked }, shaderSource: T };
        }, s = (m) => {
          if (!m || m.length !== 1) throw new Error("Pad requires 1 input");
          if (m[0].type !== "float32" && m[0].type !== "float64") throw new Error("Invalid input type.");
        }, t = (m) => {
          if (!m || m.length !== 2 && m.length !== 3) throw new Error("Pad requires 2 or 3 inputs");
          if (m[1].type !== "int32") throw new Error("Invalid input type.");
          if (m.length >= 3 && m[2].type === "string") throw new Error("Invalid input type.");
        }, e = (m, _, b) => {
          const y = (0, h.getGlsl)(m.session.backend.glContext.version), [w, T] = m.calculateTextureWidthAndHeight(_.dims, a.TextureType.unpacked), S = l.ShapeUtil.computeStrides(_.dims);
          switch (b.mode) {
            case "constant":
              return r(y, _.dims, S, w, T, b.pads, b.value);
            case "reflect":
              return i(y, _.dims, S, w, T, b.pads);
            case "edge":
              return p(y, _.dims, S, w, T, b.pads);
            default:
              throw new Error("Invalid mode");
          }
        }, r = (m, _, b, y, w, T, S) => {
          const E = _.length;
          let O = "";
          for (let v = E - 1; v >= 0; --v) O += `
        k = m[${v}] - ${T[v]};
        if (k < 0)  return constant;
        if (k >= ${_[v]}) return constant;
        offset += k * ${b[v]};
        `;
          return `
      float padA(int m[${E}]) {
        const float constant = float(${S});
        int offset = 0;
        int k = 0;
        ${O}
        vec2 coords = offsetToCoords(offset, ${y}, ${w});
        float value = getColorAsFloat(${m.texture2D}(A, coords));
        return value;
      }
      `;
        }, i = (m, _, b, y, w, T) => {
          const S = _.length;
          let E = "";
          for (let O = S - 1; O >= 0; --O) E += `
        k = m[${O}] - ${T[O]};
        if (k < 0) { k = -k; }
        {
          const int _2n_1 = ${2 * (_[O] - 1)};
          k = int( mod( float(k), float(_2n_1) ) ) ;
          if(k >= ${_[O]}) { k = _2n_1 - k; }
        }
        offset += k * ${b[O]};
        `;
          return `
      float padA(int m[${S}]) {
        int offset = 0;
        int k = 0;
        ${E}
        vec2 coords = offsetToCoords(offset, ${y}, ${w});
        float value = getColorAsFloat(${m.texture2D}(A, coords));
        return value;
      }
      `;
        }, p = (m, _, b, y, w, T) => {
          const S = _.length;
          let E = "";
          for (let O = S - 1; O >= 0; --O) E += `
        k = m[${O}] - ${T[O]};
        if (k < 0)  k = 0;
        if (k >= ${_[O]}) k = ${_[O] - 1};
        offset += k * ${b[O]};
      `;
          return `
      float padA(int m[${S}]) {
        int offset = 0;
        int k = 0;
        ${E}
        vec2 coords = offsetToCoords(offset, ${y}, ${w});
        float value = getColorAsFloat(${m.texture2D}(A, coords));
        return value;
      }
      `;
        };
      }, 2143: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.globalMaxPool = n.parseMaxPoolAttributes = n.maxPool = n.parseGlobalAveragePoolAttributes = n.globalAveragePool = n.parseAveragePoolAttributes = n.averagePool = void 0;
        const u = o(246), l = o(2517), h = o(2039);
        n.averagePool = (p, m, _) => {
          t(m);
          const b = { name: "AveragePool", inputNames: ["X"], inputTypes: [h.TextureType.unpacked], cacheHint: _.cacheKey };
          return [p.run(Object.assign(Object.assign({}, b), { get: () => a(m, b, !1, _) }), m)];
        }, n.parseAveragePoolAttributes = (p) => {
          const m = p.attributes.getString("auto_pad", "NOTSET"), _ = p.attributes.getInt("ceil_mode", 0), b = p.attributes.getInt("count_include_pad", 0) !== 0, y = p.attributes.getInts("kernel_shape"), w = p.attributes.getInts("strides", []), T = p.attributes.getInts("pads", []);
          if (_ !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool");
          return (0, u.createAttributeWithCacheKey)({ autoPad: m, ceilMode: _, countIncludePad: b, kernelShape: y, strides: w, pads: T });
        };
        const a = (p, m, _, b) => {
          const [y, w] = g(p, b, _), T = l.ShapeUtil.size(y.kernelShape);
          let S = "";
          y.countIncludePad ? S += `value /= float(${T});` : S += `value /= float(${T} - pad);`;
          const E = `
        ${e(p[0].dims, y, "value += _X(x);", S, "0.0")}
      `;
          return Object.assign(Object.assign({}, m), { output: { dims: w, type: p[0].type, textureType: h.TextureType.unpacked }, shaderSource: E });
        };
        n.globalAveragePool = (p, m, _) => {
          t(m);
          const b = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [h.TextureType.unpacked], cacheHint: `${_.countIncludePad}` };
          return [p.run(Object.assign(Object.assign({}, b), { get: () => a(m, b, !0, _) }), m)];
        }, n.parseGlobalAveragePoolAttributes = (p) => {
          const m = p.attributes.getInt("count_include_pad", 0) !== 0;
          return (0, u.createAttributeWithCacheKey)({ autoPad: "", ceilMode: 0, countIncludePad: m, kernelShape: [], strides: [], pads: [] });
        }, n.maxPool = (p, m, _) => {
          t(m);
          const b = { name: "MaxPool", inputNames: ["X"], inputTypes: [h.TextureType.unpacked], cacheHint: _.cacheKey };
          return [p.run(Object.assign(Object.assign({}, b), { get: () => f(m, b, !1, _) }), m)];
        }, n.parseMaxPoolAttributes = (p) => {
          const m = p.attributes.getString("auto_pad", "NOTSET"), _ = p.attributes.getInt("ceil_mode", 0), b = p.attributes.getInts("kernel_shape"), y = p.attributes.getInts("strides", []), w = p.attributes.getInts("pads", []), T = p.attributes.getInt("storage_order", 0), S = p.attributes.getInts("dilations", []);
          if (T !== 0) throw new Error("column major storage order is not yet supported for MaxPool");
          if (_ !== 0) throw new Error("using ceil() in shape computation is not yet supported for MaxPool");
          return (0, u.createAttributeWithCacheKey)({ autoPad: m, ceilMode: _, countIncludePad: !1, kernelShape: b, strides: y, pads: w, storageOrder: T, dilations: S });
        };
        const f = (p, m, _, b) => {
          const [y, w] = g(p, b, _), T = `
      ${e(p[0].dims, y, `
      value = max(_X(x), value);
    `, "", "-1e5")}
    `;
          return Object.assign(Object.assign({}, m), { output: { dims: w, type: p[0].type, textureType: h.TextureType.unpacked }, shaderSource: T });
        }, g = (p, m, _) => {
          const b = p[0].dims.slice(), y = Object.hasOwnProperty.call(m, "dilations"), w = m.kernelShape.slice(), T = m.strides.slice(), S = y ? m.dilations.slice() : [], E = m.pads.slice();
          l.PoolConvUtil.adjustPoolAttributes(_, b, w, T, S, E);
          const O = l.PoolConvUtil.computePoolOutputShape(_, b, T, S, w, E, m.autoPad), v = Object.assign({}, m);
          return y ? Object.assign(v, { kernelShape: w, strides: T, pads: E, dilations: S, cacheKey: m.cacheKey }) : Object.assign(v, { kernelShape: w, strides: T, pads: E, cacheKey: m.cacheKey }), [v, O];
        }, c = { autoPad: "", ceilMode: 0, countIncludePad: !1, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, s = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [h.TextureType.unpacked] };
        n.globalMaxPool = (p, m) => (t(m), [p.run(Object.assign(Object.assign({}, s), { get: () => f(m, s, !0, c) }), m)]);
        const t = (p) => {
          if (!p || p.length !== 1) throw new Error("Pool ops requires 1 input.");
          if (p[0].type !== "float32" && p[0].type !== "float64") throw new Error("Invalid input type.");
        }, e = (p, m, _, b, y) => {
          const w = p.length;
          if (m.kernelShape.length <= 2) {
            const T = m.kernelShape[m.kernelShape.length - 1], S = m.strides[m.strides.length - 1], E = m.pads[m.pads.length / 2 - 1], O = m.pads[m.pads.length - 1], v = p[w - 1];
            let A = "", L = "", j = "";
            if (A = E + O !== 0 ? `
          for (int i = 0; i < ${T}; i++) {
            x[${w} - 1] = indices[${w} - 1] * ${S} - ${E} + i;
            if (x[${w} - 1] < 0 || x[${w} - 1] >= ${v}) {
              pad++;
              continue;
            }
            ${_}
          }` : `
          for (int i = 0; i < ${T}; i++) {
            x[${w} - 1] = indices[${w} - 1] * ${S} - ${E} + i;
            ${_}
          }`, m.kernelShape.length === 2) {
              const B = m.kernelShape[m.kernelShape.length - 2], F = m.strides[m.strides.length - 2], D = m.pads[m.pads.length / 2 - 2], I = m.pads[m.pads.length - 2], $ = p[w - 2];
              L = D + I !== 0 ? `
            for (int j = 0; j < ${B}; j++) {
              x[${w} - 2] = indices[${w} - 2] * ${F} - ${D} + j;
              if (x[${w} - 2] < 0 || x[${w} - 2] >= ${$}) {
                pad+= ${T};
                continue;
              }
          ` : `
            for (int j = 0; j < ${B}; j++) {
              x[${w} - 2] = indices[${w} - 2] * ${F} - ${D} + j;
            `, j = `
          }
        `;
            }
            return `
        float process(int indices[${w}]) {
          int x[${w}];
          copyVec(indices, x);

          float value = ${y};
          int pad = 0;
          ${L}
          ${A}
          ${j}
          ${b}
          return value;
        }
      `;
          }
          {
            const T = l.ShapeUtil.size(m.kernelShape), S = l.ShapeUtil.computeStrides(m.kernelShape), E = S.length, O = m.pads.length, v = i(E), A = r(p, "inputDims"), L = r(m.pads, "pads"), j = r(S, "kernelStrides"), B = r(m.strides, "strides");
            let F = "";
            return F = m.pads.reduce(((D, I) => D + I)) ? `
            if (x[j] >= inputDims[j] || x[j] < 0) {
              pad++;
              isPad = true;
              break;
            }
          }
          if (!isPad) {
            ${_}
          }` : `
          }
          ${_}
        `, `
        ${v}
        float process(int indices[${w}]) {
          int x[${w}];
          copyVec(indices, x);
          int offset[${E}];
          int pads[${O}];
          int inputDims[${w}];
          int kernelStrides[${E}];
          int strides[${E}];
          ${L}
          ${A}
          ${B}
          ${j}

          float value = ${y};
          int pad = 0;
          bool isPad = false;
          for (int i = 0; i < ${T}; i++) {
            offsetToIndices(i, kernelStrides, offset);
            isPad = false;
            for (int j = ${w} - ${E}; j < ${w}; j++) {
              x[j] = indices[j] * strides[j - ${w} + ${E}]
                + offset[j - ${w} + ${E}] - pads[j - 2];
              ${F}
          }
          ${b}

          return value;
        }
      `;
          }
        }, r = (p, m) => {
          let _ = "";
          for (let b = 0; b < p.length; b++) _ += `
      ${m}[${b}] = ${p[b]};
    `;
          return _;
        }, i = (p) => `
  void offsetToIndices(int offset, int[${p}] strides, out int[${p}] indices) {
    if (${p} == 0) {
      return;
    }
    for (int i = 0; i < ${p} - 1; ++i) {
      indices[i] = offset / strides[i];
      offset -= indices[i] * strides[i];
    }
    indices[${p} - 1] = offset;
  }`;
      }, 4939: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.reduceLogSumSquare = n.reduceLogSum = n.reduceProd = n.reduceMin = n.reduceMax = n.reduceMean = n.reduceSum = n.parseReduceAttributes = void 0;
        const u = o(246), l = o(782), h = o(2517), a = o(2039), f = (s, t, e, r, i) => {
          c(t);
          const p = { name: r, inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
          return [s.run(Object.assign(Object.assign({}, p), { cacheHint: e.cacheKey, get: () => g(s, t, e, r, i, p) }), t)];
        };
        n.parseReduceAttributes = (s) => {
          const t = s.attributes.getInts("axes", []), e = s.attributes.getInt("keepdims", 1) === 1;
          return (0, u.createAttributeWithCacheKey)({ axes: t, keepDims: e });
        };
        const g = (s, t, e, r, i, p) => {
          const m = [], _ = t[0].dims.length || 1, b = [], y = h.ShapeUtil.normalizeAxes(e.axes, t[0].dims.length), w = i(t, y);
          let T = w[1];
          for (let E = 0; E < t[0].dims.length; E++) y.indexOf(E) >= 0 || y.length === 0 ? (e.keepDims && m.push(1), T = `
          for(int j${E} = 0; j${E} < ${t[0].dims[E]}; j${E}++) {
            inputIdx[${E}] = j${E};
            ${T}
          }`) : (b.push(`inputIdx[${E}] = outputIdx[${m.length}];`), m.push(t[0].dims[E]));
          const S = `
      float process(int outputIdx[${m.length || 1}]) {
        float value;                 // final result
        int inputIdx[${_}];      // addressing input data
        ${b.join(`
`)}
        ${w[0]}       // init ops for reduce max/min
        ${T}
        ${w[2]}       // final computation for reduce mean
        return value;
      }`;
          return Object.assign(Object.assign({}, p), { output: { dims: m, type: t[0].type, textureType: a.TextureType.unpacked }, shaderSource: S });
        }, c = (s) => {
          if (!s || s.length !== 1) throw new Error("Reduce op requires 1 input.");
          if (l.NUMBER_TYPES.indexOf(s[0].type) === -1) throw new Error("Invalid input type.");
        };
        n.reduceSum = (s, t, e) => f(s, t, e, "ReduceSum", (() => ["value = 0.0;", "value += _A(inputIdx);", ""])), n.reduceMean = (s, t, e) => f(s, t, e, "ReduceMean", ((r, i) => {
          let p = 1;
          for (let m = 0; m < r[0].dims.length; m++) (i.indexOf(m) >= 0 || i.length === 0) && (p *= r[0].dims[m]);
          return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${p}.;`];
        })), n.reduceMax = (s, t, e) => f(s, t, e, "ReduceMax", ((r, i) => {
          const p = [];
          for (let m = 0; m < r[0].dims.length; m++) (i.indexOf(m) >= 0 || i.length === 0) && p.push(`inputIdx[${m}] = 0;`);
          return [`${p.join(`
`)}
value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""];
        })), n.reduceMin = (s, t, e) => f(s, t, e, "ReduceMin", ((r, i) => {
          const p = [];
          for (let m = 0; m < r[0].dims.length; m++) (i.indexOf(m) >= 0 || i.length === 0) && p.push(`inputIdx[${m}] = 0;`);
          return [`${p.join(`
`)}
value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""];
        })), n.reduceProd = (s, t, e) => f(s, t, e, "ReduceProd", (() => ["value = 1.0;", "value *= _A(inputIdx);", ""])), n.reduceLogSum = (s, t, e) => f(s, t, e, "ReduceLogSum", (() => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"])), n.reduceLogSumSquare = (s, t, e) => f(s, t, e, "ReduceLogSumSquare", (() => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""]));
      }, 7019: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.isReshapeCheap = n.processDims3D = n.createPackedReshape3DProgramInfoLoader = void 0;
        const u = o(2517), l = o(5060), h = o(2039), a = o(2827);
        n.createPackedReshape3DProgramInfoLoader = (f, g, c) => {
          const s = ((t) => ({ name: "Reshape (packed)", inputTypes: [h.TextureType.packed], inputNames: ["A"], cacheHint: `${t}` }))(c);
          return Object.assign(Object.assign({}, s), { get: () => ((t, e, r, i) => {
            const p = e.dims, m = i;
            let _ = "";
            for (let w = 0; w < 4; w++) {
              let T = "";
              switch (w) {
                case 0:
                  T = "outputCoords = rc;";
                  break;
                case 1:
                  T = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);";
                  break;
                case 2:
                  T = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);";
                  break;
                case 3:
                  T = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";
                  break;
                default:
                  throw new Error();
              }
              _ += `
        ${T}
        ${w > 0 ? "if(outputCoords.y < rows && outputCoords.z < cols){" : ""}
          int flattenedIndex = getFlattenedIndex(outputCoords);

          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);
          vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));

          result[${w}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);

        ${w > 0 ? "}" : ""}
      `;
            }
            const b = (0, l.getGlsl)(t.session.backend.glContext.version), y = `
      ${(function(w) {
              const T = u.ShapeUtil.computeStrides(w), S = ["b", "r", "c"], E = "index";
              return `
    ivec3 inputCoordsFromReshapedOutCoords(int index) {
      ${T.map(((O, v) => `int ${S[v]} = ${E} / ${O}; ${v === T.length - 1 ? `int ${S[v + 1]} = ${E} - ${S[v]} * ${O}` : `index -= ${S[v]} * ${O}`};`)).join("")}
      return ivec3(b, r, c);
    }
  `;
            })(p)}
      ${(function(w) {
              const T = u.ShapeUtil.computeStrides(w);
              return `
  int getFlattenedIndex(ivec3 coords) {
    // reverse y, z order
    return coords.x * ${T[0]} + coords.z * ${T[1]} + coords.y;
  }
`;
            })(m)}
      ${(0, a.unpackFromChannel)()}

      void main() {
        ivec3 rc = getOutputCoords();

        vec4 result = vec4(0.0);

        ivec3 outputCoords;
        int rows = ${m[2]};
        int cols = ${m[1]};

        ${_}
        ${b.output} = result;
      }
    `;
            return Object.assign(Object.assign({}, r), { output: { dims: m, type: e.type, textureType: h.TextureType.packed }, shaderSource: y, hasMain: !0 });
          })(f, g, s, c) });
        }, n.processDims3D = function(f) {
          if (f.length === 0) return [1, 1, 1];
          let g = 1;
          for (let c = 0; c < f.length - 2; ++c) g *= f[c];
          return [g, f.length > 1 ? f[f.length - 2] : 1, f[f.length - 1]];
        }, n.isReshapeCheap = function(f, g) {
          let c = !1;
          return c = f.length === 0 || g.length === 0 || (f.length < 2 || g.length < 2 ? f[f.length - 1] === g[g.length - 1] : f[f.length - 1] === g[g.length - 1] && f[f.length - 2] === g[g.length - 2]), c;
        };
      }, 718: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.reshape = void 0;
        const u = o(2517);
        n.reshape = (l, h) => {
          const a = u.ShapeUtil.calculateReshapedDims(h[0].dims, h[1].integerData);
          return l.session.pack ? [l.reshapePacked(h[0], a)] : [l.reshapeUnpacked(h[0], a)];
        };
      }, 2268: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseResizeAttributesV11 = n.parseResizeAttributesV10 = n.resize = void 0;
        const u = o(5060), l = o(2039), h = o(9390), a = o(2827), f = o(9793), g = { name: "Resize", inputNames: ["A"], inputTypes: [l.TextureType.packed] };
        n.resize = (r, i, p) => ((0, f.validateInputs)(i, p), [r.run(Object.assign(Object.assign({}, g), { cacheHint: p.cacheKey, get: () => c(r, i, p) }), i)]), n.parseResizeAttributesV10 = (r) => (0, f.parseUpsampleAttributes)(r, 10), n.parseResizeAttributesV11 = (r) => (0, f.parseUpsampleAttributes)(r, 11);
        const c = (r, i, p) => {
          const m = (0, u.getGlsl)(r.session.backend.glContext.version), [_, b] = s(i, p);
          if (_.every(((F) => F === 1)) && p.coordinateTransformMode !== "tf_crop_and_resize") return Object.assign(Object.assign({}, g), { output: { dims: b, type: i[0].type, textureType: l.TextureType.packed }, hasMain: !0, shaderSource: `void main() {
                    vec4 v = ${m.texture2D}(X, TexCoords);
                    ${m.output} = v;
                }` });
          const y = b.length;
          if (y < 2) throw new Error(`output dimension should be at least 2, but got ${y}`);
          const w = b[y - 2], T = b[y - 1], S = i[0].dims;
          if (y !== S.length) throw new Error(`output dimension should match input ${S.length}, but got ${y}`);
          const E = S[y - 2], O = S[y - 1], v = _[y - 2], A = _[y - 1];
          let L = "";
          if (p.mode !== "linear") throw new Error(`resize (packed) does not support mode: '${p.mode}'`);
          switch (p.coordinateTransformMode) {
            case "asymmetric":
              L = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        return vec4(coords) / scaleWHWH;
                    }
                `;
              break;
            case "half_pixel":
              L = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        return (vec4(coords) + 0.5) / scaleWHWH - 0.5;
                    }
                `;
              break;
            case "pytorch_half_pixel":
              L = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        vec4 fcoords = vec4(coords);
                        return vec4(
                            ${T}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,
                            ${w}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,
                            ${T}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,
                            ${w}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0
                          );
                    }
                `;
              break;
            case "align_corners":
              L = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        vec4 resized = vec4(${T}.0 - 1.0, ${w}.0 - 1.0, ${T}.0 - 1.0,
                            ${w}.0 - 1.0);
                        vec4 original = vec4(${O}.0 - 1.0, ${E}.0 - 1.0, ${O}.0 - 1.0,
                            ${E}.0 - 1.0);
                        vec4 new_scale = original / resized;
                        return vec4(coords) * new_scale;
                    }
                `;
              break;
            default:
              throw new Error(`resize (packed) does not support coordinateTransformMode:                                 '${p.coordinateTransformMode}'`);
          }
          const j = (0, h.getCoordsDataType)(y), B = `
            const vec2 inputWH = vec2(${E}.0, ${O}.0);
            const vec4 scaleWHWH = vec4(float(${v}), float(${A}), float(${v}), float(${A}));
            ${(0, a.unpackFromChannel)()}
            ${L}
            float getAValue(int x10, int r, int c, int d) {
                return getChannel(getA(x10, r, c, d), vec2(c, d));
            }
            void main() {
                ${j} rc = getOutputCoords();

                int batch = rc[0];
                int depth = rc[1];

                // retrieve the 4 coordinates that is used in the 4 packed output values.
                ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);

                // calculate the source index in fraction
                vec4 sourceFrac = getSourceFracIndex(coords);

                // get the lower and upper bound of the 4 values that will be packed into one texel.
                ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));
                ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));
                ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));
                ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));

                bool hasNextRow = rc.w < ${w - 1};
                bool hasNextCol = rc.z < ${T - 1};

                // pack x00, x01, x10, x11's top-left corner into one vec4 structure
                vec4 topLeft = vec4(
                    getAValue(batch, depth, x00.x, x00.y),
                    hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);

                // pack x00, x01, x10, x11's top-right corner into one vec4 structure
                vec4 topRight = vec4(
                    getAValue(batch, depth, x00.x, x00.w),
                    hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);

                // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure
                vec4 bottomLeft = vec4(
                    getAValue(batch, depth, x00.z, x00.y),
                    hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);

                // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure
                vec4 bottomRight = vec4(
                    getAValue(batch, depth, x00.z, x00.w),
                    hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);

                // calculate the interpolation fraction on u and v direction
                vec4 frac = vec4(sourceFrac) - floor(sourceFrac);
                vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));

                vec4 top = mix(topLeft, topRight, clampFrac.ywyw);
                vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);
                vec4 newValue = mix(top, bottom, clampFrac.xxzz);

                ${m.output} = vec4(newValue);
            }
        `;
          return Object.assign(Object.assign({}, g), { output: { dims: b, type: i[0].type, textureType: l.TextureType.packed }, hasMain: !0, shaderSource: B });
        }, s = (r, i) => {
          const p = r[0].dims;
          let m, _ = i.scales;
          if (_.length === 0) {
            const y = r[i.scalesInputIdx];
            if (y && y.size !== 0) {
              if (r[i.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input.");
              _ = t(y, i.mode, i.isResize);
            } else {
              const w = r[i.sizesInputIdx];
              if (!w || w.size === 0) throw new Error("Either scales or sizes MUST be provided as input.");
              m = Array.from(w.integerData), _ = e(m, p, i.mode, i.isResize);
            }
          } else if (r[i.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input.");
          const b = m || p.map(((y, w) => Math.floor(y * _[w])));
          return [_, b];
        }, t = (r, i, p) => {
          const m = Array.from(r.floatData);
          return (0, f.scalesValidation)(m, i, p), m;
        }, e = (r, i, p, m) => {
          const _ = i.length, b = new Array(_);
          for (let y = 0, w = _; y < w; y++) if (i[y] === 0) {
            if (r[y] !== 0) throw new Error("Input dim is zero but required output dim is non-zero.");
            b[y] = 1;
          } else b[y] = r[y] / i[y];
          return (0, f.scalesValidation)(b, p, m), b;
        };
      }, 8117: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.shape = void 0;
        const u = o(9162);
        n.shape = (h, a) => (l(a), [new u.Tensor([a[0].dims.length], "int32", void 0, void 0, new Int32Array(a[0].dims))]);
        const l = (h) => {
          if (!h || h.length !== 1) throw new Error("Shape requires 1 input.");
        };
      }, 2278: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.sliceV10 = n.parseSliceAttributes = n.slice = void 0;
        const u = o(246), l = o(782), h = o(2517), a = o(2039), f = { name: "Slice", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
        n.slice = (e, r, i) => (c(r), [e.run(Object.assign(Object.assign({}, f), { cacheHint: i.cacheKey, get: () => g(e, r[0], i) }), r)]), n.parseSliceAttributes = (e) => {
          const r = e.attributes.getInts("starts"), i = e.attributes.getInts("ends"), p = e.attributes.getInts("axes", []);
          return (0, u.createAttributeWithCacheKey)({ starts: r, ends: i, axes: p });
        };
        const g = (e, r, i) => {
          const p = i.axes.length === 0 ? r.dims.slice(0).map(((S, E) => E)) : i.axes, m = h.ShapeUtil.normalizeAxes(p, r.dims.length), _ = i.starts.map(((S, E) => S > r.dims[m[E]] - 1 ? r.dims[m[E]] : h.ShapeUtil.normalizeAxis(S, r.dims[m[E]]))), b = i.ends.map(((S, E) => S > r.dims[m[E]] - 1 ? r.dims[m[E]] : h.ShapeUtil.normalizeAxis(S, r.dims[m[E]]))), y = r.dims.slice(), w = [];
          for (let S = 0; S < m.length; S++) y[m[S]] = b[S] - _[S], _[S] > 0 && w.push(`outputIdx[${m[S]}] += ${_[S]};`);
          const T = `
      float process(int outputIdx[${y.length}]) {
        ${w.join(`
      `)}
        return _A(outputIdx);
      }`;
          return Object.assign(Object.assign({}, f), { output: { dims: y, type: r.type, textureType: a.TextureType.unpacked }, shaderSource: T });
        }, c = (e) => {
          if (!e || e.length !== 1) throw new Error("Slice requires 1 input.");
          if (l.NUMBER_TYPES.indexOf(e[0].type) === -1) throw new Error("Invalid input type.");
        };
        n.sliceV10 = (e, r) => {
          t(r);
          const i = s(e, r);
          return [e.run(Object.assign(Object.assign({}, f), { cacheHint: i.cacheKey, get: () => g(e, r[0], i) }), [r[0]])];
        };
        const s = (e, r) => {
          if (!e.session.isInitializer(r[1].dataId) || !e.session.isInitializer(r[2].dataId) || r.length >= 4 && !e.session.isInitializer(r[3].dataId) || r.length >= 5 && !e.session.isInitializer(r[4].dataId)) throw new Error("dynamic slice attributes are not allowed");
          if (r.length >= 5 && r[4].integerData.some(((_) => _ !== 1))) throw new Error("currently non-1 steps is not supported for Slice");
          const i = Array.from(r[1].integerData), p = Array.from(r[2].integerData), m = r.length >= 4 ? Array.from(r[3].integerData) : [];
          return { starts: i, ends: p, axes: m, cacheKey: `${m};${i};${p}` };
        }, t = (e) => {
          if (!e || e.length < 3 || e.length > 5) throw new Error("Invalid input number.");
          if (e[1].type !== "int32" || e[1].dims.length !== 1) throw new Error("Invalid input type.");
          if (e[2].type !== "int32" || e[2].dims.length !== 1) throw new Error("Invalid input type.");
          if (e.length >= 4 && (e[3].type !== "int32" || e[3].dims.length !== 1)) throw new Error("Invalid input type.");
          if (e.length >= 5 && (e[4].type !== "int32" || e[4].dims.length !== 1)) throw new Error("Invalid input type.");
        };
      }, 5524: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.softmaxV13 = n.parseSoftmaxAttributesV13 = n.parseSoftmaxAttributes = n.softmax = void 0;
        const u = o(246), l = o(2517), h = o(5060), a = o(2039), f = o(3738), g = { name: "SoftmaxComputeMax", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }, c = { name: "SoftmaxComputeScale", inputNames: ["A", "Max"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, s = { name: "SoftMax", inputNames: ["A", "Max", "Norm"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked, a.TextureType.unpacked] };
        n.softmax = (m, _, b) => {
          p(_);
          const y = _[0].dims.slice(), w = l.ShapeUtil.normalizeAxis(b.axis, y.length), T = l.ShapeUtil.sizeToDimension(y, w), S = l.ShapeUtil.sizeFromDimension(y, w);
          return t(m, _, b, T, S);
        }, n.parseSoftmaxAttributes = (m) => (0, u.createAttributeWithCacheKey)({ axis: m.attributes.getInt("axis", 1) }), n.parseSoftmaxAttributesV13 = (m) => (0, u.createAttributeWithCacheKey)({ axis: m.attributes.getInt("axis", -1) }), n.softmaxV13 = (m, _, b) => {
          p(_);
          const y = _[0].dims.slice(), w = l.ShapeUtil.normalizeAxis(b.axis, y.length), T = y.length, S = w !== T - 1, E = [];
          let O, v = [], A = [];
          S && (v = Array.from({ length: T }).map(((F, D) => D)), v[w] = T - 1, v[T - 1] = w, v.map(((F) => E.push(y[F]))), O = (0, u.createAttributeWithCacheKey)({ perm: v }), A = (0, f.transpose)(m, _, O));
          const L = S ? l.ShapeUtil.sizeToDimension(E, T - 1) : l.ShapeUtil.sizeToDimension(y, T - 1), j = S ? l.ShapeUtil.sizeFromDimension(E, T - 1) : l.ShapeUtil.sizeFromDimension(y, T - 1), B = t(m, S ? A : _, b, L, j);
          return S ? (0, f.transpose)(m, B, O) : B;
        };
        const t = (m, _, b, y, w) => {
          const T = e(m, _[0], y, w, [y]), S = m.run(Object.assign(Object.assign({}, g), { cacheHint: b.cacheKey, get: () => T }), _), E = r(m, _[0], y, w, T.output.dims, [y]), O = m.run(Object.assign(Object.assign({}, c), { cacheHint: b.cacheKey, get: () => E }), [_[0], S]), v = i(m, _[0], y, w, T.output.dims, E.output.dims);
          return [m.run(Object.assign(Object.assign({}, s), { cacheHint: b.cacheKey, get: () => v }), [_[0], S, O])];
        }, e = (m, _, b, y, w) => {
          const [T, S] = m.calculateTextureWidthAndHeight(_.dims, a.TextureType.unpacked), E = w.length;
          if (b < 1 || y < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
          if (w.length !== 1) throw new Error("Dimensionality of the output should be 1");
          if (w[0] !== b) throw new Error("Shape of the output should be equal to logical row count");
          const O = (0, h.getGlsl)(m.session.backend.glContext.version), v = `
      float process(int[${E}] indices) {
        int logical_row_start_offset = indices[0] * ${y};

        float max = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset, ${T},
        ${S} )));
        for(int i=1; i<${y}; ++i)
        {
          float current = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
            ${T}, ${S})));
          if(current > max)
          max = current;
        }

        return max;
      }`;
          return Object.assign(Object.assign({}, g), { output: { dims: w, type: _.type, textureType: a.TextureType.unpacked }, shaderSource: v });
        }, r = (m, _, b, y, w, T) => {
          const [S, E] = m.calculateTextureWidthAndHeight(_.dims, a.TextureType.unpacked), O = T.length;
          if (b < 1 || y < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
          if (T.length !== 1) throw new Error("Dimensionality of the output should be 1");
          if (T[0] !== b) throw new Error("Shape of the output should be equal to logical row count");
          if (w.length !== 1) throw new Error("Dimensionality of the intermediate results should be 1");
          if (w[0] !== b) throw new Error("Shape of the intermediate results should be equal to logical row count");
          const v = `
      float process(int[${O}] indices) {
        int logical_row_start_offset = indices[0] * ${y};

        float norm_factor = 0.0;
        float max = _Max(indices);
        for(int i=0; i<${y}; ++i)
        {
          norm_factor += exp(getColorAsFloat(${(0, h.getGlsl)(m.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,
            ${S}, ${E}))) - max);
        }

        return norm_factor;
      }`;
          return Object.assign(Object.assign({}, c), { output: { dims: T, type: _.type, textureType: a.TextureType.unpacked }, shaderSource: v });
        }, i = (m, _, b, y, w, T) => {
          const [S, E] = m.calculateTextureWidthAndHeight(_.dims, a.TextureType.unpacked), O = _.dims.length;
          if (b < 1 || y < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
          if (w.length !== 1 || T.length !== 1) throw new Error("Dimensionality of the intermediate results should be 1");
          if (w[0] !== b || T[0] !== b) throw new Error("Shape of the intermediate results should be equal to logical row count");
          const v = `
      float process(int[${O}] indices) {

      // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
      int offset = coordsToOffset(TexCoords, ${S}, ${E});

      //determine the logical row for this index
      int logical_row_index[1];
      logical_row_index[0] = offset / ${y};

      float norm_factor = _Norm(logical_row_index);

      // avoid possible division by 0
      // if norm_facor is 0, all elements are zero
      // if so, return 0
      if(norm_factor == 0.0)
        return 0.0;

      return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
    }`;
          return Object.assign(Object.assign({}, s), { output: { dims: _.dims, type: _.type, textureType: a.TextureType.unpacked }, shaderSource: v });
        }, p = (m) => {
          if (!m || m.length !== 1) throw new Error("Softmax requires 1 input.");
          if (m[0].type !== "float32" && m[0].type !== "float64") throw new Error("Invalid input type");
        };
      }, 5975: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseSplitAttributes = n.split = void 0;
        const u = o(246), l = o(2517), h = o(2039), a = { name: "Split", inputNames: ["A"], inputTypes: [h.TextureType.unpacked] };
        n.split = (s, t, e) => {
          c(t);
          const r = l.ShapeUtil.normalizeAxis(e.axis, t[0].dims.length), i = f(s, t, r, e), p = [];
          for (let m = 0; m < i; ++m) p.push(s.run(Object.assign(Object.assign({}, a), { cacheHint: `${e.cacheKey};${m}`, get: () => g(s, t[0], e, r, m) }), t));
          return p;
        }, n.parseSplitAttributes = (s) => {
          const t = s.attributes.getInt("axis", 0), e = s.attributes.getInts("split", []), r = s.outputs.length;
          return (0, u.createAttributeWithCacheKey)({ axis: t, split: e, numOutputs: r });
        };
        const f = (s, t, e, r) => {
          const [, i] = l.SplitUtil.splitShape(t[0].dims, e, r.split, r.numOutputs);
          return i.length;
        }, g = (s, t, e, r, i) => {
          const [p, m] = l.SplitUtil.splitShape(t.dims, r, e.split, e.numOutputs), _ = m[i], b = p[i], y = `
      float process(int indices[${b.length}]) {
        indices[${r}] += ${_};
        return _A(indices);
      }
    `;
          return Object.assign(Object.assign({}, a), { cacheHint: `${e.cacheKey}:${i}`, output: { dims: b, type: t.type, textureType: h.TextureType.unpacked }, shaderSource: y });
        }, c = (s) => {
          if (!s || s.length !== 1) throw new Error("Split requires one input.");
          if (s[0].type !== "int8" && s[0].type !== "uint8" && s[0].type !== "int16" && s[0].type !== "uint16" && s[0].type !== "int32" && s[0].type !== "uint32" && s[0].type !== "float32" && s[0].type !== "float64" && s[0].type !== "bool") throw new Error("Invalid input type.");
        };
      }, 3933: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseSqueezeAttributes = n.squeezeV13 = n.squeeze = void 0;
        const u = o(2517);
        n.squeeze = (a, f, g) => {
          l(f);
          const c = u.ShapeUtil.squeezeShape(f[0].dims, g);
          return [a.reshapeUnpacked(f[0], c)];
        }, n.squeezeV13 = (a, f) => (h(f), (0, n.squeeze)(a, [f[0]], Array.from(f[1].integerData))), n.parseSqueezeAttributes = (a) => a.attributes.getInts("axes");
        const l = (a) => {
          if (!a || a.length !== 1) throw new Error("Squeeze requires 1 input.");
          if (a[0].type === "string") throw new Error("invalid input tensor types.");
        }, h = (a) => {
          if (!a || a.length !== 2) throw new Error("Squeeze requires 2 inputs.");
          if (a[1].type !== "int32") throw new Error("Invalid input type.");
        };
      }, 6558: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.sum = void 0;
        const u = o(5060), l = o(2039);
        n.sum = (f, g) => {
          a(g);
          const c = { name: "Sum", inputNames: g.map(((s, t) => `X${t}`)), inputTypes: new Array(g.length).fill(l.TextureType.unpacked) };
          return [f.run(Object.assign(Object.assign({}, c), { get: () => h(f, g, c) }), g)];
        };
        const h = (f, g, c) => {
          const s = (0, u.getGlsl)(f.session.backend.glContext.version), t = g[0].dims.slice(), e = `
      void main() {
        vec4 result = ${g.map(((r, i) => `${s.texture2D}(X${i},TexCoords)`)).join(" + ")};
        ${s.output} = result;
      }
    `;
          return Object.assign(Object.assign({}, c), { output: { dims: t, type: g[0].type, textureType: l.TextureType.unpacked }, hasMain: !0, shaderSource: e });
        }, a = (f) => {
          if (!f || f.length === 0) throw new Error("Sum requires inputs.");
          const g = f[0].dims.length;
          for (let c = 1; c < f.length; c++) {
            if (g !== f[c].dims.length) throw new Error("Input shapes are mismatched.");
            for (let s = 0; s < g; s++) if (f[0].dims[s] !== f[c].dims[s]) throw new Error("Input shapes are not matched.");
          }
          if (f[0].type !== "float32" && f[0].type !== "float64") throw new Error("Invalid input type.");
          for (let c = 1; c < f.length; c++) if (f[0].type !== f[c].type) throw new Error("Input types are not matched.");
        };
      }, 5723: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.tile = void 0;
        const u = o(782), l = o(2039);
        n.tile = (f, g) => {
          a(g);
          const c = { name: "Tile", inputNames: ["A"], inputTypes: [l.TextureType.unpacked] };
          return [f.run(Object.assign(Object.assign({}, c), { get: () => h(f, g, c) }), g)];
        };
        const h = (f, g, c) => {
          const s = g[0].dims.slice(), t = new Array(s.length), e = [];
          for (let p = 0; p < s.length; p++) t[p] = s[p] * g[1].numberData[p], e.push(`inputIdx[${p}] = int(mod(float(outputIdx[${p}]), ${s[p]}.));`);
          const r = t.length, i = `
      float process(int outputIdx[${r}]) {
        int inputIdx[${r}];
        ${e.join(`
`)}
        return _A(inputIdx);
      }
    `;
          return Object.assign(Object.assign({}, c), { output: { dims: t, type: g[0].type, textureType: l.TextureType.unpacked }, shaderSource: i });
        }, a = (f) => {
          if (!f || f.length !== 2) throw new Error("Tile requires 2 input.");
          if (f[1].dims.length !== 1) throw new Error("The second input shape must 1 dimension.");
          if (f[1].dims[0] !== f[0].dims.length) throw new Error("Invalid input shape.");
          if (u.NUMBER_TYPES.indexOf(f[0].type) === -1) throw new Error("Invalid input type.");
          if (f[1].type !== "int32" && f[1].type !== "int16") throw new Error("Invalid repeat type.");
        };
      }, 3738: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseTransposeAttributes = n.transpose = void 0;
        const u = o(246), l = o(2517), h = o(2039), a = { name: "Transpose", inputNames: ["A"], inputTypes: [h.TextureType.unpacked] };
        n.transpose = (e, r, i) => (t(r), [e.run(Object.assign(Object.assign({}, a), { cacheHint: i.cacheKey, get: () => f(e, r[0], i.perm) }), r)]), n.parseTransposeAttributes = (e) => (0, u.createAttributeWithCacheKey)({ perm: e.attributes.getInts("perm", []) });
        const f = (e, r, i) => {
          const p = r.dims;
          i = g(p, i);
          const m = c(p, i), _ = p.length, b = `
      ${s("perm", i, _)}
      float process(int indices[${_}]) {
        int a[${_}];
        perm(a, indices);
        return _A(a);
      }`;
          return Object.assign(Object.assign({}, a), { output: { dims: m, type: r.type, textureType: h.TextureType.unpacked }, shaderSource: b });
        }, g = (e, r) => (r && r.length !== e.length && (r = [...e.keys()].reverse()), r), c = (e, r) => (r = g(e, r), l.ShapeUtil.sortBasedOnPerm(e, r)), s = (e, r, i) => {
          const p = [];
          p.push(`void ${e}(out int a[${i}], int src[${i}]) {`);
          for (let m = 0; m < i; ++m) p.push(`	a[${r[m]}]=src[${m}];`);
          return p.push("	}"), p.join(`
`);
        }, t = (e) => {
          if (!e || e.length !== 1) throw new Error("Transpose requires 1 input.");
          if (e[0].type !== "float32" && e[0].type !== "float64") throw new Error("input should be float tensor");
        };
      }, 8710: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.encodeAsUint8 = void 0;
        const u = o(5060), l = o(2039);
        n.encodeAsUint8 = (h, a) => {
          const f = a.shape, g = (0, u.getGlsl)(h.session.backend.glContext.version), c = `
    const float FLOAT_MAX = 1.70141184e38;
    const float FLOAT_MIN = 1.17549435e-38;

    bool isNaN(float val) {
      return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;
    }

    highp vec4 encodeAsUint8(highp float v) {
      if (isNaN(v)) {
        return vec4(255, 255, 255, 255);
      }

      highp float av = abs(v);

      if(av < FLOAT_MIN) {
        return vec4(0.0, 0.0, 0.0, 0.0);
      } else if(v > FLOAT_MAX) {
        return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
      } else if(v < -FLOAT_MAX) {
        return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;
      }

      highp vec4 c = vec4(0,0,0,0);

      highp float e = floor(log2(av));
      highp float m = exp2(fract(log2(av))) - 1.0;

      c[2] = floor(128.0 * m);
      m -= c[2] / 128.0;
      c[1] = floor(32768.0 * m);
      m -= c[1] / 32768.0;
      c[0] = floor(8388608.0 * m);

      highp float ebias = e + 127.0;
      c[3] = floor(ebias / 2.0);
      ebias -= c[3] * 2.0;
      c[2] += floor(ebias) * 128.0;

      c[3] += 128.0 * step(0.0, -v);

      return c / 255.0;
    }

    void main() {
      float value = ${g.texture2D}(X,TexCoords).r;
      ${g.output} = encodeAsUint8(value);
    }`, s = { name: "Uint8Encode", inputTypes: [l.TextureType.unpacked], inputNames: ["X"], output: { dims: f, type: a.tensor.type, textureType: l.TextureType.downloadUint8AsFloat }, shaderSource: c, hasMain: !0 };
          return h.executeProgram(s, [a.tensor]);
        };
      }, 4909: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.tanh = n.tan = n.sqrt = n.sin = n.sigmoid = n.relu = n.not = n.neg = n.log = n.parseLeakyReluAttributes = n.leakyRelu = n.identity = n.floor = n.exp = n.parseEluAttributes = n.elu = n.cos = n.ceil = n.clipV11 = n.parseClipAttributes = n.clip = n.atan = n.asin = n.acos = n.abs = n.glslTanh = n.glslTan = n.glslSqrt = n.glslSigmoid = n.glslRelu = n.glslSin = n.glslNot = n.glslNeg = n.glslLog = n.glslLeakyRelu = n.glslIdentity = n.glslClip = n.glslFloor = n.glslExp = n.glslElu = n.glslCos = n.glslCeil = n.glslAtan = n.glslAsin = n.glslAcos = n.glslAbs = void 0;
        const u = o(246), l = o(2517), h = o(8520), a = o(5060), f = o(2039);
        function g() {
          return B("abs");
        }
        function c() {
          return B("acos");
        }
        function s() {
          return B("asin");
        }
        function t() {
          return B("atan");
        }
        function e() {
          return B("ceil");
        }
        function r() {
          return B("cos");
        }
        function i(I) {
          return { body: `
  const float alpha = float(${I});

  float elu_(float a) {
    return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
  }
  vec4 elu_(vec4 v) {
    return vec4(elu_(v.x), elu_(v.y), elu_(v.z), elu_(v.w));
  }
  `, name: "elu", type: h.FunctionType.ValueBased };
        }
        function p() {
          return B("exp");
        }
        function m() {
          return B("floor");
        }
        function _(I, $) {
          const Q = "clip";
          return { body: `
  const float min = float(${I});
  const float max = float(${$});

  float ${Q}_(float a) {
    return clamp(a, min, max);
  }
  vec4 ${Q}_(vec4 v) {
    return clamp(v, min, max);
  }
  `, name: Q, type: h.FunctionType.ValueBased };
        }
        function b() {
          const I = "indentity";
          return { body: `
  float ${I}_(float a) {
    return a;
  }
  vec4 ${I}_(vec4 v) {
    return v;
  }
  `, name: I, type: h.FunctionType.ValueBased };
        }
        function y(I) {
          const $ = "leakyRelu";
          return { body: `
  const float alpha = float(${I});

  float ${$}_(float a) {
    return a < 0.0 ? a * alpha : a;
  }
  vec4 ${$}_(vec4 v) {
    return vec4(${$}_(v.x), ${$}_(v.y), ${$}_(v.z), ${$}_(v.w));
  }
  `, name: $, type: h.FunctionType.ValueBased };
        }
        function w() {
          return B("log");
        }
        function T() {
          return { body: `
  float neg_(float a) {
    return -a;
  }
  vec4 neg_(vec4 v) {
    return -v;
  }
  `, name: "neg", type: h.FunctionType.ValueBased };
        }
        function S() {
          return { body: `
  float not_(float a) {
    return float( ! bool(a) );
  }
  bool not_(bool a) {
    return !a;
  }
  vec4 not_(vec4 v) {
    return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
  }
  bvec4 not_(bvec4 v) {
    return bvec4(!v.x, !v.y, !v.z, !v.w);
  }
  `, name: "not", type: h.FunctionType.ValueBased };
        }
        function E() {
          return B("sin");
        }
        function O() {
          const I = "relu";
          return { body: `
  float ${I}_(float a) {
    return max( a, 0.0 );
  }
  vec4 ${I}_(vec4 v) {
    return max( v, 0.0 );
  }
  `, name: I, type: h.FunctionType.ValueBased };
        }
        function v() {
          const I = "sigmoid";
          return { body: `
  float ${I}_(float a) {
    return 1.0 / (1.0 + exp(-a));
  }
  vec4 ${I}_(vec4 v) {
    return 1.0 / (1.0 + exp(-v));
  }
  `, name: I, type: h.FunctionType.ValueBased };
        }
        function A() {
          return B("sqrt");
        }
        function L() {
          return B("tan");
        }
        function j() {
          const I = "tanh";
          return { body: `
  float ${I}_(float a) {
    a = clamp(a, -10., 10.);
    a = exp(2.*a);
    return (a - 1.) / (a + 1.);
  }
  vec4 ${I}_(vec4 v) {
    v = clamp(v, -10., 10.);
    v = exp(2.*v);
    return (v - 1.) / (v + 1.);
  }
  `, name: I, type: h.FunctionType.ValueBased };
        }
        function B(I) {
          return { body: `
  float ${I}_(float a) {
    return ${I}(a);
  }
  vec4 ${I}_(vec4 v) {
    return ${I}(v);
  }
  `, name: I, type: h.FunctionType.ValueBased };
        }
        n.glslAbs = g, n.glslAcos = c, n.glslAsin = s, n.glslAtan = t, n.glslCeil = e, n.glslCos = r, n.glslElu = i, n.glslExp = p, n.glslFloor = m, n.glslClip = _, n.glslIdentity = b, n.glslLeakyRelu = y, n.glslLog = w, n.glslNeg = T, n.glslNot = S, n.glslSin = E, n.glslRelu = O, n.glslSigmoid = v, n.glslSqrt = A, n.glslTan = L, n.glslTanh = j;
        const F = (I, $, Q, Y) => {
          const te = I.session.pack ? f.TextureType.packed : f.TextureType.unpacked, ne = { name: Q.name, inputTypes: [te], inputNames: ["A"], cacheHint: Y };
          return Object.assign(Object.assign({}, ne), { get: () => ((me, Ae, Ee, ce) => {
            const ve = me.session.pack ? f.TextureType.packed : f.TextureType.unpacked, ye = (0, a.getGlsl)(me.session.backend.glContext.version);
            return Object.assign(Object.assign({}, Ae), { output: { dims: Ee.dims, type: Ee.type, textureType: ve }, shaderSource: `
     ${ce.body}
     void main() {
       vec4 v = ${ye.texture2D}(A, TexCoords);
       v = ${ce.name}_(v);
       ${ye.output} = v;
     }
     `, hasMain: !0 });
          })(I, ne, $, Q) });
        };
        n.abs = (I, $) => [I.run(F(I, $[0], g()), $)], n.acos = (I, $) => [I.run(F(I, $[0], c()), $)], n.asin = (I, $) => [I.run(F(I, $[0], s()), $)], n.atan = (I, $) => [I.run(F(I, $[0], t()), $)], n.clip = (I, $, Q) => [I.run(F(I, $[0], _(Q.min, Q.max), Q.cacheKey), $)], n.parseClipAttributes = (I) => (0, u.createAttributeWithCacheKey)({ min: I.attributes.getFloat("min", l.MIN_CLIP), max: I.attributes.getFloat("max", l.MAX_CLIP) }), n.clipV11 = (I, $) => {
          const Q = D(I, $);
          return (0, n.clip)(I, [$[0]], Q);
        };
        const D = (I, $) => {
          if ($.length >= 3 && (!I.session.isInitializer($[1].dataId) || !I.session.isInitializer($[2].dataId))) throw new Error("dynamic clip attributes are not allowed");
          const Q = $.length >= 3 ? $[1].numberData[0] : l.MIN_CLIP, Y = $.length >= 3 ? $[2].numberData[0] : l.MAX_CLIP;
          return (0, u.createAttributeWithCacheKey)({ min: Q, max: Y });
        };
        n.ceil = (I, $) => [I.run(F(I, $[0], e()), $)], n.cos = (I, $) => [I.run(F(I, $[0], r()), $)], n.elu = (I, $, Q) => [I.run(F(I, $[0], i(Q.alpha), Q.cacheKey), $)], n.parseEluAttributes = (I) => (0, u.createAttributeWithCacheKey)({ alpha: I.attributes.getFloat("alpha", 1) }), n.exp = (I, $) => [I.run(F(I, $[0], p()), $)], n.floor = (I, $) => [I.run(F(I, $[0], m()), $)], n.identity = (I, $) => [I.run(F(I, $[0], b()), $)], n.leakyRelu = (I, $, Q) => [I.run(F(I, $[0], y(Q.alpha), Q.cacheKey), $)], n.parseLeakyReluAttributes = (I) => (0, u.createAttributeWithCacheKey)({ alpha: I.attributes.getFloat("alpha", 0.01) }), n.log = (I, $) => [I.run(F(I, $[0], w()), $)], n.neg = (I, $) => [I.run(F(I, $[0], T()), $)], n.not = (I, $) => [I.run(F(I, $[0], S()), $)], n.relu = (I, $) => [I.run(F(I, $[0], O()), $)], n.sigmoid = (I, $) => [I.run(F(I, $[0], v()), $)], n.sin = (I, $) => [I.run(F(I, $[0], E()), $)], n.sqrt = (I, $) => [I.run(F(I, $[0], A()), $)], n.tan = (I, $) => [I.run(F(I, $[0], L()), $)], n.tanh = (I, $) => [I.run(F(I, $[0], j()), $)];
      }, 5611: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createUnpackProgramInfoLoader = n.createUnpackProgramInfo = void 0;
        const u = o(5060), l = o(2039), h = o(9390), a = o(2827), f = { name: "unpack", inputNames: ["A"], inputTypes: [l.TextureType.packed] };
        n.createUnpackProgramInfo = (g, c) => {
          const s = c.dims.length, t = (0, a.getChannels)("rc", s), e = t.slice(-2), r = (0, h.getCoordsDataType)(s), i = (0, a.unpackFromChannel)(), p = c.dims.length === 0 ? "" : (function(b, y) {
            if (b === 1) return "rc";
            let w = "";
            for (let T = 0; T < b; T++) w += y[T], T < b - 1 && (w += ",");
            return w;
          })(s, t), m = s <= 1 ? "rc" : `vec2(${e.join(",")})`, _ = `
    ${i}
    void main() {
      ${r} rc = getOutputCoords();

       // Sample the texture with the coords to get the rgba channel value.
       vec4 packedInput = getA(${p});

       ${(0, u.getGlsl)(g.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${m}), 0, 0, 0);
     }
   `;
          return Object.assign(Object.assign({}, f), { hasMain: !0, output: { dims: c.dims, type: c.type, textureType: l.TextureType.unpacked }, shaderSource: _ });
        }, n.createUnpackProgramInfoLoader = (g, c) => Object.assign(Object.assign({}, f), { get: () => (0, n.createUnpackProgramInfo)(g, c) });
      }, 8428: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.parseUnsqueezeAttributes = n.unsqueezeV13 = n.unsqueeze = void 0;
        const u = o(2517);
        n.unsqueeze = (a, f, g) => {
          l(f);
          const c = u.ShapeUtil.unsqueezeShape(f[0].dims, g);
          return [a.reshapeUnpacked(f[0], c)];
        }, n.unsqueezeV13 = (a, f) => (h(f), (0, n.unsqueeze)(a, [f[0]], Array.from(f[1].integerData))), n.parseUnsqueezeAttributes = (a) => a.attributes.getInts("axes");
        const l = (a) => {
          if (!a || a.length !== 1) throw new Error("Unsqueeze requires 1 input.");
          if (a[0].type === "string") throw new Error("invalid input tensor types.");
        }, h = (a) => {
          if (!a || a.length !== 2) throw new Error("Unsqueeze requires 2 inputs.");
          if (a[1].type !== "int32") throw new Error("Invalid input type.");
        };
      }, 9793: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.scalesValidation = n.validateInputs = n.parseUpsampleAttributes = n.parseUpsampleAttributesV9 = n.parseUpsampleAttributesV7 = n.upsample = void 0;
        const u = o(246), l = o(5060), h = o(2039), a = { name: "Upsample", inputNames: ["X"], inputTypes: [h.TextureType.unpacked] };
        n.upsample = (g, c, s) => ((0, n.validateInputs)(c, s), [g.run(Object.assign(Object.assign({}, a), { cacheHint: s.cacheKey, get: () => f(g, c, s) }), c)]), n.parseUpsampleAttributesV7 = (g) => (0, n.parseUpsampleAttributes)(g, 7), n.parseUpsampleAttributesV9 = (g) => (0, n.parseUpsampleAttributes)(g, 9), n.parseUpsampleAttributes = (g, c) => {
          const s = c >= 10, t = g.attributes.getString("mode", "nearest");
          if (t !== "nearest" && t !== "linear" && (c < 11 || t !== "cubic")) throw new Error(`unrecognized mode: ${t}`);
          let e = [];
          c < 9 && (e = g.attributes.getFloats("scales"), (0, n.scalesValidation)(e, t, s));
          const r = g.attributes.getFloat("extrapolation_value", 0), i = c > 10 ? g.attributes.getString("coordinate_transformation_mode", "half_pixel") : "asymmetric";
          if (["asymmetric", "pytorch_half_pixel", "tf_half_pixel_for_nn", "align_corners", "tf_crop_and_resize", "half_pixel"].indexOf(i) === -1) throw new Error(`coordinate_transform_mode '${i}' is not supported`);
          const p = i === "tf_crop_and_resize", m = p, _ = t === "nearest" && c >= 11 ? g.attributes.getString("nearest_mode", "round_prefer_floor") : "";
          if (["round_prefer_floor", "round_prefer_ceil", "floor", "ceil", ""].indexOf(_) === -1) throw new Error(`nearest_mode '${_}' is not supported`);
          const b = g.attributes.getFloat("cubic_coeff_a", -0.75), y = g.attributes.getInt("exclude_outside", 0) !== 0;
          if (y && t !== "cubic") throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");
          const w = c < 11 || t === "nearest" && i === "asymmetric" && _ === "floor";
          let T = 0, S = 0, E = 0;
          return c > 10 ? g.inputs.length > 2 ? (T = 1, S = 2, E = 3) : (S = 1, E = 2) : c === 9 && (S = 1), (0, u.createAttributeWithCacheKey)({ opset: c, isResize: s, mode: t, scales: e, extrapolationValue: r, coordinateTransformMode: i, useExtrapolation: m, needRoiInput: p, nearestMode: _, cubicCoefficientA: b, excludeOutside: y, useNearest2xOptimization: w, roiInputIdx: T, scalesInputIdx: S, sizesInputIdx: E });
        };
        const f = (g, c, s) => {
          const t = (0, l.getGlsl)(g.session.backend.glContext.version), [e, r] = g.calculateTextureWidthAndHeight(c[0].dims, h.TextureType.unpacked), i = c[0].dims.map(((E, O) => Math.floor(E * s.scales[O]))), [p, m] = g.calculateTextureWidthAndHeight(i, h.TextureType.unpacked), _ = i.length, b = new Array(_), y = new Array(_);
          let w = `
      int output_pitches[${_}];
      int input_pitches[${_}];
      `;
          for (let E = _ - 1; E >= 0; E--) b[E] = E === _ - 1 ? 1 : b[E + 1] * i[E + 1], y[E] = E === _ - 1 ? 1 : y[E + 1] * c[0].dims[E + 1], w += `
        output_pitches[${E}] = ${b[E]};
        input_pitches[${E}] = ${y[E]};
        `;
          const T = `
      float getInputFloat(int index) {
        vec2 coords = offsetToCoords(index, ${e}, ${r});
        float value = getColorAsFloat(${t.texture2D}(X, coords));
        return value;
      }
      `, S = s.mode === "nearest" ? `
    ${T}
    float process(int indices[${_}]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${p}, ${m});

      ${w}

      int d, m;
      for (int dim = 0; dim < ${_}; ++dim) {
        d = output_index / output_pitches[dim];
        m = output_index - d * output_pitches[dim];
        output_index = m;

        if (scales[dim] != 1 && d > 0) {
          int d2 = d / scales[dim];
          m = d - d2 * scales[dim];
          d = d2;
        }
        input_index += input_pitches[dim] * d;
      }

      return getInputFloat(input_index);
    }` : _ === 4 ? `
    ${T}
    float process(int indices[4]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${p}, ${m});

      ${w}

      int m;
      int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;
      index_of_dim0 = output_index / output_pitches[0];
      m = output_index - index_of_dim0 * output_pitches[0];
      index_of_dim1 = m / output_pitches[1];
      m = m - index_of_dim1 * output_pitches[1];
      index_of_dim2 = m / output_pitches[2];
      m = m - index_of_dim2 * output_pitches[2];
      index_of_dim3 = m;

      int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;
      index_of_input_dim2 = index_of_dim2 / scales[2];
      y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];
      index_of_input_dim3 = index_of_dim3 / scales[3];
      x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];

      input_index = index_of_dim0 * input_pitches[0] +
            index_of_dim1 * input_pitches[1] +
            index_of_input_dim2 * input_pitches[2] +
            index_of_input_dim3;

      float x00 = getInputFloat(input_index);
      float x10, x01, x11;

      bool end_of_dim2 = false;
      if (index_of_input_dim2 == (${c[0].dims[2]} - 1)) {
        // It's the end in dimension 2
        x01 = x00;
        end_of_dim2 = true;
      } else {
        x01 = getInputFloat(input_index + input_pitches[2]);
      }

      if (index_of_input_dim3 == (input_pitches[2] - 1)) {
        // It's the end in dimension 3
        x10 = x00;
        x11 = x01;
      }
      else {
        x10 = getInputFloat(input_index + 1);
        x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);
      }

      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);
      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);
      return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);
    }` : `
    ${T}
    float process(int indices[2]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${p}, ${m});

      ${w}

      int m;
      int index_of_dim0, index_of_dim1;
      index_of_dim0 = output_index / output_pitches[0];
      m = output_index - index_of_dim0 * output_pitches[0];
      index_of_dim1 = m;

      int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;
      index_of_input_dim0 = index_of_dim0 / scales[0];
      y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];
      index_of_input_dim1 = index_of_dim1 / scales[1];
      x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];

      input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;

      float x00 = getInputFloat(input_index);
      float x10, x01, x11;

      bool end_of_dim0 = false;
      if (index_of_input_dim0 == (${c[0].dims[0]} - 1)) {
        // It's the end in dimension 0
        x01 = x00;
        end_of_dim0 = true;
      } else {
        x01 = getInputFloat(input_index + input_pitches[0]);
      }

      if (index_of_input_dim1 == (input_pitches[0] - 1)) {
        // It's the end in dimension 1
        x10 = x00;
        x11 = x01;
      }
      else {
        x10 = getInputFloat(input_index + 1);
        x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
      }

      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
      return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
    }`;
          return Object.assign(Object.assign({}, a), { output: { dims: i, type: c[0].type, textureType: h.TextureType.unpacked }, shaderSource: S, variables: [{ name: "scales", type: "int", arrayLength: s.scales.length, data: s.scales.map(((E) => Math.ceil(E))) }] });
        };
        n.validateInputs = (g, c) => {
          if (!g || c.opset < 9 && g.length !== 1 || c.opset >= 9 && c.opset < 11 && g.length !== 2 || c.opset >= 11 && g.length < 2) throw new Error("invalid inputs.");
          if (c.scales.length > 0 && g[0].dims.length !== c.scales.length) throw new Error("Invalid input shape.");
          if (g[0].type === "string") throw new Error("Invalid input tensor types.");
        }, n.scalesValidation = (g, c, s) => {
          if (s) {
            for (const t of g) if (t <= 0) throw new Error("Scale value should be greater than 0.");
          } else for (const t of g) if (t < 1) throw new Error("Scale value should be greater than or equal to 1.");
          if (!(c !== "linear" && c !== "cubic" || g.length === 2 || g.length === 4 && g[0] === 1 && g[1] === 1)) throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic')         or 4-D inputs with the corresponding outermost 2 scale values being 1         in the ${s ? "Resize" : "Upsample"} opeartor.`);
        };
      }, 1958: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.ProgramManager = void 0;
        const u = o(1670), l = o(6231), h = o(8879), a = o(5060);
        n.ProgramManager = class {
          constructor(f, g, c) {
            this.profiler = f, this.glContext = g, this.textureLayoutStrategy = c, this.repo = /* @__PURE__ */ new Map(), this.attributesBound = !1;
          }
          getArtifact(f) {
            return this.repo.get(f);
          }
          setArtifact(f, g) {
            this.repo.set(f, g);
          }
          run(f, g, c) {
            var s;
            this.profiler.event("op", `ProgramManager.run ${(s = f.programInfo.name) !== null && s !== void 0 ? s : "unknown kernel"}`, (() => {
              var t;
              const e = this.glContext.gl, r = f.program;
              e.useProgram(r);
              try {
                this.bindOutput(c), this.attributesBound || this.bindAttributes(f.attribLocations), this.bindUniforms(f.uniformLocations, (t = f.programInfo.variables) !== null && t !== void 0 ? t : [], g);
              } catch (i) {
                throw l.Logger.error("ProgramManager", f.programInfo.shaderSource), i;
              }
              this.profiler.event("backend", "GlContext.draw()", (() => {
                this.glContext.draw();
              }));
            }), this.glContext);
          }
          dispose() {
            this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach(((f) => this.glContext.deleteProgram(f.program)));
          }
          build(f, g, c) {
            return this.profiler.event("backend", "ProgramManager.build", (() => {
              const s = new h.GlslPreprocessor(this.glContext, f, g, c), t = s.preprocess(), e = this.compile(t);
              return { programInfo: f, program: e, uniformLocations: this.getUniformLocations(e, s.context.programInfo.inputNames, s.context.programInfo.variables), attribLocations: this.getAttribLocations(e) };
            }));
          }
          compile(f) {
            if (!this.vertexShader) {
              l.Logger.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time");
              const s = (0, a.getVertexShaderSource)(this.glContext.version);
              this.vertexShader = this.glContext.compileShader(s, this.glContext.gl.VERTEX_SHADER);
            }
            u.env.debug && l.Logger.verbose("ProrgramManager", `FragShader:
${f}
`);
            const g = this.glContext.compileShader(f, this.glContext.gl.FRAGMENT_SHADER), c = this.glContext.createProgram(this.vertexShader, g);
            return this.glContext.deleteShader(g), c;
          }
          bindOutput(f) {
            const g = f.width, c = f.height;
            l.Logger.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${g}/${c}, shape=${f.shape}, type=${f.tensor.type}`), this.glContext.attachFramebuffer(f.texture, g, c);
          }
          bindAttributes(f) {
            const g = f.position, c = f.textureCoord;
            this.glContext.setVertexAttributes(g, c), this.attributesBound = !0;
          }
          bindUniforms(f, g, c) {
            var s;
            const t = this.glContext.gl;
            let e = 0;
            for (const { name: r, type: i, location: p, arrayLength: m } of f) {
              const _ = (s = g.find(((b) => b.name === r))) === null || s === void 0 ? void 0 : s.data;
              if (i !== "sampler2D" && !_) throw new Error(`variable '${r}' does not have data defined in program info`);
              switch (i) {
                case "sampler2D":
                  this.bindTexture(c[e], p, e), e++;
                  break;
                case "float":
                  m ? t.uniform1fv(p, _) : t.uniform1f(p, _);
                  break;
                case "int":
                  m ? t.uniform1iv(p, _) : t.uniform1i(p, _);
                  break;
                default:
                  throw new Error(`Uniform not implemented: ${i}`);
              }
            }
          }
          bindTexture(f, g, c) {
            this.glContext.bindTextureToUniform(f.texture, c, g);
          }
          getAttribLocations(f) {
            return { position: this.getAttribLocation(f, "position"), textureCoord: this.getAttribLocation(f, "textureCoord") };
          }
          getUniformLocations(f, g, c) {
            const s = [];
            if (g) for (const t of g) s.push({ name: t, type: "sampler2D", location: this.getUniformLocation(f, t) });
            if (c) for (const t of c) s.push(Object.assign(Object.assign({}, t), { location: this.getUniformLocation(f, t.name) }));
            return s;
          }
          getUniformLocation(f, g) {
            const c = this.glContext.gl.getUniformLocation(f, g);
            if (c === null) throw new Error(`Uniform ${g} not found.`);
            return c;
          }
          getAttribLocation(f, g) {
            return this.glContext.gl.getAttribLocation(f, g);
          }
        };
      }, 6416: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.WebGLSessionHandler = void 0;
        const u = o(6231), l = o(1047), h = o(8316), a = o(1640), f = o(1958), g = o(7859), c = o(5702);
        n.WebGLSessionHandler = class {
          constructor(s, t) {
            this.backend = s, this.context = t, this.layoutStrategy = new g.PreferLogicalStrategy(s.glContext.maxTextureSize), this.programManager = new f.ProgramManager(this.context.profiler, s.glContext, this.layoutStrategy), this.textureManager = new c.TextureManager(s.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: s.textureCacheMode === "full" }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = s.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map();
          }
          createInferenceHandler() {
            return new h.WebGLInferenceHandler(this);
          }
          onGraphInitialized(s) {
            const t = s.getValues().filter(((e) => e.from === -1 && e.tensor)).map(((e) => e.tensor.dataId));
            this.initializers = new Set(t);
          }
          isInitializer(s) {
            return !!this.initializers && this.initializers.has(s);
          }
          addInitializer(s) {
            this.initializers.add(s);
          }
          getTextureData(s, t) {
            return t ? this.packedTextureDataCache.get(s) : this.unpackedTextureDataCache.get(s);
          }
          setTextureData(s, t, e = !1) {
            u.Logger.verbose("WebGLSessionHandler", "Storing Texture data in cache"), e ? this.packedTextureDataCache.set(s, t) : this.unpackedTextureDataCache.set(s, t);
          }
          dispose() {
            this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach(((s) => this.textureManager.releaseTexture(s, !0))), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach(((s) => this.textureManager.releaseTexture(s, !0))), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
          }
          resolve(s, t, e) {
            const r = (0, l.resolveOperator)(s, t, a.WEBGL_OP_RESOLVE_RULES);
            return { impl: r.opImpl, context: r.opInit ? r.opInit(s, e) : s };
          }
        };
      }, 7769: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.Uint8DataEncoder = n.RGBAFloatDataEncoder = n.RedFloat32DataEncoder = void 0;
        const u = o(6231);
        n.RedFloat32DataEncoder = class {
          constructor(l, h = 1) {
            if (h === 1) this.internalFormat = l.R32F, this.format = l.RED, this.textureType = l.FLOAT, this.channelSize = h;
            else {
              if (h !== 4) throw new Error(`Invalid number of channels: ${h}`);
              this.internalFormat = l.RGBA32F, this.format = l.RGBA, this.textureType = l.FLOAT, this.channelSize = h;
            }
          }
          encode(l, h) {
            let a, f;
            return l.constructor !== Float32Array && (u.Logger.warning("Encoder", "data was not of type Float32; creating new Float32Array"), f = new Float32Array(l)), h * this.channelSize > l.length ? (u.Logger.warning("Encoder", "Source data too small. Allocating larger array"), f = l, a = this.allocate(h * this.channelSize), f.forEach(((g, c) => a[c] = g))) : (f = l, a = f), a;
          }
          allocate(l) {
            return new Float32Array(4 * l);
          }
          decode(l, h) {
            return this.channelSize === 1 ? l.filter(((a, f) => f % 4 == 0)).subarray(0, h) : l.subarray(0, h);
          }
        }, n.RGBAFloatDataEncoder = class {
          constructor(l, h = 1, a) {
            if (h !== 1 && h !== 4) throw new Error(`Invalid number of channels: ${h}`);
            this.internalFormat = l.RGBA, this.format = l.RGBA, this.channelSize = h, this.textureType = a || l.FLOAT;
          }
          encode(l, h) {
            let a = l;
            return this.channelSize === 1 && (u.Logger.verbose("Encoder", "Exploding into a larger array"), a = this.allocate(h), l.forEach(((f, g) => a[4 * g] = f))), a;
          }
          allocate(l) {
            return new Float32Array(4 * l);
          }
          decode(l, h) {
            return this.channelSize === 1 ? l.filter(((a, f) => f % 4 == 0)).subarray(0, h) : l.subarray(0, h);
          }
        }, n.Uint8DataEncoder = class {
          constructor(l, h = 1) {
            if (this.channelSize = 4, h === 1) this.internalFormat = l.ALPHA, this.format = l.ALPHA, this.textureType = l.UNSIGNED_BYTE, this.channelSize = h;
            else {
              if (h !== 4) throw new Error(`Invalid number of channels: ${h}`);
              this.internalFormat = l.RGBA, this.format = l.RGBA, this.textureType = l.UNSIGNED_BYTE, this.channelSize = h;
            }
          }
          encode(l, h) {
            return new Uint8Array(l.buffer, l.byteOffset, l.byteLength);
          }
          allocate(l) {
            return new Uint8Array(l * this.channelSize);
          }
          decode(l, h) {
            if (l instanceof Uint8Array) return l.subarray(0, h);
            throw new Error(`Invalid array type: ${l.constructor}`);
          }
        };
      }, 7859: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.getBatchDim = n.sizeToSquarishShape = n.getRowsCols = n.sizeFromShape = n.isInt = n.parseAxisParam = n.squeezeShape = n.PreferLogicalStrategy = n.AlwaysKeepOriginalSizeStrategy = void 0;
        const u = o(6231), l = o(2517);
        function h(s, t) {
          const e = [], r = [], i = t != null && Array.isArray(t) && t.length === 0, p = t == null || i ? null : a(t, s).sort();
          let m = 0;
          for (let _ = 0; _ < s.length; ++_) {
            if (p != null) {
              if (p[m] === _ && s[_] !== 1) throw new Error(`Can't squeeze axis ${_} since its dim '${s[_]}' is not 1`);
              (p[m] == null || p[m] > _) && s[_] === 1 && (e.push(s[_]), r.push(_)), p[m] <= _ && m++;
            }
            s[_] !== 1 && (e.push(s[_]), r.push(_));
          }
          return { newShape: e, keptDims: r };
        }
        function a(s, t) {
          const e = t.length;
          return s = s == null ? t.map(((r, i) => i)) : [].concat(s), (0, l.assert)(s.every(((r) => r >= -e && r < e)), (() => `All values in axis param must be in range [-${e}, ${e}) but got axis ${s}`)), (0, l.assert)(s.every(f), (() => `All values in axis param must be integers but got axis ${s}`)), s.map(((r) => r < 0 ? e + r : r));
        }
        function f(s) {
          return s % 1 == 0;
        }
        function g(s) {
          if (s.length === 0) return 1;
          let t = s[0];
          for (let e = 1; e < s.length; e++) t *= s[e];
          return t;
        }
        function c(s) {
          const t = Math.ceil(Math.sqrt(s));
          return [t, Math.ceil(s / t)];
        }
        n.AlwaysKeepOriginalSizeStrategy = class {
          constructor(s) {
            this.maxTextureSize = s;
          }
          computeTextureWH(s, t) {
            if (s.length === 0) return [1, 1];
            const e = this.maxTextureSize;
            if (t && t.breakAxis !== void 0) {
              const p = t.breakAxis >= s.length ? 1 : s.slice(t.breakAxis).reduce(((_, b) => _ * b)), m = t.breakAxis <= 0 ? 1 : s.slice(0, t.breakAxis).reduce(((_, b) => _ * b));
              if (!(p > e || m > e)) return [p, m];
              u.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${s}, breakAxis:${t.breakAxis}`);
            }
            const r = s.reduce(((p, m) => p * m));
            let i = Math.floor(Math.sqrt(r));
            for (; i < e && i < r && r % i != 0; i++) ;
            if (i >= e || r % i != 0) throw new Error(`The given dimensions are outside this GPU's boundaries: ${s}`);
            return [i, r / i];
          }
        }, n.PreferLogicalStrategy = class {
          constructor(s) {
            this.maxTextureSize = s;
          }
          computeTextureWH(s, t) {
            const e = this.computeTexture(s, t);
            return t && t.isPacked && (e[0] /= 2, e[1] /= 2), t && t.reverseWH ? [e[1], e[0]] : e;
          }
          computeTexture(s, t) {
            const e = t && t.isPacked;
            if (s.length === 0) return e ? [2, 2] : [1, 1];
            let r = this.maxTextureSize;
            if (t && t.breakAxis !== void 0) {
              const m = t.breakAxis >= s.length ? 1 : s.slice(t.breakAxis).reduce(((b, y) => b * y)), _ = t.breakAxis <= 0 ? 1 : s.slice(0, t.breakAxis).reduce(((b, y) => b * y));
              if (!(m > r || _ > r)) return [m, _];
              u.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${s}, breakAxis:${t.breakAxis}`);
            }
            let i = s.slice(0);
            e && (r *= 2, i = i.map(((m, _) => _ >= i.length - 2 ? i[_] % 2 == 0 ? i[_] : i[_] + 1 : i[_])), i.length === 1 && (i = [2, i[0]])), i.length !== 2 && (i = h(i).newShape);
            const p = g(i);
            return i.length <= 1 && p <= r ? [1, p] : i.length === 2 && i[0] <= r && i[1] <= r ? i : i.length === 3 && i[0] * i[1] <= r && i[2] <= r ? [i[0] * i[1], i[2]] : i.length === 3 && i[0] <= r && i[1] * i[2] <= r ? [i[0], i[1] * i[2]] : i.length === 4 && i[0] * i[1] * i[2] <= r && i[3] <= r ? [i[0] * i[1] * i[2], i[3]] : i.length === 4 && i[0] <= r && i[1] * i[2] * i[3] <= r ? [i[0], i[1] * i[2] * i[3]] : e ? c(p / 4).map(((m) => 2 * m)) : c(p);
          }
        }, n.squeezeShape = h, n.parseAxisParam = a, n.isInt = f, n.sizeFromShape = g, n.getRowsCols = function(s) {
          if (s.length === 0) throw Error("Cannot get rows and columns of an empty shape array.");
          return [s.length > 1 ? s[s.length - 2] : 1, s[s.length - 1]];
        }, n.sizeToSquarishShape = c, n.getBatchDim = function(s, t = 2) {
          return g(s.slice(0, s.length - t));
        };
      }, 4057: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createTextureLayoutFromShape = n.calculateTextureWidthAndHeight = n.createTextureLayoutFromTextureType = void 0;
        const u = o(2517), l = o(2039);
        n.createTextureLayoutFromTextureType = (h, a, f) => {
          const g = f === l.TextureType.unpacked || f === l.TextureType.unpackedReversed ? 1 : 4, c = f === l.TextureType.packed, s = f === l.TextureType.unpackedReversed || f === l.TextureType.packed, t = f === l.TextureType.packedLastDimension ? a.length - 1 : void 0, e = f === l.TextureType.packedLastDimension ? a.map(((r, i) => i === a.length - 1 ? 4 * r : r)) : void 0;
          return (0, n.createTextureLayoutFromShape)(h, a, g, e, { isPacked: c, reverseWH: s, breakAxis: t });
        }, n.calculateTextureWidthAndHeight = (h, a, f) => {
          const g = (0, n.createTextureLayoutFromTextureType)(h, a, f);
          return [g.width, g.height];
        }, n.createTextureLayoutFromShape = (h, a, f = 1, g, c) => {
          const s = !(!c || !c.isPacked), [t, e] = h.computeTextureWH(s && g || a, c), r = a.length;
          let i = a.slice(0);
          if (r === 0 && (i = [1]), f === 1) g = a;
          else if (s) {
            if (f !== 4) throw new Error("a packed texture must be 4-channel");
            g = a, r > 0 && (i[r - 1] = Math.ceil(i[r - 1] / 2)), r > 1 && (i[r - 2] = Math.ceil(i[r - 2] / 2));
          } else if (!g) throw new Error("Unpacked shape is needed when using channels > 1");
          return { width: t, height: e, channels: f, isPacked: s, shape: i, strides: u.ShapeUtil.computeStrides(i), unpackedShape: g, reversedWH: c && c.reverseWH };
        };
      }, 5702: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.TextureManager = void 0;
        const u = o(6231);
        n.TextureManager = class {
          constructor(l, h, a, f) {
            this.glContext = l, this.layoutStrategy = h, this.profiler = a, this.config = f, this.pendingRead = /* @__PURE__ */ new Map(), f.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map());
          }
          createTextureFromLayout(l, h, a, f) {
            const g = this.toEncoderType(l), c = this.glContext.getEncoder(g, h.channels || 1, f);
            if (h.isPacked && f === 1) throw new Error("not implemented");
            const s = h.width, t = h.height;
            let e, r;
            if (this.config.reuseTextures) {
              e = `${s}x${t}_${c.format}_${c.internalFormat}_${c.textureType}`, r = this.inUseTextures.get(e), r || (r = [], this.inUseTextures.set(e, r));
              const p = this.idleTextures.get(e);
              if (p && p.length > 0) {
                const m = p.pop();
                return r.push(m), f === 1 && this.glContext.updateTexture(m, s, t, c, this.toTextureData(l, a)), m;
              }
            }
            u.Logger.verbose("TextureManager", `Creating new texture of size ${h.width}x${h.height}`);
            const i = this.glContext.allocateTexture(s, t, c, this.toTextureData(l, a));
            return this.config.reuseTextures && (r.push(i), this.textureLookup.set(i, e)), i;
          }
          readTexture(l, h, a) {
            return a || (a = 1), this.profiler.event("backend", "TextureManager.readTexture", (() => {
              const f = l.shape.reduce(((c, s) => c * s)) * a, g = this.glContext.readTexture(l.texture, l.width, l.height, f, this.toEncoderType(h), a);
              return this.toTensorData(h, g);
            }));
          }
          async readTextureAsync(l, h, a) {
            const f = l.tensor.dataId;
            if (a || (a = 1), this.pendingRead.has(f)) {
              const g = this.pendingRead.get(f);
              return new Promise(((c) => g?.push(c)));
            }
            return this.profiler.event("backend", "TextureManager.readTextureAsync", (async () => {
              this.pendingRead.set(f, []);
              const g = l.shape.reduce(((e, r) => e * r)) * a;
              await this.glContext.createAndWaitForFence();
              const c = this.glContext.readTexture(l.texture, l.width, l.height, g, this.toEncoderType(h), a), s = this.toTensorData(h, c), t = this.pendingRead.get(f);
              return this.pendingRead.delete(f), t?.forEach(((e) => e(s))), s;
            }));
          }
          readUint8TextureAsFloat(l) {
            return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", (() => {
              const h = l.shape.reduce(((f, g) => f * g)), a = this.glContext.readTexture(l.texture, l.width, l.height, 4 * h, "byte", 4);
              return new Float32Array(a.buffer, a.byteOffset, h);
            }));
          }
          releaseTexture(l, h) {
            let a;
            if (this.config.reuseTextures && (a = this.textureLookup.get(l.texture), a)) {
              h && this.textureLookup.delete(a);
              const f = this.inUseTextures.get(a);
              if (f) {
                const g = f.indexOf(l.texture);
                if (g !== -1) {
                  f.splice(g, 1);
                  let c = this.idleTextures.get(a);
                  c || (c = [], this.idleTextures.set(a, c)), c.push(l.texture);
                }
              }
            }
            a && !h || (u.Logger.verbose("TextureManager", `Deleting texture of size ${l.width}x${l.height}`), this.glContext.deleteTexture(l.texture));
          }
          toTensorData(l, h) {
            switch (l) {
              case "int16":
                return h instanceof Int16Array ? h : Int16Array.from(h);
              case "int32":
                return h instanceof Int32Array ? h : Int32Array.from(h);
              case "int8":
                return h instanceof Int8Array ? h : Int8Array.from(h);
              case "uint16":
                return h instanceof Uint16Array ? h : Uint16Array.from(h);
              case "uint32":
                return h instanceof Uint32Array ? h : Uint32Array.from(h);
              case "uint8":
              case "bool":
                return h instanceof Uint8Array ? h : Uint8Array.from(h);
              case "float32":
                return h instanceof Float32Array ? h : Float32Array.from(h);
              case "float64":
                return h instanceof Float64Array ? h : Float64Array.from(h);
              default:
                throw new Error(`TensorData type ${l} is not supported`);
            }
          }
          toTextureData(l, h) {
            if (h) return h instanceof Float32Array ? h : new Float32Array(h);
          }
          toEncoderType(l) {
            return "float";
          }
          clearActiveTextures() {
            this.glContext.clearActiveTextures();
          }
        };
      }, 2039: (d, n) => {
        var o;
        Object.defineProperty(n, "__esModule", { value: !0 }), n.TextureType = void 0, (o = n.TextureType || (n.TextureType = {}))[o.unpacked = 0] = "unpacked", o[o.unpackedReversed = 1] = "unpackedReversed", o[o.packed = 2] = "packed", o[o.downloadUint8AsFloat = 3] = "downloadUint8AsFloat", o[o.packedLastDimension = 4] = "packedLastDimension";
      }, 9390: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.getGlChannels = n.getCoordsDataType = n.getSqueezedParams = n.squeezeInputShape = n.generateShaderFuncNameFromInputSamplerNameAtOutCoords = n.generateShaderFuncNameFromInputSamplerName = n.repeatedTry = n.getPackedShape = void 0;
        const u = o(2517);
        n.getPackedShape = function(l) {
          const h = l.length;
          return l.slice(0, h - 1).concat(l[h - 1] / 4);
        }, n.repeatedTry = async function(l, h = ((f) => 0), a) {
          return new Promise(((f, g) => {
            let c = 0;
            const s = () => {
              if (l()) return void f();
              c++;
              const t = h(c);
              a != null && c >= a ? g() : setTimeout(s, t);
            };
            s();
          }));
        }, n.generateShaderFuncNameFromInputSamplerName = function(l) {
          return (0, u.assert)(l !== void 0 && l.length !== 0, (() => "empty string found for sampler name")), "get" + l.charAt(0).toUpperCase() + l.slice(1);
        }, n.generateShaderFuncNameFromInputSamplerNameAtOutCoords = function(l) {
          return (0, u.assert)(l !== void 0 && l.length !== 0, (() => "empty string found for sampler name")), "get" + l.charAt(0).toUpperCase() + l.slice(1) + "AtOutCoords";
        }, n.squeezeInputShape = function(l, h) {
          let a = JSON.parse(JSON.stringify(l));
          return a = h, a;
        }, n.getSqueezedParams = function(l, h) {
          return h.map(((a) => l[a])).join(", ");
        }, n.getCoordsDataType = function(l) {
          if (l <= 1) return "int";
          if (l === 2) return "ivec2";
          if (l === 3) return "ivec3";
          if (l === 4) return "ivec4";
          if (l === 5) return "ivec5";
          if (l === 6) return "ivec6";
          throw Error(`GPU for rank ${l} is not yet supported`);
        }, n.getGlChannels = function(l = 6) {
          return ["x", "y", "z", "w", "u", "v"].slice(0, l);
        };
      }, 7305: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.createNewWebGLContext = n.createWebGLContext = void 0;
        const u = o(6231), l = o(1713), h = {};
        function a(f) {
          const g = (function() {
            if (typeof document > "u") {
              if (typeof OffscreenCanvas > "u") throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");
              return new OffscreenCanvas(1, 1);
            }
            const t = document.createElement("canvas");
            return t.width = 1, t.height = 1, t;
          })();
          let c;
          const s = { alpha: !1, depth: !1, antialias: !1, stencil: !1, preserveDrawingBuffer: !1, premultipliedAlpha: !1, failIfMajorPerformanceCaveat: !1 };
          if ((!f || f === "webgl2") && (c = g.getContext("webgl2", s), c)) try {
            return new l.WebGLContext(c, 2);
          } catch (t) {
            u.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`);
          }
          if ((!f || f === "webgl") && (c = g.getContext("webgl", s) || g.getContext("experimental-webgl", s), c)) try {
            return new l.WebGLContext(c, 1);
          } catch (t) {
            u.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`);
          }
          throw new Error("WebGL is not supported");
        }
        n.createWebGLContext = function f(g) {
          let c;
          g && g !== "webgl2" || !("webgl2" in h) ? g && g !== "webgl" || !("webgl" in h) || (c = h.webgl) : c = h.webgl2, c = c || a(g), g = g || c.version === 1 ? "webgl" : "webgl2";
          const s = c.gl;
          return h[g] = c, s.isContextLost() ? (delete h[g], f(g)) : (s.disable(s.DEPTH_TEST), s.disable(s.STENCIL_TEST), s.disable(s.BLEND), s.disable(s.DITHER), s.disable(s.POLYGON_OFFSET_FILL), s.disable(s.SAMPLE_COVERAGE), s.enable(s.SCISSOR_TEST), s.enable(s.CULL_FACE), s.cullFace(s.BACK), c);
        }, n.createNewWebGLContext = a;
      }, 1713: function(d, n, o) {
        var u = this && this.__createBinding || (Object.create ? function(s, t, e, r) {
          r === void 0 && (r = e);
          var i = Object.getOwnPropertyDescriptor(t, e);
          i && !("get" in i ? !t.__esModule : i.writable || i.configurable) || (i = { enumerable: !0, get: function() {
            return t[e];
          } }), Object.defineProperty(s, r, i);
        } : function(s, t, e, r) {
          r === void 0 && (r = e), s[r] = t[e];
        }), l = this && this.__setModuleDefault || (Object.create ? function(s, t) {
          Object.defineProperty(s, "default", { enumerable: !0, value: t });
        } : function(s, t) {
          s.default = t;
        }), h = this && this.__importStar || function(s) {
          if (s && s.__esModule) return s;
          var t = {};
          if (s != null) for (var e in s) e !== "default" && Object.prototype.hasOwnProperty.call(s, e) && u(t, s, e);
          return l(t, s), t;
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), n.WebGLContext = n.linearSearchLastTrue = void 0;
        const a = o(1670), f = h(o(7769)), g = o(9390);
        function c(s) {
          let t = 0;
          for (; t < s.length && s[t](); ++t) ;
          return t - 1;
        }
        n.linearSearchLastTrue = c, n.WebGLContext = class {
          constructor(s, t) {
            this.frameBufferBound = !1, this.itemsToPoll = [], this.gl = s, this.version = t, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters();
          }
          allocateTexture(s, t, e, r) {
            const i = this.gl, p = i.createTexture();
            i.bindTexture(i.TEXTURE_2D, p), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_MIN_FILTER, i.NEAREST), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_MAG_FILTER, i.NEAREST), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_WRAP_S, i.CLAMP_TO_EDGE), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_WRAP_T, i.CLAMP_TO_EDGE);
            const m = r ? e.encode(r, s * t) : null;
            return i.texImage2D(i.TEXTURE_2D, 0, e.internalFormat, s, t, 0, e.format, e.textureType, m), this.checkError(), p;
          }
          updateTexture(s, t, e, r, i) {
            const p = this.gl;
            p.bindTexture(p.TEXTURE_2D, s);
            const m = r.encode(i, t * e);
            p.texSubImage2D(p.TEXTURE_2D, 0, 0, 0, t, e, r.format, r.textureType, m), this.checkError();
          }
          attachFramebuffer(s, t, e) {
            const r = this.gl;
            r.bindTexture(r.TEXTURE_2D, s), r.bindFramebuffer(r.FRAMEBUFFER, this.framebuffer), r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, s, 0), this.checkError(), r.viewport(0, 0, t, e), r.scissor(0, 0, t, e);
          }
          readTexture(s, t, e, r, i, p) {
            const m = this.gl;
            p || (p = 1), this.frameBufferBound || this.attachFramebuffer(s, t, e);
            const _ = this.getEncoder(i, p), b = _.allocate(t * e);
            return m.bindTexture(m.TEXTURE_2D, s), m.framebufferTexture2D(m.FRAMEBUFFER, m.COLOR_ATTACHMENT0, m.TEXTURE_2D, s, 0), m.readPixels(0, 0, t, e, m.RGBA, _.textureType, b), this.checkError(), _.decode(b, r);
          }
          isFramebufferReady() {
            return !0;
          }
          getActiveTexture() {
            const s = this.gl;
            return "TEXTURE" + (s.getParameter(this.gl.ACTIVE_TEXTURE) - s.TEXTURE0);
          }
          getTextureBinding() {
            return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D);
          }
          getFramebufferBinding() {
            return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING);
          }
          setVertexAttributes(s, t) {
            const e = this.gl;
            e.vertexAttribPointer(s, 3, e.FLOAT, !1, 20, 0), e.enableVertexAttribArray(s), t !== -1 && (e.vertexAttribPointer(t, 2, e.FLOAT, !1, 20, 12), e.enableVertexAttribArray(t)), this.checkError();
          }
          createProgram(s, t) {
            const e = this.gl, r = e.createProgram();
            return e.attachShader(r, s), e.attachShader(r, t), e.linkProgram(r), r;
          }
          compileShader(s, t) {
            const e = this.gl, r = e.createShader(t);
            if (!r) throw new Error(`createShader() returned null with type ${t}`);
            if (e.shaderSource(r, s), e.compileShader(r), e.getShaderParameter(r, e.COMPILE_STATUS) === !1) throw new Error(`Failed to compile shader: ${e.getShaderInfoLog(r)}
Shader source:
${s}`);
            return r;
          }
          deleteShader(s) {
            this.gl.deleteShader(s);
          }
          bindTextureToUniform(s, t, e) {
            const r = this.gl;
            r.activeTexture(r.TEXTURE0 + t), this.checkError(), r.bindTexture(r.TEXTURE_2D, s), this.checkError(), r.uniform1i(e, t), this.checkError();
          }
          draw() {
            this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError();
          }
          checkError() {
            if (a.env.debug) {
              const s = this.gl, t = s.getError();
              let e = "";
              switch (t) {
                case s.NO_ERROR:
                  return;
                case s.INVALID_ENUM:
                  e = "INVALID_ENUM";
                  break;
                case s.INVALID_VALUE:
                  e = "INVALID_VALUE";
                  break;
                case s.INVALID_OPERATION:
                  e = "INVALID_OPERATION";
                  break;
                case s.INVALID_FRAMEBUFFER_OPERATION:
                  e = "INVALID_FRAMEBUFFER_OPERATION";
                  break;
                case s.OUT_OF_MEMORY:
                  e = "OUT_OF_MEMORY";
                  break;
                case s.CONTEXT_LOST_WEBGL:
                  e = "CONTEXT_LOST_WEBGL";
                  break;
                default:
                  e = `Unknown WebGL Error: ${t.toString(16)}`;
              }
              throw new Error(e);
            }
          }
          deleteTexture(s) {
            this.gl.deleteTexture(s);
          }
          deleteProgram(s) {
            this.gl.deleteProgram(s);
          }
          getEncoder(s, t, e = 0) {
            if (this.version === 2) return new f.RedFloat32DataEncoder(this.gl, t);
            switch (s) {
              case "float":
                return e === 1 || this.isRenderFloat32Supported ? new f.RGBAFloatDataEncoder(this.gl, t) : new f.RGBAFloatDataEncoder(this.gl, t, this.textureHalfFloatExtension.HALF_FLOAT_OES);
              case "int":
                throw new Error("not implemented");
              case "byte":
                return new f.Uint8DataEncoder(this.gl, t);
              default:
                throw new Error(`Invalid dataType: ${s}`);
            }
          }
          clearActiveTextures() {
            const s = this.gl;
            for (let t = 0; t < this.maxTextureImageUnits; ++t) s.activeTexture(s.TEXTURE0 + t), s.bindTexture(s.TEXTURE_2D, null);
          }
          dispose() {
            if (this.disposed) return;
            const s = this.gl;
            s.bindFramebuffer(s.FRAMEBUFFER, null), s.deleteFramebuffer(this.framebuffer), s.bindBuffer(s.ARRAY_BUFFER, null), s.deleteBuffer(this.vertexbuffer), s.bindBuffer(s.ELEMENT_ARRAY_BUFFER, null), s.finish(), this.disposed = !0;
          }
          createDefaultGeometry() {
            return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
          }
          createVertexbuffer() {
            const s = this.gl, t = s.createBuffer();
            if (!t) throw new Error("createBuffer() returned null");
            const e = this.createDefaultGeometry();
            return s.bindBuffer(s.ARRAY_BUFFER, t), s.bufferData(s.ARRAY_BUFFER, e, s.STATIC_DRAW), this.checkError(), t;
          }
          createFramebuffer() {
            const s = this.gl.createFramebuffer();
            if (!s) throw new Error("createFramebuffer returned null");
            return s;
          }
          queryVitalParameters() {
            const s = this.gl;
            if (this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(), this.isRenderFloat32Supported = this.checkRenderFloat32(), this.isFloat32DownloadSupported = this.checkFloat32Download(), this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) throw new Error("both float32 and float16 TextureType are not supported");
            this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(), this.maxTextureSize = s.getParameter(s.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS), this.version;
          }
          getExtensions() {
            this.version === 2 ? (this.colorBufferFloatExtension = this.gl.getExtension("EXT_color_buffer_float"), this.disjointTimerQueryWebgl2Extension = this.gl.getExtension("EXT_disjoint_timer_query_webgl2")) : (this.textureFloatExtension = this.gl.getExtension("OES_texture_float"), this.textureHalfFloatExtension = this.gl.getExtension("OES_texture_half_float"));
          }
          checkFloatTextureAttachableToFrameBuffer() {
            const s = this.gl, t = s.createTexture();
            s.bindTexture(s.TEXTURE_2D, t);
            const e = this.version === 2 ? s.RGBA32F : s.RGBA;
            s.texImage2D(s.TEXTURE_2D, 0, e, 1, 1, 0, s.RGBA, s.FLOAT, null);
            const r = s.createFramebuffer();
            s.bindFramebuffer(s.FRAMEBUFFER, r), s.framebufferTexture2D(s.FRAMEBUFFER, s.COLOR_ATTACHMENT0, s.TEXTURE_2D, t, 0);
            const i = s.checkFramebufferStatus(s.FRAMEBUFFER) === s.FRAMEBUFFER_COMPLETE;
            return s.bindTexture(s.TEXTURE_2D, null), s.bindFramebuffer(s.FRAMEBUFFER, null), s.deleteTexture(t), s.deleteFramebuffer(r), i;
          }
          checkRenderFloat32() {
            if (this.version === 2) {
              if (!this.colorBufferFloatExtension) return !1;
            } else if (!this.textureFloatExtension) return !1;
            return this.isFloatTextureAttachableToFrameBuffer;
          }
          checkFloat32Download() {
            if (this.version === 2) {
              if (!this.colorBufferFloatExtension) return !1;
            } else if (!this.textureFloatExtension || !this.gl.getExtension("WEBGL_color_buffer_float")) return !1;
            return this.isFloatTextureAttachableToFrameBuffer;
          }
          checkFloat32Blend() {
            const s = this.gl;
            let t, e, r, i, p;
            try {
              t = s.createTexture(), e = s.createFramebuffer(), s.bindTexture(s.TEXTURE_2D, t);
              const m = this.version === 2 ? s.RGBA32F : s.RGBA;
              return s.texImage2D(s.TEXTURE_2D, 0, m, 1, 1, 0, s.RGBA, s.FLOAT, null), s.bindFramebuffer(s.FRAMEBUFFER, e), s.framebufferTexture2D(s.FRAMEBUFFER, s.COLOR_ATTACHMENT0, s.TEXTURE_2D, t, 0), s.enable(s.BLEND), r = s.createShader(s.VERTEX_SHADER), !!r && (s.shaderSource(r, "void main(){}"), s.compileShader(r), i = s.createShader(s.FRAGMENT_SHADER), !!i && (s.shaderSource(i, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), s.compileShader(i), p = s.createProgram(), !!p && (s.attachShader(p, r), s.attachShader(p, i), s.linkProgram(p), s.useProgram(p), s.drawArrays(s.POINTS, 0, 1), s.getError() === s.NO_ERROR)));
            } finally {
              s.disable(s.BLEND), p && s.deleteProgram(p), r && s.deleteShader(r), i && s.deleteShader(i), e && (s.bindFramebuffer(s.FRAMEBUFFER, null), s.deleteFramebuffer(e)), t && (s.bindTexture(s.TEXTURE_2D, null), s.deleteTexture(t));
            }
          }
          beginTimer() {
            if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
              const s = this.gl, t = this.disjointTimerQueryWebgl2Extension, e = s.createQuery();
              return s.beginQuery(t.TIME_ELAPSED_EXT, e), e;
            }
            throw new Error("WebGL1 profiling currently not supported.");
          }
          endTimer() {
            if (this.version !== 2 || !this.disjointTimerQueryWebgl2Extension) throw new Error("WebGL1 profiling currently not supported");
            {
              const s = this.gl, t = this.disjointTimerQueryWebgl2Extension;
              s.endQuery(t.TIME_ELAPSED_EXT);
            }
          }
          isTimerResultAvailable(s) {
            let t = !1, e = !1;
            if (this.version !== 2 || !this.disjointTimerQueryWebgl2Extension) throw new Error("WebGL1 profiling currently not supported");
            {
              const r = this.gl, i = this.disjointTimerQueryWebgl2Extension;
              t = r.getQueryParameter(s, r.QUERY_RESULT_AVAILABLE), e = r.getParameter(i.GPU_DISJOINT_EXT);
            }
            return t && !e;
          }
          getTimerResult(s) {
            let t = 0;
            if (this.version !== 2) throw new Error("WebGL1 profiling currently not supported");
            {
              const e = this.gl;
              t = e.getQueryParameter(s, e.QUERY_RESULT), e.deleteQuery(s);
            }
            return t / 1e6;
          }
          async waitForQueryAndGetTime(s) {
            return await (0, g.repeatedTry)((() => this.isTimerResultAvailable(s))), this.getTimerResult(s);
          }
          async createAndWaitForFence() {
            const s = this.createFence(this.gl);
            return this.pollFence(s);
          }
          createFence(s) {
            let t;
            const e = s, r = e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE, 0);
            return s.flush(), t = r === null ? () => !0 : () => {
              const i = e.clientWaitSync(r, 0, 0);
              return i === e.ALREADY_SIGNALED || i === e.CONDITION_SATISFIED;
            }, { query: r, isFencePassed: t };
          }
          async pollFence(s) {
            return new Promise(((t) => {
              this.addItemToPoll((() => s.isFencePassed()), (() => t()));
            }));
          }
          pollItems() {
            const s = c(this.itemsToPoll.map(((t) => t.isDoneFn)));
            for (let t = 0; t <= s; ++t) {
              const { resolveFn: e } = this.itemsToPoll[t];
              e();
            }
            this.itemsToPoll = this.itemsToPoll.slice(s + 1);
          }
          async addItemToPoll(s, t) {
            this.itemsToPoll.push({ isDoneFn: s, resolveFn: t }), this.itemsToPoll.length > 1 || await (0, g.repeatedTry)((() => (this.pollItems(), this.itemsToPoll.length === 0)));
          }
        };
      }, 1036: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.ExecutionPlan = void 0;
        const u = o(6231);
        class l {
          constructor(a, f) {
            this.op = a, this.node = f;
          }
        }
        n.ExecutionPlan = class {
          constructor(h, a, f) {
            this.graph = h, this.profiler = f, this.initialize(a);
          }
          initialize(h) {
            this.profiler.event("session", "ExecutionPlan.initialize", (() => {
              const a = this.graph.getNodes();
              if (a.length !== h.length) throw new Error("The size of nodes and OPs do not match.");
              this._ops = h.map(((f, g) => new l(f, a[g]))), this.reset(), this._starter = [], this._ops.forEach(((f, g) => {
                let c = !0;
                for (const s of f.node.inputs) if (!this._values[s] && this.graph.getInputIndices().indexOf(s) === -1) {
                  c = !1;
                  break;
                }
                c && this._starter.push(g);
              }));
            }));
          }
          reset() {
            this._values = this.graph.getValues().map(((h) => h.tensor));
          }
          async execute(h, a) {
            return this.profiler.event("session", "ExecutionPlan.execute", (async () => {
              this.reset();
              const f = h.createInferenceHandler(), g = this.graph.getInputIndices();
              if (a.length !== g.length) throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${a.length} expected: ${g.length}`);
              a.forEach(((i, p) => {
                const m = g[p];
                this._values[m] = i;
              }));
              const c = this._starter.slice(0), s = this.graph.getValues(), t = this.graph.getNodes();
              let e = 0;
              for (; e < c.length; ) {
                const i = c[e++], p = this._ops[i], m = p.node.inputs.map(((w) => this._values[w]));
                if (m.indexOf(void 0) !== -1) throw new Error(`unresolved input detected: op: ${p.node}`);
                const _ = m;
                u.Logger.verbose("ExecPlan", `Runing op:${p.node.name} (${_.map(((w, T) => `'${p.node.inputs[T]}': ${w.type}[${w.dims.join(",")}]`)).join(", ")})`);
                const b = await this.profiler.event("node", p.node.name, (async () => p.op.impl(f, _, p.op.context)));
                if (b.length !== p.node.outputs.length) throw new Error("the size of output does not match model definition.");
                b.forEach(((w, T) => {
                  const S = p.node.outputs[T];
                  if (this._values[S]) throw new Error(`output [${S}] already has value: op:${p.node.name}`);
                  this._values[S] = w;
                }));
                const y = /* @__PURE__ */ new Set();
                b.forEach(((w, T) => {
                  const S = p.node.outputs[T];
                  for (const E of s[S].to) {
                    const O = t[E];
                    let v = !0;
                    for (const A of O.inputs) if (!this._values[A]) {
                      v = !1;
                      break;
                    }
                    v && y.add(E);
                  }
                })), c.push(...y);
              }
              const r = [];
              for (let i = 0; i < this.graph.getOutputIndices().length; i++) {
                const p = this.graph.getOutputIndices()[i], m = this._values[p];
                if (m === void 0) throw new Error(`required output [${p}] does not have value`);
                p === 0 ? await m.getData() : m.data, r.push(m);
              }
              return u.Logger.verbose("ExecPlan", "disposing of inferenceHandler"), f.dispose(), r;
            }));
          }
        };
      }, 7070: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.Graph = void 0;
        const u = o(1446), l = o(7778), h = o(9395), a = o(9162), f = o(2517);
        var g = h.onnxruntime.experimental.fbs;
        n.Graph = { from: (e, r) => new t(e, r) };
        class c {
          constructor(r) {
            this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, r && (this.type = f.ProtoUtil.tensorValueTypeFromProto(r.type.tensorType));
          }
          get from() {
            return this._from;
          }
          get to() {
            return this._to;
          }
        }
        class s {
          constructor(r, i) {
            r instanceof u.onnx.NodeProto ? (this.name = r.name, this.opType = r.opType, this.attributes = new l.Attribute(r.attribute)) : r instanceof g.Node && (this.name = i ?? r.name(), this.opType = r.opType(), this.attributes = new l.Attribute(f.ProtoUtil.tensorAttributesFromORTFormat(r))), this.inputs = [], this.outputs = [], this.executeNode = !0;
          }
        }
        class t {
          constructor(r, i) {
            if (!r) throw new TypeError("graph is empty");
            this.buildGraph(r), this.transformGraph(i), this.checkIsAcyclic();
          }
          getInputIndices() {
            return this._allInputIndices;
          }
          getInputNames() {
            return this._allInputNames;
          }
          getOutputIndices() {
            return this._allOutputIndices;
          }
          getOutputNames() {
            return this._allOutputNames;
          }
          getValues() {
            return this._allData;
          }
          getNodes() {
            return this._nodes;
          }
          buildGraph(r) {
            if (r instanceof u.onnx.GraphProto) this.buildGraphFromOnnxFormat(r);
            else {
              if (!(r instanceof g.Graph)) throw new TypeError("Graph type is not supported.");
              this.buildGraphFromOrtFormat(r);
            }
          }
          buildGraphFromOnnxFormat(r) {
            const i = /* @__PURE__ */ new Map();
            this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = [];
            const p = /* @__PURE__ */ new Map();
            if (!r.input) throw new Error("missing information in graph: input");
            const m = [];
            for (const _ of r.input) {
              if (i.has(_.name)) throw new Error(`duplicated input name: ${_.name}`);
              const b = this._allData.push(new c(_)) - 1;
              i.set(_.name, b), m.push(_.name);
            }
            if (!r.initializer) throw new Error("missing information in graph: initializer");
            for (const _ of r.initializer) {
              let b = i.get(_.name);
              if (b === void 0) {
                const y = new c();
                y.type = { shape: { dims: f.ProtoUtil.tensorDimsFromProto(_.dims) }, tensorType: f.ProtoUtil.tensorDataTypeFromProto(_.dataType) }, b = this._allData.push(y) - 1, i.set(_.name, b);
              }
              this._allData[b]._from = -1, this._allData[b].tensor = a.Tensor.fromProto(_);
            }
            for (let _ = 0; _ < this._allData.length; _++) this._allData[_].tensor || (this._allInputIndices.push(_), this._allInputNames.push(m[_]));
            if (!r.output) throw new Error("missing information in graph: output");
            for (const _ of r.output) {
              if (i.has(_.name)) throw new Error(`duplicated output name: ${_.name}`);
              const b = this._allData.push(new c(_)) - 1;
              i.set(_.name, b), this._allOutputIndices.push(b), this._allOutputNames.push(_.name);
            }
            if (!r.node) throw new Error("missing information in graph: node");
            for (const _ of r.node) {
              if (!_.name) for (let y = 0; ; y++) {
                const w = `unnamed_${_.opType}_${y}`;
                if (!p.has(w)) {
                  _.name = w;
                  break;
                }
              }
              if (p.has(_.name)) throw new Error(`duplicated node name: ${_.name}`);
              const b = this._nodes.push(new s(_)) - 1;
              p.set(_.name, b);
            }
            for (let _ = 0; _ < this._nodes.length; _++) {
              const b = this._nodes[_], y = r.node[_];
              if (!y.output) throw new Error(`missing output for node: ${y.name}`);
              for (const w of y.output) {
                let T = i.get(w);
                if (T === void 0 && (T = this._allData.push(new c()) - 1, i.set(w, T)), b.outputs.push(T), this._allData[T]._from !== void 0) throw new Error(`multiple nodes output to one data value: ${T}`);
                if (this._allData[T]._from = _, y.opType === "Constant") {
                  if (!y.attribute || y.attribute.length !== 1 || !y.attribute[0].t) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");
                  if (!y.output || y.output.length !== 1) throw new Error("missing output or incorrect number of outputs for this Constant operator");
                  b.outputs.pop(), b.executeNode = !1, this._allData[T]._from = -1, this._allData[T].tensor = a.Tensor.fromProto(y.attribute[0].t);
                }
              }
            }
            for (let _ = 0; _ < this._nodes.length; _++) {
              const b = this._nodes[_], y = r.node[_];
              if (!y.input) throw new Error(`missing input for node: ${y.name}`);
              for (const w of y.input) {
                const T = i.get(w);
                if (T === void 0) {
                  if (w === "" && y.input.length === 3 && y.opType === "Resize") continue;
                  throw new Error(`unrecognized input '${w}' for node: ${y.name}`);
                }
                b.inputs.push(T), this._allData[T]._to.push(_);
              }
            }
            return !0;
          }
          buildGraphFromOrtFormat(r) {
            var i, p, m;
            const _ = /* @__PURE__ */ new Map();
            this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = [];
            const b = /* @__PURE__ */ new Map(), y = [];
            for (let w = 0; w < r.inputsLength(); w++) {
              const T = r.inputs(w);
              if (_.has(T)) throw new Error(`duplicated input name: ${T}`);
              for (let S = 0; S < r.nodeArgsLength(); S++) if (((i = r.nodeArgs(S)) === null || i === void 0 ? void 0 : i.name()) === T) {
                const E = new c();
                if (((m = (p = r.nodeArgs(S)) === null || p === void 0 ? void 0 : p.type()) === null || m === void 0 ? void 0 : m.valueType()) !== g.TypeInfoValue.tensor_type) throw new Error("Unexpected value type for the nodeArg.");
                const O = r.nodeArgs(S).type().value(new g.TensorTypeAndShape()), v = f.ProtoUtil.tensorDataTypeFromProto(O.elemType()), A = O.shape(), L = [];
                for (let B = 0; B < A.dimLength(); B++) L.push(f.LongUtil.longToNumber(A.dim(B).value().dimValue()));
                E.type = { shape: { dims: L }, tensorType: v };
                const j = this._allData.push(E) - 1;
                _.set(T, j), y.push(T);
              }
            }
            for (let w = 0; w < r.initializersLength(); w++) {
              const T = r.initializers(w);
              let S = _.get(T.name());
              if (S === void 0) {
                const E = new c(), O = f.ProtoUtil.tensorDimsFromORTFormat(T), v = f.ProtoUtil.tensorDataTypeFromProto(T.dataType());
                E.type = { shape: { dims: O }, tensorType: v }, S = this._allData.push(E) - 1, _.set(T.name(), S);
              }
              this._allData[S]._from = -1, this._allData[S].tensor = a.Tensor.fromOrtTensor(T);
            }
            for (let w = 0; w < this._allData.length; w++) this._allData[w].tensor || (this._allInputIndices.push(w), this._allInputNames.push(y[w]));
            for (let w = 0; w < r.outputsLength(); w++) {
              const T = r.outputs(w);
              if (_.has(T)) throw new Error(`duplicated output name: ${T}`);
              const S = this._allData.push(new c()) - 1;
              _.set(T, S), this._allOutputIndices.push(S), this._allOutputNames.push(T);
            }
            if (!r.nodes) throw new Error("missing information in graph: node");
            for (let w = 0; w < r.nodesLength(); w++) {
              const T = r.nodes(w);
              let S = T.name();
              if (!S) for (let O = 0; S = `unnamed_${T.opType()}_${O}`, b.has(S); O++) ;
              if (b.has(S)) throw new Error(`duplicated node name: ${S}`);
              const E = this._nodes.push(new s(T, S)) - 1;
              b.set(S, E);
            }
            for (let w = 0; w < this._nodes.length; w++) {
              const T = this._nodes[w], S = r.nodes(w);
              if (S == null) throw new Error(`No node exists at index ${w}`);
              if (S?.outputsLength() === 0) throw new Error(`missing output for node: ${S.name}`);
              for (let E = 0; E < S?.outputsLength(); E++) {
                const O = S?.outputs(E);
                let v = _.get(O);
                if (v === void 0 && (v = this._allData.push(new c()) - 1, _.set(O, v)), T.outputs.push(v), this._allData[v]._from !== void 0) throw new Error(`multiple nodes output to one data value: ${v}`);
                if (this._allData[v]._from = w, S.opType() === "Constant") {
                  if (S.attributesLength() !== 1 || !S.attributes(0).t()) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");
                  if (S.outputsLength() !== 1) throw new Error("missing output or incorrect number of outputs for this Constant operator");
                  T.outputs.pop(), T.executeNode = !1, this._allData[v]._from = -1, this._allData[v].tensor = a.Tensor.fromOrtTensor(S.attributes(0).t());
                }
              }
            }
            for (let w = 0; w < this._nodes.length; w++) {
              const T = this._nodes[w], S = r.nodes(w);
              if (S.inputsLength() === 0) throw new Error(`missing input for node: ${S.name}`);
              for (let E = 0; E < S.inputsLength(); E++) {
                const O = S.inputs(E), v = _.get(O);
                if (v === void 0) throw new Error(`unrecognized input '${O}' for node: ${S.name()}`);
                T.inputs.push(v), this._allData[v]._to.push(w);
              }
            }
          }
          checkIsAcyclic() {
            const r = /* @__PURE__ */ new Set();
            this._allInputIndices.forEach(((m) => {
              this._allData[m]._to.forEach(((_) => {
                r.add(_);
              }));
            }));
            const i = Array.from(r), p = new Array(this._nodes.length).fill("white");
            for (; i.length > 0; ) {
              const m = i.pop();
              p[m] === "gray" ? p[m] = "black" : (i.push(m), p[m] = "gray", this._nodes[m].outputs.forEach(((_) => {
                const b = this._allData[_];
                if (b.tensor !== void 0) throw new Error("node outputs should not be initialized");
                if (b._from !== m) throw new Error("from property of the Value object doesn't match index of Node being processed");
                b._to.forEach(((y) => {
                  if (p[y] === "gray") throw new Error("model graph is cyclic");
                  p[y] === "white" && i.push(y);
                }));
              })));
            }
          }
          transformGraph(r) {
            this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), r && r.transformGraph(this), this.finalizeGraph();
          }
          finalizeGraph() {
            let r = 0;
            for (let i = 0; i < this._nodes.length; i++) this._nodes[i].executeNode ? r > 0 && (this._nodes[i].inputs.forEach(((p) => {
              const m = this._allData[p]._to.indexOf(i + r);
              m !== -1 && (this._allData[p]._to[m] = i);
            })), this._nodes[i].outputs.forEach(((p) => {
              this._allData[p]._from && this._allData[p]._from === i + r && (this._allData[p]._from = i);
            }))) : (r++, this._nodes[i].outputs.forEach(((p) => {
              this._allData[p]._from = -2;
            })), this._nodes.splice(i, 1), i--);
            r = 0;
            for (let i = 0; i < this._allData.length; i++) if (this._allData[i].from !== -2 || this._allOutputIndices.indexOf(i + r) !== -1) {
              if (r > 0) {
                let p = -1;
                this._allData[i].from !== void 0 && this._allData[i].from !== -1 ? (p = this._nodes[this._allData[i].from].outputs.indexOf(i + r), p !== -1 && (this._nodes[this._allData[i].from].outputs[p] = i)) : (p = this._allInputIndices.indexOf(i + r), p !== -1 && (this._allInputIndices[p] = i)), this._allData[i].to.forEach(((m) => {
                  p = this._nodes[m].inputs.indexOf(i + r), p !== -1 && (this._nodes[m].inputs[p] = i);
                })), this._allData[i].to.length === 0 && (p = this._allOutputIndices.indexOf(i + r), p !== -1 && (this._allOutputIndices[p] = i));
              }
            } else r++, this._allData.splice(i, 1), i--;
          }
          deleteNode(r) {
            const i = this._nodes[r];
            if (i.outputs.length > 1) {
              for (let w = 1; w < i.outputs.length; w++) if (this._allData[i.outputs[w]].to.length > 0) throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");
            }
            i.executeNode = !1;
            const p = i.inputs[0], m = i.outputs[0], _ = this._allData[m].to, b = this._allData[p].to.indexOf(r);
            if (b === -1) throw new Error("The Value object doesn't have the current Node in it's 'to' property ");
            this._allData[p].to.splice(b, 1), this._allData[m]._to = [];
            const y = this._allOutputIndices.indexOf(m);
            if (y !== -1 && (this._allOutputIndices[y] = p), _ && _.length > 0) for (const w of _) {
              const T = this._nodes[w].inputs.indexOf(m);
              if (T === -1) throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");
              this._nodes[w].inputs[T] = p, this._allData[p].to.push(w);
            }
          }
          removeAllDropoutNodes() {
            let r = 0;
            for (const i of this._nodes) {
              if (i.opType === "Dropout") {
                if (i.inputs.length !== 1) throw new Error("Dropout nodes should only contain one input. ");
                if (i.outputs.length !== 1 && i.outputs.length !== 2) throw new Error("Dropout nodes should contain either 1 or 2 output(s)");
                if (i.outputs.length === 2 && this._allData[i.outputs[1]]._to.length !== 0) throw new Error("Dropout nodes's second output should not be referenced by other nodes");
                this.deleteNode(r);
              }
              r++;
            }
          }
          removeAllIdentityNodes() {
            let r = 0;
            for (const i of this._nodes) i.opType === "Identity" && this.deleteNode(r), r++;
          }
          isActivation(r) {
            switch (r.opType) {
              case "Relu":
              case "Sigmoid":
              case "Clip":
                return !0;
              default:
                return !1;
            }
          }
          fuseConvActivationNodes() {
            for (const r of this._nodes) if (r.opType === "Conv") {
              const i = this._allData[r.outputs[0]]._to;
              if (i.length === 1 && this.isActivation(this._nodes[i[0]])) {
                const p = this._nodes[i[0]];
                if (p.opType === "Clip") if (p.inputs.length === 1) try {
                  r.attributes.set("activation_params", "floats", [p.attributes.getFloat("min"), p.attributes.getFloat("max")]);
                } catch {
                  r.attributes.set("activation_params", "floats", [f.MIN_CLIP, f.MAX_CLIP]);
                }
                else {
                  if (!(p.inputs.length >= 3 && this._allData[p.inputs[1]].tensor !== void 0 && this._allData[p.inputs[2]].tensor !== void 0)) continue;
                  r.attributes.set("activation_params", "floats", [this._allData[p.inputs[1]].tensor.floatData[0], this._allData[p.inputs[2]].tensor.floatData[0]]);
                }
                r.attributes.set("activation", "string", p.opType), this.deleteNode(i[0]);
              }
            }
          }
        }
      }, 6231: (d, n) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.now = n.Profiler = n.Logger = void 0;
        const o = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }, u = { none: new class {
          log(s, t, e) {
          }
        }(), console: new class {
          log(s, t, e) {
            console.log(`${this.color(s)} ${e ? "\x1B[35m" + e + "\x1B[0m " : ""}${t}`);
          }
          color(s) {
            switch (s) {
              case "verbose":
                return "\x1B[34;40mv\x1B[0m";
              case "info":
                return "\x1B[32mi\x1B[0m";
              case "warning":
                return "\x1B[30;43mw\x1B[0m";
              case "error":
                return "\x1B[31;40me\x1B[0m";
              case "fatal":
                return "\x1B[101mf\x1B[0m";
              default:
                throw new Error(`unsupported severity: ${s}`);
            }
          }
        }() }, l = { provider: "console", minimalSeverity: "warning", logDateTime: !0, logSourceLocation: !1 };
        let h = { "": l };
        function a(s, t, e, r) {
          if (t === void 0) return i = s, { verbose: a.verbose.bind(null, i), info: a.info.bind(null, i), warning: a.warning.bind(null, i), error: a.error.bind(null, i), fatal: a.fatal.bind(null, i) };
          if (e === void 0) f(s, t);
          else if (typeof e == "number" && r === void 0) f(s, t);
          else if (typeof e == "string" && r === void 0) f(s, e, 0, t);
          else {
            if (typeof e != "string" || typeof r != "number") throw new TypeError("input is valid");
            f(s, e, 0, t);
          }
          var i;
        }
        function f(s, t, e, r) {
          const i = h[r || ""] || h[""];
          o[s] < o[i.minimalSeverity] || (i.logDateTime && (t = `${(/* @__PURE__ */ new Date()).toISOString()}|${t}`), i.logSourceLocation, u[i.provider].log(s, t, r));
        }
        (function(s) {
          function t(r) {
            h = {}, e("", r || {});
          }
          function e(r, i) {
            if (r === "*") t(i);
            else {
              const p = h[r] || l;
              h[r] = { provider: i.provider || p.provider, minimalSeverity: i.minimalSeverity || p.minimalSeverity, logDateTime: i.logDateTime === void 0 ? p.logDateTime : i.logDateTime, logSourceLocation: i.logSourceLocation === void 0 ? p.logSourceLocation : i.logSourceLocation };
            }
          }
          s.verbose = function(r, i) {
            s("verbose", r, i);
          }, s.info = function(r, i) {
            s("info", r, i);
          }, s.warning = function(r, i) {
            s("warning", r, i);
          }, s.error = function(r, i) {
            s("error", r, i);
          }, s.fatal = function(r, i) {
            s("fatal", r, i);
          }, s.reset = t, s.set = e, s.setWithEnv = function(r) {
            const i = {};
            r.logLevel && (i.minimalSeverity = r.logLevel), e("", i);
          };
        })(a || (a = {})), n.Logger = a;
        class g {
          constructor(t, e, r, i, p, m) {
            this.category = t, this.name = e, this.startTime = r, this.endCallback = i, this.timer = p, this.ctx = m;
          }
          end() {
            return this.endCallback(this);
          }
          async checkTimer() {
            if (this.ctx === void 0 || this.timer === void 0) throw new Error("No webgl timer found");
            return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer);
          }
        }
        class c {
          constructor(t, e, r, i) {
            this.category = t, this.name = e, this.startTime = r, this.endTime = i;
          }
        }
        n.Profiler = class {
          static create(s) {
            return s === void 0 ? new this() : new this(s.maxNumberEvents, s.flushBatchSize, s.flushIntervalInMilliseconds);
          }
          constructor(s, t, e) {
            this._started = !1, this._flushPointer = 0, this._started = !1, this._maxNumberEvents = s === void 0 ? 1e4 : s, this._flushBatchSize = t === void 0 ? 10 : t, this._flushIntervalInMilliseconds = e === void 0 ? 5e3 : e;
          }
          start() {
            this._started = !0, this._timingEvents = [], this._flushTime = (0, n.now)(), this._flushPointer = 0;
          }
          stop() {
            for (this._started = !1; this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]);
          }
          event(s, t, e, r) {
            const i = this._started ? this.begin(s, t, r) : void 0;
            let p = !1;
            const m = e();
            if (m && typeof m.then == "function") return p = !0, new Promise(((_, b) => {
              m.then((async (y) => {
                i && await i.end(), _(y);
              }), (async (y) => {
                i && await i.end(), b(y);
              }));
            }));
            if (!p && i) {
              const _ = i.end();
              if (_ && typeof _.then == "function") return new Promise(((b, y) => {
                _.then((() => {
                  b(m);
                }), ((w) => {
                  y(w);
                }));
              }));
            }
            return m;
          }
          begin(s, t, e) {
            if (!this._started) throw new Error("profiler is not started yet");
            if (e === void 0) {
              const r = (0, n.now)();
              return this.flush(r), new g(s, t, r, ((i) => this.endSync(i)));
            }
            {
              const r = e.beginTimer();
              return new g(s, t, 0, (async (i) => this.end(i)), r, e);
            }
          }
          async end(s) {
            const t = await s.checkTimer();
            this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(s.category, s.name, s.startTime, t)), this.flush(t));
          }
          endSync(s) {
            const t = (0, n.now)();
            this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(s.category, s.name, s.startTime, t)), this.flush(t));
          }
          logOneEvent(s) {
            n.Logger.verbose(`Profiler.${s.category}`, `${(s.endTime - s.startTime).toFixed(2)}ms on event '${s.name}' at ${s.endTime.toFixed(2)}`);
          }
          flush(s) {
            if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || s - this._flushTime >= this._flushIntervalInMilliseconds) {
              for (const t = this._flushPointer; this._flushPointer < t + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]);
              this._flushTime = (0, n.now)();
            }
          }
          get started() {
            return this._started;
          }
        }, n.now = typeof performance < "u" && performance.now ? () => performance.now() : Date.now;
      }, 2644: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.Model = void 0;
        const u = o(5686), l = o(1446), h = o(7070), a = o(9395), f = o(2517);
        var g = a.onnxruntime.experimental.fbs;
        n.Model = class {
          constructor() {
          }
          load(c, s, t) {
            if (!t) try {
              return void this.loadFromOnnxFormat(c, s);
            } catch (e) {
              if (t !== void 0) throw e;
            }
            this.loadFromOrtFormat(c, s);
          }
          loadFromOnnxFormat(c, s) {
            const t = l.onnx.ModelProto.decode(c);
            if (f.LongUtil.longToNumber(t.irVersion) < 3) throw new Error("only support ONNX model with IR_VERSION>=3");
            this._opsets = t.opsetImport.map(((e) => ({ domain: e.domain, version: f.LongUtil.longToNumber(e.version) }))), this._graph = h.Graph.from(t.graph, s);
          }
          loadFromOrtFormat(c, s) {
            const t = new u.flatbuffers.ByteBuffer(c), e = g.InferenceSession.getRootAsInferenceSession(t).model();
            if (f.LongUtil.longToNumber(e.irVersion()) < 3) throw new Error("only support ONNX model with IR_VERSION>=3");
            this._opsets = [];
            for (let r = 0; r < e.opsetImportLength(); r++) {
              const i = e.opsetImport(r);
              this._opsets.push({ domain: i?.domain(), version: f.LongUtil.longToNumber(i.version()) });
            }
            this._graph = h.Graph.from(e.graph(), s);
          }
          get graph() {
            return this._graph;
          }
          get opsets() {
            return this._opsets;
          }
        };
      }, 782: (d, n) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.FLOAT_TYPES = n.INT_TYPES = n.NUMBER_TYPES = void 0, n.NUMBER_TYPES = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"], n.INT_TYPES = ["int32", "int16", "int8", "uint16", "uint32", "uint8"], n.FLOAT_TYPES = ["float32", "float64"];
      }, 1047: (d, n) => {
        function o(u, l) {
          if (l.endsWith("+")) {
            const h = Number.parseInt(l.substring(0, l.length - 1), 10);
            return !isNaN(h) && h <= u;
          }
          if (l.split("-").length === 2) {
            const h = l.split("-"), a = Number.parseInt(h[0], 10), f = Number.parseInt(h[1], 10);
            return !isNaN(a) && !isNaN(f) && a <= u && u <= f;
          }
          return Number.parseInt(l, 10) === u;
        }
        Object.defineProperty(n, "__esModule", { value: !0 }), n.resolveOperator = void 0, n.resolveOperator = function(u, l, h) {
          for (const a of h) {
            const f = a[0], g = a[1], c = a[2], s = a[3], t = a[4];
            if (u.opType === f) {
              for (const e of l) if ((e.domain === g || e.domain === "ai.onnx" && g === "") && o(e.version, c)) return { opImpl: s, opInit: t };
            }
          }
          throw new TypeError(`cannot resolve operator '${u.opType}' with opsets: ${l.map(((a) => `${a.domain || "ai.onnx"} v${a.version}`)).join(", ")}`);
        };
      }, 9395: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.onnxruntime = void 0;
        const u = o(5686);
        var l, h;
        l = n.onnxruntime || (n.onnxruntime = {}), (function(a) {
          (function(f) {
            f[f.UNDEFINED = 0] = "UNDEFINED", f[f.FLOAT = 1] = "FLOAT", f[f.INT = 2] = "INT", f[f.STRING = 3] = "STRING", f[f.TENSOR = 4] = "TENSOR", f[f.GRAPH = 5] = "GRAPH", f[f.FLOATS = 6] = "FLOATS", f[f.INTS = 7] = "INTS", f[f.STRINGS = 8] = "STRINGS", f[f.TENSORS = 9] = "TENSORS", f[f.GRAPHS = 10] = "GRAPHS", f[f.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", f[f.SPARSE_TENSORS = 12] = "SPARSE_TENSORS";
          })(a.AttributeType || (a.AttributeType = {}));
        })((h = l.experimental || (l.experimental = {})).fbs || (h.fbs = {})), (function(a) {
          (function(f) {
            (function(g) {
              (function(c) {
                c[c.UNKNOWN = 0] = "UNKNOWN", c[c.VALUE = 1] = "VALUE", c[c.PARAM = 2] = "PARAM";
              })(g.DimensionValueType || (g.DimensionValueType = {}));
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              (function(c) {
                c[c.UNDEFINED = 0] = "UNDEFINED", c[c.FLOAT = 1] = "FLOAT", c[c.UINT8 = 2] = "UINT8", c[c.INT8 = 3] = "INT8", c[c.UINT16 = 4] = "UINT16", c[c.INT16 = 5] = "INT16", c[c.INT32 = 6] = "INT32", c[c.INT64 = 7] = "INT64", c[c.STRING = 8] = "STRING", c[c.BOOL = 9] = "BOOL", c[c.FLOAT16 = 10] = "FLOAT16", c[c.DOUBLE = 11] = "DOUBLE", c[c.UINT32 = 12] = "UINT32", c[c.UINT64 = 13] = "UINT64", c[c.COMPLEX64 = 14] = "COMPLEX64", c[c.COMPLEX128 = 15] = "COMPLEX128", c[c.BFLOAT16 = 16] = "BFLOAT16";
              })(g.TensorDataType || (g.TensorDataType = {}));
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              (function(c) {
                c[c.Primitive = 0] = "Primitive", c[c.Fused = 1] = "Fused";
              })(g.NodeType || (g.NodeType = {}));
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              (function(c) {
                c[c.NONE = 0] = "NONE", c[c.tensor_type = 1] = "tensor_type", c[c.sequence_type = 2] = "sequence_type", c[c.map_type = 3] = "map_type";
              })(g.TypeInfoValue || (g.TypeInfoValue = {}));
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsShape(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsShape(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                dim(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 4);
                  return r ? (e || new a.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                dimLength() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startShape(t) {
                  t.startObject(1);
                }
                static addDim(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static createDimVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startDimVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static endShape(t) {
                  return t.endObject();
                }
                static createShape(t, e) {
                  return c.startShape(t), c.addDim(t, e), c.endShape(t);
                }
              }
              g.Shape = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsDimension(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsDimension(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                value(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? (t || new a.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                denotation(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                static startDimension(t) {
                  t.startObject(2);
                }
                static addValue(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addDenotation(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static endDimension(t) {
                  return t.endObject();
                }
                static createDimension(t, e, r) {
                  return c.startDimension(t), c.addValue(t, e), c.addDenotation(t, r), c.endDimension(t);
                }
              }
              g.Dimension = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsDimensionValue(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsDimensionValue(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                dimType() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.readInt8(this.bb_pos + t) : a.experimental.fbs.DimensionValueType.UNKNOWN;
                }
                dimValue() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.readInt64(this.bb_pos + t) : this.bb.createLong(0, 0);
                }
                dimParam(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                static startDimensionValue(t) {
                  t.startObject(3);
                }
                static addDimType(t, e) {
                  t.addFieldInt8(0, e, a.experimental.fbs.DimensionValueType.UNKNOWN);
                }
                static addDimValue(t, e) {
                  t.addFieldInt64(1, e, t.createLong(0, 0));
                }
                static addDimParam(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static endDimensionValue(t) {
                  return t.endObject();
                }
                static createDimensionValue(t, e, r, i) {
                  return c.startDimensionValue(t), c.addDimType(t, e), c.addDimValue(t, r), c.addDimParam(t, i), c.endDimensionValue(t);
                }
              }
              g.DimensionValue = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsTensorTypeAndShape(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsTensorTypeAndShape(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                elemType() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.readInt32(this.bb_pos + t) : a.experimental.fbs.TensorDataType.UNDEFINED;
                }
                shape(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? (t || new a.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                static startTensorTypeAndShape(t) {
                  t.startObject(2);
                }
                static addElemType(t, e) {
                  t.addFieldInt32(0, e, a.experimental.fbs.TensorDataType.UNDEFINED);
                }
                static addShape(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static endTensorTypeAndShape(t) {
                  return t.endObject();
                }
                static createTensorTypeAndShape(t, e, r) {
                  return c.startTensorTypeAndShape(t), c.addElemType(t, e), c.addShape(t, r), c.endTensorTypeAndShape(t);
                }
              }
              g.TensorTypeAndShape = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsMapType(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsMapType(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                keyType() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.readInt32(this.bb_pos + t) : a.experimental.fbs.TensorDataType.UNDEFINED;
                }
                valueType(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? (t || new a.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                static startMapType(t) {
                  t.startObject(2);
                }
                static addKeyType(t, e) {
                  t.addFieldInt32(0, e, a.experimental.fbs.TensorDataType.UNDEFINED);
                }
                static addValueType(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static endMapType(t) {
                  return t.endObject();
                }
                static createMapType(t, e, r) {
                  return c.startMapType(t), c.addKeyType(t, e), c.addValueType(t, r), c.endMapType(t);
                }
              }
              g.MapType = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsSequenceType(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsSequenceType(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                elemType(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? (t || new a.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                static startSequenceType(t) {
                  t.startObject(1);
                }
                static addElemType(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static endSequenceType(t) {
                  return t.endObject();
                }
                static createSequenceType(t, e) {
                  return c.startSequenceType(t), c.addElemType(t, e), c.endSequenceType(t);
                }
              }
              g.SequenceType = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (f.fbs || (f.fbs = {})).EdgeEnd = class {
              constructor() {
                this.bb = null, this.bb_pos = 0;
              }
              __init(g, c) {
                return this.bb_pos = g, this.bb = c, this;
              }
              nodeIndex() {
                return this.bb.readUint32(this.bb_pos);
              }
              srcArgIndex() {
                return this.bb.readInt32(this.bb_pos + 4);
              }
              dstArgIndex() {
                return this.bb.readInt32(this.bb_pos + 8);
              }
              static createEdgeEnd(g, c, s, t) {
                return g.prep(4, 12), g.writeInt32(t), g.writeInt32(s), g.writeInt32(c), g.offset();
              }
            };
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsNodeEdge(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsNodeEdge(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                nodeIndex() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.readUint32(this.bb_pos + t) : 0;
                }
                inputEdges(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 6);
                  return r ? (e || new a.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r) + 12 * t, this.bb) : null;
                }
                inputEdgesLength() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                outputEdges(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 8);
                  return r ? (e || new a.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r) + 12 * t, this.bb) : null;
                }
                outputEdgesLength() {
                  let t = this.bb.__offset(this.bb_pos, 8);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startNodeEdge(t) {
                  t.startObject(3);
                }
                static addNodeIndex(t, e) {
                  t.addFieldInt32(0, e, 0);
                }
                static addInputEdges(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static startInputEdgesVector(t, e) {
                  t.startVector(12, e, 4);
                }
                static addOutputEdges(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static startOutputEdgesVector(t, e) {
                  t.startVector(12, e, 4);
                }
                static endNodeEdge(t) {
                  return t.endObject();
                }
                static createNodeEdge(t, e, r, i) {
                  return c.startNodeEdge(t), c.addNodeIndex(t, e), c.addInputEdges(t, r), c.addOutputEdges(t, i), c.endNodeEdge(t);
                }
              }
              g.NodeEdge = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsNode(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsNode(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                name(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                docString(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                domain(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                sinceVersion() {
                  let t = this.bb.__offset(this.bb_pos, 10);
                  return t ? this.bb.readInt32(this.bb_pos + t) : 0;
                }
                index() {
                  let t = this.bb.__offset(this.bb_pos, 12);
                  return t ? this.bb.readUint32(this.bb_pos + t) : 0;
                }
                opType(t) {
                  let e = this.bb.__offset(this.bb_pos, 14);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                type() {
                  let t = this.bb.__offset(this.bb_pos, 16);
                  return t ? this.bb.readInt32(this.bb_pos + t) : a.experimental.fbs.NodeType.Primitive;
                }
                executionProviderType(t) {
                  let e = this.bb.__offset(this.bb_pos, 18);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                inputs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 20);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                inputsLength() {
                  let t = this.bb.__offset(this.bb_pos, 20);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                outputs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 22);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                outputsLength() {
                  let t = this.bb.__offset(this.bb_pos, 22);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                attributes(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 24);
                  return r ? (e || new a.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                attributesLength() {
                  let t = this.bb.__offset(this.bb_pos, 24);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                inputArgCounts(t) {
                  let e = this.bb.__offset(this.bb_pos, 26);
                  return e ? this.bb.readInt32(this.bb.__vector(this.bb_pos + e) + 4 * t) : 0;
                }
                inputArgCountsLength() {
                  let t = this.bb.__offset(this.bb_pos, 26);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                inputArgCountsArray() {
                  let t = this.bb.__offset(this.bb_pos, 26);
                  return t ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t), this.bb.__vector_len(this.bb_pos + t)) : null;
                }
                implicitInputs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 28);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                implicitInputsLength() {
                  let t = this.bb.__offset(this.bb_pos, 28);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startNode(t) {
                  t.startObject(13);
                }
                static addName(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addDocString(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static addDomain(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static addSinceVersion(t, e) {
                  t.addFieldInt32(3, e, 0);
                }
                static addIndex(t, e) {
                  t.addFieldInt32(4, e, 0);
                }
                static addOpType(t, e) {
                  t.addFieldOffset(5, e, 0);
                }
                static addType(t, e) {
                  t.addFieldInt32(6, e, a.experimental.fbs.NodeType.Primitive);
                }
                static addExecutionProviderType(t, e) {
                  t.addFieldOffset(7, e, 0);
                }
                static addInputs(t, e) {
                  t.addFieldOffset(8, e, 0);
                }
                static createInputsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startInputsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addOutputs(t, e) {
                  t.addFieldOffset(9, e, 0);
                }
                static createOutputsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startOutputsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addAttributes(t, e) {
                  t.addFieldOffset(10, e, 0);
                }
                static createAttributesVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startAttributesVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addInputArgCounts(t, e) {
                  t.addFieldOffset(11, e, 0);
                }
                static createInputArgCountsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt32(e[r]);
                  return t.endVector();
                }
                static startInputArgCountsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addImplicitInputs(t, e) {
                  t.addFieldOffset(12, e, 0);
                }
                static createImplicitInputsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startImplicitInputsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static endNode(t) {
                  return t.endObject();
                }
                static createNode(t, e, r, i, p, m, _, b, y, w, T, S, E, O) {
                  return c.startNode(t), c.addName(t, e), c.addDocString(t, r), c.addDomain(t, i), c.addSinceVersion(t, p), c.addIndex(t, m), c.addOpType(t, _), c.addType(t, b), c.addExecutionProviderType(t, y), c.addInputs(t, w), c.addOutputs(t, T), c.addAttributes(t, S), c.addInputArgCounts(t, E), c.addImplicitInputs(t, O), c.endNode(t);
                }
              }
              g.Node = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsValueInfo(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsValueInfo(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                name(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                docString(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                type(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? (t || new a.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                static startValueInfo(t) {
                  t.startObject(3);
                }
                static addName(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addDocString(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static addType(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static endValueInfo(t) {
                  return t.endObject();
                }
                static createValueInfo(t, e, r, i) {
                  return c.startValueInfo(t), c.addName(t, e), c.addDocString(t, r), c.addType(t, i), c.endValueInfo(t);
                }
              }
              g.ValueInfo = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsTypeInfo(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsTypeInfo(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                denotation(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                valueType() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.readUint8(this.bb_pos + t) : a.experimental.fbs.TypeInfoValue.NONE;
                }
                value(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? this.bb.__union(t, this.bb_pos + e) : null;
                }
                static startTypeInfo(t) {
                  t.startObject(3);
                }
                static addDenotation(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addValueType(t, e) {
                  t.addFieldInt8(1, e, a.experimental.fbs.TypeInfoValue.NONE);
                }
                static addValue(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static endTypeInfo(t) {
                  return t.endObject();
                }
                static createTypeInfo(t, e, r, i) {
                  return c.startTypeInfo(t), c.addDenotation(t, e), c.addValueType(t, r), c.addValue(t, i), c.endTypeInfo(t);
                }
              }
              g.TypeInfo = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsOperatorSetId(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsOperatorSetId(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                domain(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                version() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.readInt64(this.bb_pos + t) : this.bb.createLong(0, 0);
                }
                static startOperatorSetId(t) {
                  t.startObject(2);
                }
                static addDomain(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addVersion(t, e) {
                  t.addFieldInt64(1, e, t.createLong(0, 0));
                }
                static endOperatorSetId(t) {
                  return t.endObject();
                }
                static createOperatorSetId(t, e, r) {
                  return c.startOperatorSetId(t), c.addDomain(t, e), c.addVersion(t, r), c.endOperatorSetId(t);
                }
              }
              g.OperatorSetId = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsTensor(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsTensor(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                name(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                docString(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                dims(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e) + 8 * t) : this.bb.createLong(0, 0);
                }
                dimsLength() {
                  let t = this.bb.__offset(this.bb_pos, 8);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                dataType() {
                  let t = this.bb.__offset(this.bb_pos, 10);
                  return t ? this.bb.readInt32(this.bb_pos + t) : a.experimental.fbs.TensorDataType.UNDEFINED;
                }
                rawData(t) {
                  let e = this.bb.__offset(this.bb_pos, 12);
                  return e ? this.bb.readUint8(this.bb.__vector(this.bb_pos + e) + t) : 0;
                }
                rawDataLength() {
                  let t = this.bb.__offset(this.bb_pos, 12);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                rawDataArray() {
                  let t = this.bb.__offset(this.bb_pos, 12);
                  return t ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t), this.bb.__vector_len(this.bb_pos + t)) : null;
                }
                stringData(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 14);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                stringDataLength() {
                  let t = this.bb.__offset(this.bb_pos, 14);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startTensor(t) {
                  t.startObject(6);
                }
                static addName(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addDocString(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static addDims(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static createDimsVector(t, e) {
                  t.startVector(8, e.length, 8);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt64(e[r]);
                  return t.endVector();
                }
                static startDimsVector(t, e) {
                  t.startVector(8, e, 8);
                }
                static addDataType(t, e) {
                  t.addFieldInt32(3, e, a.experimental.fbs.TensorDataType.UNDEFINED);
                }
                static addRawData(t, e) {
                  t.addFieldOffset(4, e, 0);
                }
                static createRawDataVector(t, e) {
                  t.startVector(1, e.length, 1);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt8(e[r]);
                  return t.endVector();
                }
                static startRawDataVector(t, e) {
                  t.startVector(1, e, 1);
                }
                static addStringData(t, e) {
                  t.addFieldOffset(5, e, 0);
                }
                static createStringDataVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startStringDataVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static endTensor(t) {
                  return t.endObject();
                }
                static createTensor(t, e, r, i, p, m, _) {
                  return c.startTensor(t), c.addName(t, e), c.addDocString(t, r), c.addDims(t, i), c.addDataType(t, p), c.addRawData(t, m), c.addStringData(t, _), c.endTensor(t);
                }
              }
              g.Tensor = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsSparseTensor(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsSparseTensor(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                values(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? (t || new a.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                indices(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? (t || new a.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                dims(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e) + 8 * t) : this.bb.createLong(0, 0);
                }
                dimsLength() {
                  let t = this.bb.__offset(this.bb_pos, 8);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startSparseTensor(t) {
                  t.startObject(3);
                }
                static addValues(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addIndices(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static addDims(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static createDimsVector(t, e) {
                  t.startVector(8, e.length, 8);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt64(e[r]);
                  return t.endVector();
                }
                static startDimsVector(t, e) {
                  t.startVector(8, e, 8);
                }
                static endSparseTensor(t) {
                  return t.endObject();
                }
                static createSparseTensor(t, e, r, i) {
                  return c.startSparseTensor(t), c.addValues(t, e), c.addIndices(t, r), c.addDims(t, i), c.endSparseTensor(t);
                }
              }
              g.SparseTensor = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsAttribute(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsAttribute(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                name(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                docString(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                type() {
                  let t = this.bb.__offset(this.bb_pos, 8);
                  return t ? this.bb.readInt32(this.bb_pos + t) : a.experimental.fbs.AttributeType.UNDEFINED;
                }
                f() {
                  let t = this.bb.__offset(this.bb_pos, 10);
                  return t ? this.bb.readFloat32(this.bb_pos + t) : 0;
                }
                i() {
                  let t = this.bb.__offset(this.bb_pos, 12);
                  return t ? this.bb.readInt64(this.bb_pos + t) : this.bb.createLong(0, 0);
                }
                s(t) {
                  let e = this.bb.__offset(this.bb_pos, 14);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                t(t) {
                  let e = this.bb.__offset(this.bb_pos, 16);
                  return e ? (t || new a.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                g(t) {
                  let e = this.bb.__offset(this.bb_pos, 18);
                  return e ? (t || new a.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                floats(t) {
                  let e = this.bb.__offset(this.bb_pos, 20);
                  return e ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + e) + 4 * t) : 0;
                }
                floatsLength() {
                  let t = this.bb.__offset(this.bb_pos, 20);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                floatsArray() {
                  let t = this.bb.__offset(this.bb_pos, 20);
                  return t ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t), this.bb.__vector_len(this.bb_pos + t)) : null;
                }
                ints(t) {
                  let e = this.bb.__offset(this.bb_pos, 22);
                  return e ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e) + 8 * t) : this.bb.createLong(0, 0);
                }
                intsLength() {
                  let t = this.bb.__offset(this.bb_pos, 22);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                strings(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 24);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                stringsLength() {
                  let t = this.bb.__offset(this.bb_pos, 24);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                tensors(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 26);
                  return r ? (e || new a.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                tensorsLength() {
                  let t = this.bb.__offset(this.bb_pos, 26);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                graphs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 28);
                  return r ? (e || new a.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                graphsLength() {
                  let t = this.bb.__offset(this.bb_pos, 28);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startAttribute(t) {
                  t.startObject(13);
                }
                static addName(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addDocString(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static addType(t, e) {
                  t.addFieldInt32(2, e, a.experimental.fbs.AttributeType.UNDEFINED);
                }
                static addF(t, e) {
                  t.addFieldFloat32(3, e, 0);
                }
                static addI(t, e) {
                  t.addFieldInt64(4, e, t.createLong(0, 0));
                }
                static addS(t, e) {
                  t.addFieldOffset(5, e, 0);
                }
                static addT(t, e) {
                  t.addFieldOffset(6, e, 0);
                }
                static addG(t, e) {
                  t.addFieldOffset(7, e, 0);
                }
                static addFloats(t, e) {
                  t.addFieldOffset(8, e, 0);
                }
                static createFloatsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addFloat32(e[r]);
                  return t.endVector();
                }
                static startFloatsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addInts(t, e) {
                  t.addFieldOffset(9, e, 0);
                }
                static createIntsVector(t, e) {
                  t.startVector(8, e.length, 8);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt64(e[r]);
                  return t.endVector();
                }
                static startIntsVector(t, e) {
                  t.startVector(8, e, 8);
                }
                static addStrings(t, e) {
                  t.addFieldOffset(10, e, 0);
                }
                static createStringsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startStringsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addTensors(t, e) {
                  t.addFieldOffset(11, e, 0);
                }
                static createTensorsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startTensorsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addGraphs(t, e) {
                  t.addFieldOffset(12, e, 0);
                }
                static createGraphsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startGraphsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static endAttribute(t) {
                  return t.endObject();
                }
                static createAttribute(t, e, r, i, p, m, _, b, y, w, T, S, E, O) {
                  return c.startAttribute(t), c.addName(t, e), c.addDocString(t, r), c.addType(t, i), c.addF(t, p), c.addI(t, m), c.addS(t, _), c.addT(t, b), c.addG(t, y), c.addFloats(t, w), c.addInts(t, T), c.addStrings(t, S), c.addTensors(t, E), c.addGraphs(t, O), c.endAttribute(t);
                }
              }
              g.Attribute = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsGraph(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsGraph(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                initializers(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 4);
                  return r ? (e || new a.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                initializersLength() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                nodeArgs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 6);
                  return r ? (e || new a.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                nodeArgsLength() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                nodes(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 8);
                  return r ? (e || new a.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                nodesLength() {
                  let t = this.bb.__offset(this.bb_pos, 8);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                maxNodeIndex() {
                  let t = this.bb.__offset(this.bb_pos, 10);
                  return t ? this.bb.readUint32(this.bb_pos + t) : 0;
                }
                nodeEdges(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 12);
                  return r ? (e || new a.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                nodeEdgesLength() {
                  let t = this.bb.__offset(this.bb_pos, 12);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                inputs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 14);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                inputsLength() {
                  let t = this.bb.__offset(this.bb_pos, 14);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                outputs(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 16);
                  return r ? this.bb.__string(this.bb.__vector(this.bb_pos + r) + 4 * t, e) : null;
                }
                outputsLength() {
                  let t = this.bb.__offset(this.bb_pos, 16);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                sparseInitializers(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 18);
                  return r ? (e || new a.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                sparseInitializersLength() {
                  let t = this.bb.__offset(this.bb_pos, 18);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startGraph(t) {
                  t.startObject(8);
                }
                static addInitializers(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static createInitializersVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startInitializersVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addNodeArgs(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static createNodeArgsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startNodeArgsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addNodes(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static createNodesVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startNodesVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addMaxNodeIndex(t, e) {
                  t.addFieldInt32(3, e, 0);
                }
                static addNodeEdges(t, e) {
                  t.addFieldOffset(4, e, 0);
                }
                static createNodeEdgesVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startNodeEdgesVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addInputs(t, e) {
                  t.addFieldOffset(5, e, 0);
                }
                static createInputsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startInputsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addOutputs(t, e) {
                  t.addFieldOffset(6, e, 0);
                }
                static createOutputsVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startOutputsVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addSparseInitializers(t, e) {
                  t.addFieldOffset(7, e, 0);
                }
                static createSparseInitializersVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startSparseInitializersVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static endGraph(t) {
                  return t.endObject();
                }
                static createGraph(t, e, r, i, p, m, _, b, y) {
                  return c.startGraph(t), c.addInitializers(t, e), c.addNodeArgs(t, r), c.addNodes(t, i), c.addMaxNodeIndex(t, p), c.addNodeEdges(t, m), c.addInputs(t, _), c.addOutputs(t, b), c.addSparseInitializers(t, y), c.endGraph(t);
                }
              }
              g.Graph = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsModel(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsModel(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                irVersion() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.readInt64(this.bb_pos + t) : this.bb.createLong(0, 0);
                }
                opsetImport(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 6);
                  return r ? (e || new a.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                opsetImportLength() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                producerName(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                producerVersion(t) {
                  let e = this.bb.__offset(this.bb_pos, 10);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                domain(t) {
                  let e = this.bb.__offset(this.bb_pos, 12);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                modelVersion() {
                  let t = this.bb.__offset(this.bb_pos, 14);
                  return t ? this.bb.readInt64(this.bb_pos + t) : this.bb.createLong(0, 0);
                }
                docString(t) {
                  let e = this.bb.__offset(this.bb_pos, 16);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                graph(t) {
                  let e = this.bb.__offset(this.bb_pos, 18);
                  return e ? (t || new a.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                graphDocString(t) {
                  let e = this.bb.__offset(this.bb_pos, 20);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                static startModel(t) {
                  t.startObject(9);
                }
                static addIrVersion(t, e) {
                  t.addFieldInt64(0, e, t.createLong(0, 0));
                }
                static addOpsetImport(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static createOpsetImportVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startOpsetImportVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addProducerName(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static addProducerVersion(t, e) {
                  t.addFieldOffset(3, e, 0);
                }
                static addDomain(t, e) {
                  t.addFieldOffset(4, e, 0);
                }
                static addModelVersion(t, e) {
                  t.addFieldInt64(5, e, t.createLong(0, 0));
                }
                static addDocString(t, e) {
                  t.addFieldOffset(6, e, 0);
                }
                static addGraph(t, e) {
                  t.addFieldOffset(7, e, 0);
                }
                static addGraphDocString(t, e) {
                  t.addFieldOffset(8, e, 0);
                }
                static endModel(t) {
                  return t.endObject();
                }
                static createModel(t, e, r, i, p, m, _, b, y, w) {
                  return c.startModel(t), c.addIrVersion(t, e), c.addOpsetImport(t, r), c.addProducerName(t, i), c.addProducerVersion(t, p), c.addDomain(t, m), c.addModelVersion(t, _), c.addDocString(t, b), c.addGraph(t, y), c.addGraphDocString(t, w), c.endModel(t);
                }
              }
              g.Model = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsKernelCreateInfos(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsKernelCreateInfos(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                nodeIndices(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.readUint32(this.bb.__vector(this.bb_pos + e) + 4 * t) : 0;
                }
                nodeIndicesLength() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                nodeIndicesArray() {
                  let t = this.bb.__offset(this.bb_pos, 4);
                  return t ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t), this.bb.__vector_len(this.bb_pos + t)) : null;
                }
                kernelDefHashes(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? this.bb.readUint64(this.bb.__vector(this.bb_pos + e) + 8 * t) : this.bb.createLong(0, 0);
                }
                kernelDefHashesLength() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startKernelCreateInfos(t) {
                  t.startObject(2);
                }
                static addNodeIndices(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static createNodeIndicesVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt32(e[r]);
                  return t.endVector();
                }
                static startNodeIndicesVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static addKernelDefHashes(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static createKernelDefHashesVector(t, e) {
                  t.startVector(8, e.length, 8);
                  for (let r = e.length - 1; r >= 0; r--) t.addInt64(e[r]);
                  return t.endVector();
                }
                static startKernelDefHashesVector(t, e) {
                  t.startVector(8, e, 8);
                }
                static endKernelCreateInfos(t) {
                  return t.endObject();
                }
                static createKernelCreateInfos(t, e, r) {
                  return c.startKernelCreateInfos(t), c.addNodeIndices(t, e), c.addKernelDefHashes(t, r), c.endKernelCreateInfos(t);
                }
              }
              g.KernelCreateInfos = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsSubGraphSessionState(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsSubGraphSessionState(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                graphId(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                sessionState(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? (t || new a.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                static startSubGraphSessionState(t) {
                  t.startObject(2);
                }
                static addGraphId(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addSessionState(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static endSubGraphSessionState(t) {
                  let e = t.endObject();
                  return t.requiredField(e, 4), e;
                }
                static createSubGraphSessionState(t, e, r) {
                  return c.startSubGraphSessionState(t), c.addGraphId(t, e), c.addSessionState(t, r), c.endSubGraphSessionState(t);
                }
              }
              g.SubGraphSessionState = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsSessionState(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsSessionState(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                kernels(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? (t || new a.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                subGraphSessionStates(t, e) {
                  let r = this.bb.__offset(this.bb_pos, 6);
                  return r ? (e || new a.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r) + 4 * t), this.bb) : null;
                }
                subGraphSessionStatesLength() {
                  let t = this.bb.__offset(this.bb_pos, 6);
                  return t ? this.bb.__vector_len(this.bb_pos + t) : 0;
                }
                static startSessionState(t) {
                  t.startObject(2);
                }
                static addKernels(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addSubGraphSessionStates(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static createSubGraphSessionStatesVector(t, e) {
                  t.startVector(4, e.length, 4);
                  for (let r = e.length - 1; r >= 0; r--) t.addOffset(e[r]);
                  return t.endVector();
                }
                static startSubGraphSessionStatesVector(t, e) {
                  t.startVector(4, e, 4);
                }
                static endSessionState(t) {
                  return t.endObject();
                }
                static createSessionState(t, e, r) {
                  return c.startSessionState(t), c.addKernels(t, e), c.addSubGraphSessionStates(t, r), c.endSessionState(t);
                }
              }
              g.SessionState = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {})), (function(a) {
          (function(f) {
            (function(g) {
              class c {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t, e) {
                  return this.bb_pos = t, this.bb = e, this;
                }
                static getRootAsInferenceSession(t, e) {
                  return (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static getSizePrefixedRootAsInferenceSession(t, e) {
                  return t.setPosition(t.position() + u.flatbuffers.SIZE_PREFIX_LENGTH), (e || new c()).__init(t.readInt32(t.position()) + t.position(), t);
                }
                static bufferHasIdentifier(t) {
                  return t.__has_identifier("ORTM");
                }
                ortVersion(t) {
                  let e = this.bb.__offset(this.bb_pos, 4);
                  return e ? this.bb.__string(this.bb_pos + e, t) : null;
                }
                model(t) {
                  let e = this.bb.__offset(this.bb_pos, 6);
                  return e ? (t || new a.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                sessionState(t) {
                  let e = this.bb.__offset(this.bb_pos, 8);
                  return e ? (t || new a.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + e), this.bb) : null;
                }
                static startInferenceSession(t) {
                  t.startObject(3);
                }
                static addOrtVersion(t, e) {
                  t.addFieldOffset(0, e, 0);
                }
                static addModel(t, e) {
                  t.addFieldOffset(1, e, 0);
                }
                static addSessionState(t, e) {
                  t.addFieldOffset(2, e, 0);
                }
                static endInferenceSession(t) {
                  return t.endObject();
                }
                static finishInferenceSessionBuffer(t, e) {
                  t.finish(e, "ORTM");
                }
                static finishSizePrefixedInferenceSessionBuffer(t, e) {
                  t.finish(e, "ORTM", !0);
                }
                static createInferenceSession(t, e, r, i) {
                  return c.startInferenceSession(t), c.addOrtVersion(t, e), c.addModel(t, r), c.addSessionState(t, i), c.endInferenceSession(t);
                }
              }
              g.InferenceSession = c;
            })(f.fbs || (f.fbs = {}));
          })(a.experimental || (a.experimental = {}));
        })(n.onnxruntime || (n.onnxruntime = {}));
      }, 7448: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.OnnxjsSessionHandler = void 0;
        const u = o(1670), l = o(9162);
        n.OnnxjsSessionHandler = class {
          constructor(h) {
            this.session = h, this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames;
          }
          async dispose() {
          }
          async run(h, a, f) {
            const g = /* @__PURE__ */ new Map();
            for (const t in h) if (Object.hasOwnProperty.call(h, t)) {
              const e = h[t];
              g.set(t, new l.Tensor(e.dims, e.type, void 0, void 0, e.data));
            }
            const c = await this.session.run(g), s = {};
            return c.forEach(((t, e) => {
              s[e] = new u.Tensor(t.type, t.data, t.dims);
            })), s;
          }
          startProfiling() {
            this.session.startProfiling();
          }
          endProfiling() {
            this.session.endProfiling();
          }
        };
      }, 6919: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.Session = void 0;
        const u = o(7067), l = o(1296), h = o(7091), a = o(1036), f = o(6231), g = o(2644);
        n.Session = class {
          constructor(c = {}) {
            this._initialized = !1, this.backendHint = c.backendHint, this.profiler = f.Profiler.create(c.profiler), this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] };
          }
          get inputNames() {
            return this._model.graph.getInputNames();
          }
          get outputNames() {
            return this._model.graph.getOutputNames();
          }
          startProfiling() {
            this.profiler.start();
          }
          endProfiling() {
            this.profiler.stop();
          }
          async loadModel(c, s, t) {
            await this.profiler.event("session", "Session.loadModel", (async () => {
              const e = await (0, h.resolveBackend)(this.backendHint);
              if (this.sessionHandler = e.createSessionHandler(this.context), this._model = new g.Model(), typeof c == "string") {
                const r = c.endsWith(".ort");
                if (typeof fetch > "u") {
                  const i = await (0, l.promisify)(u.readFile)(c);
                  this.initialize(i, r);
                } else {
                  const i = await fetch(c), p = await i.arrayBuffer();
                  this.initialize(new Uint8Array(p), r);
                }
              } else if (ArrayBuffer.isView(c)) this.initialize(c);
              else {
                const r = new Uint8Array(c, s || 0, t || c.byteLength);
                this.initialize(r);
              }
            }));
          }
          initialize(c, s) {
            if (this._initialized) throw new Error("already initialized");
            this.profiler.event("session", "Session.initialize", (() => {
              const t = this.sessionHandler.transformGraph ? this.sessionHandler : void 0;
              this._model.load(c, t, s), this.sessionHandler.onGraphInitialized && this.sessionHandler.onGraphInitialized(this._model.graph), this.initializeOps(this._model.graph), this._executionPlan = new a.ExecutionPlan(this._model.graph, this._ops, this.profiler);
            })), this._initialized = !0;
          }
          async run(c) {
            if (!this._initialized) throw new Error("session not initialized yet");
            return this.profiler.event("session", "Session.run", (async () => {
              const s = this.normalizeAndValidateInputs(c), t = await this._executionPlan.execute(this.sessionHandler, s);
              return this.createOutput(t);
            }));
          }
          normalizeAndValidateInputs(c) {
            const s = this._model.graph.getInputNames();
            if (Array.isArray(c)) {
              if (c.length !== s.length) throw new Error(`incorrect input array length: expected ${s.length} but got ${c.length}`);
            } else {
              if (c.size !== s.length) throw new Error(`incorrect input map size: expected ${s.length} but got ${c.size}`);
              const t = new Array(c.size);
              let e = 0;
              for (let r = 0; r < s.length; ++r) {
                const i = c.get(s[r]);
                if (!i) throw new Error(`missing input tensor for: '${name}'`);
                t[e++] = i;
              }
              c = t;
            }
            if (this.context.graphInputTypes && this.context.graphInputTypes.length !== 0 && this.context.graphInputDims && this.context.graphInputDims.length !== 0) this.validateInputTensorDims(this.context.graphInputDims, c, !1);
            else {
              const t = this._model.graph.getInputIndices(), e = this._model.graph.getValues(), r = new Array(t.length);
              for (let i = 0; i < t.length; ++i) {
                const p = e[t[i]];
                r[i] = p.type.shape.dims, this.context.graphInputTypes.push(p.type.tensorType), this.context.graphInputDims.push(c[i].dims);
              }
              this.validateInputTensorDims(r, c, !0);
            }
            return this.validateInputTensorTypes(this.context.graphInputTypes, c), c;
          }
          validateInputTensorTypes(c, s) {
            for (let t = 0; t < s.length; t++) {
              const e = c[t], r = s[t].type;
              if (e !== r) throw new Error(`input tensor[${t}] check failed: expected type '${e}' but got ${r}`);
            }
          }
          validateInputTensorDims(c, s, t) {
            for (let e = 0; e < s.length; e++) {
              const r = c[e], i = s[e].dims;
              if (!this.compareTensorDims(r, i, t)) throw new Error(`input tensor[${e}] check failed: expected shape '[${r.join(",")}]' but got [${i.join(",")}]`);
            }
          }
          compareTensorDims(c, s, t) {
            if (c.length !== s.length) return !1;
            for (let e = 0; e < c.length; ++e) if (c[e] !== s[e] && (!t || c[e] !== 0)) return !1;
            return !0;
          }
          createOutput(c) {
            const s = this._model.graph.getOutputNames();
            if (c.length !== s.length) throw new Error("expected number of outputs do not match number of generated outputs");
            const t = /* @__PURE__ */ new Map();
            for (let e = 0; e < s.length; ++e) t.set(s[e], c[e]);
            return t;
          }
          initializeOps(c) {
            const s = c.getNodes();
            this._ops = new Array(s.length);
            for (let t = 0; t < s.length; t++) this._ops[t] = this.sessionHandler.resolve(s[t], this._model.opsets, c);
          }
        };
      }, 9162: function(d, n, o) {
        var u = this && this.__importDefault || function(p) {
          return p && p.__esModule ? p : { default: p };
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), n.Tensor = void 0;
        const l = o(3442), h = u(o(3720)), a = o(1446), f = o(9395), g = o(2517);
        var c = f.onnxruntime.experimental.fbs;
        class s {
          get data() {
            if (this.cache === void 0) {
              const m = this.dataProvider(this.dataId);
              if (m.length !== this.size) throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");
              this.cache = m;
            }
            return this.cache;
          }
          get stringData() {
            if (this.type !== "string") throw new TypeError("data type is not string");
            return this.data;
          }
          get integerData() {
            switch (this.type) {
              case "uint8":
              case "int8":
              case "uint16":
              case "int16":
              case "int32":
              case "uint32":
              case "bool":
                return this.data;
              default:
                throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)");
            }
          }
          get floatData() {
            switch (this.type) {
              case "float32":
              case "float64":
                return this.data;
              default:
                throw new TypeError("data type is not float (float32, float64)");
            }
          }
          get numberData() {
            if (this.type !== "string") return this.data;
            throw new TypeError("type cannot be non-number (string)");
          }
          get(m) {
            return this.data[g.ShapeUtil.indicesToOffset(m, this.strides)];
          }
          set(m, _) {
            this.data[g.ShapeUtil.indicesToOffset(m, this.strides)] = _;
          }
          async getData() {
            return this.cache === void 0 && (this.cache = await this.asyncDataProvider(this.dataId)), this.cache;
          }
          get strides() {
            return this._strides || (this._strides = g.ShapeUtil.computeStrides(this.dims)), this._strides;
          }
          constructor(m, _, b, y, w, T = l.Guid.create()) {
            this.dims = m, this.type = _, this.dataProvider = b, this.asyncDataProvider = y, this.cache = w, this.dataId = T, this.size = g.ShapeUtil.validateDimsAndCalcSize(m);
            const S = this.size, E = b === void 0 && y === void 0 && w === void 0;
            if (w !== void 0 && w.length !== S) throw new RangeError("Input dims doesn't match data length.");
            if (_ === "string") {
              if (!(w === void 0 || Array.isArray(w) && w.every(((O) => typeof O == "string")))) throw new TypeError("cache should be a string array");
              E && (this.cache = new Array(S));
            } else {
              if (w !== void 0) {
                const O = e(_);
                if (!(w instanceof O)) throw new TypeError(`cache should be type ${O.name}`);
              }
              if (E) {
                const O = new ArrayBuffer(S * (function(v) {
                  switch (v) {
                    case "bool":
                    case "int8":
                    case "uint8":
                      return 1;
                    case "int16":
                    case "uint16":
                      return 2;
                    case "int32":
                    case "uint32":
                    case "float32":
                      return 4;
                    case "float64":
                      return 8;
                    default:
                      throw new Error(`cannot calculate sizeof() on type ${v}`);
                  }
                })(_));
                this.cache = (function(v, A) {
                  return new (e(A))(v);
                })(O, _);
              }
            }
          }
          static fromProto(m) {
            if (!m) throw new Error("cannot construct Value from an empty tensor");
            const _ = g.ProtoUtil.tensorDataTypeFromProto(m.dataType), b = g.ProtoUtil.tensorDimsFromProto(m.dims), y = new s(b, _);
            if (_ === "string") m.stringData.forEach(((w, T) => {
              y.data[T] = (0, g.decodeUtf8String)(w);
            }));
            else if (m.rawData && typeof m.rawData.byteLength == "number" && m.rawData.byteLength > 0) {
              const w = y.data, T = new DataView(m.rawData.buffer, m.rawData.byteOffset, m.rawData.byteLength), S = t(m.dataType), E = m.rawData.byteLength / S;
              if (m.rawData.byteLength % S != 0) throw new Error("invalid buffer length");
              if (w.length !== E) throw new Error("buffer length mismatch");
              for (let O = 0; O < E; O++) {
                const v = i(T, m.dataType, O * S);
                w[O] = v;
              }
            } else {
              let w;
              switch (m.dataType) {
                case a.onnx.TensorProto.DataType.FLOAT:
                  w = m.floatData;
                  break;
                case a.onnx.TensorProto.DataType.INT32:
                case a.onnx.TensorProto.DataType.INT16:
                case a.onnx.TensorProto.DataType.UINT16:
                case a.onnx.TensorProto.DataType.INT8:
                case a.onnx.TensorProto.DataType.UINT8:
                case a.onnx.TensorProto.DataType.BOOL:
                  w = m.int32Data;
                  break;
                case a.onnx.TensorProto.DataType.INT64:
                  w = m.int64Data;
                  break;
                case a.onnx.TensorProto.DataType.DOUBLE:
                  w = m.doubleData;
                  break;
                case a.onnx.TensorProto.DataType.UINT32:
                case a.onnx.TensorProto.DataType.UINT64:
                  w = m.uint64Data;
                  break;
                default:
                  throw new Error("unspecific error");
              }
              if (w == null) throw new Error("failed to populate data from a tensorproto value");
              const T = y.data;
              if (T.length !== w.length) throw new Error("array length mismatch");
              for (let S = 0; S < w.length; S++) {
                const E = w[S];
                h.default.isLong(E) ? T[S] = r(E, m.dataType) : T[S] = E;
              }
            }
            return y;
          }
          static fromData(m, _, b) {
            return new s(_, b, void 0, void 0, m);
          }
          static fromOrtTensor(m) {
            if (!m) throw new Error("cannot construct Value from an empty tensor");
            const _ = g.ProtoUtil.tensorDimsFromORTFormat(m), b = g.ProtoUtil.tensorDataTypeFromProto(m.dataType()), y = new s(_, b);
            if (b === "string") for (let w = 0; w < m.stringDataLength(); w++) y.data[w] = m.stringData(w);
            else if (m.rawDataArray() && typeof m.rawDataLength() == "number" && m.rawDataLength() > 0) {
              const w = y.data, T = new DataView(m.rawDataArray().buffer, m.rawDataArray().byteOffset, m.rawDataLength()), S = t(m.dataType()), E = m.rawDataLength() / S;
              if (m.rawDataLength() % S != 0) throw new Error("invalid buffer length");
              if (w.length !== E) throw new Error("buffer length mismatch");
              for (let O = 0; O < E; O++) {
                const v = i(T, m.dataType(), O * S);
                w[O] = v;
              }
            }
            return y;
          }
        }
        function t(p) {
          switch (p) {
            case a.onnx.TensorProto.DataType.UINT8:
            case a.onnx.TensorProto.DataType.INT8:
            case a.onnx.TensorProto.DataType.BOOL:
              return 1;
            case a.onnx.TensorProto.DataType.UINT16:
            case a.onnx.TensorProto.DataType.INT16:
              return 2;
            case a.onnx.TensorProto.DataType.FLOAT:
            case a.onnx.TensorProto.DataType.INT32:
            case a.onnx.TensorProto.DataType.UINT32:
              return 4;
            case a.onnx.TensorProto.DataType.INT64:
            case a.onnx.TensorProto.DataType.DOUBLE:
            case a.onnx.TensorProto.DataType.UINT64:
              return 8;
            default:
              throw new Error(`cannot calculate sizeof() on type ${a.onnx.TensorProto.DataType[p]}`);
          }
        }
        function e(p) {
          switch (p) {
            case "bool":
            case "uint8":
              return Uint8Array;
            case "int8":
              return Int8Array;
            case "int16":
              return Int16Array;
            case "uint16":
              return Uint16Array;
            case "int32":
              return Int32Array;
            case "uint32":
              return Uint32Array;
            case "float32":
              return Float32Array;
            case "float64":
              return Float64Array;
            default:
              throw new Error("unspecified error");
          }
        }
        function r(p, m) {
          if (m === a.onnx.TensorProto.DataType.INT64 || m === c.TensorDataType.INT64) {
            if (p.greaterThanOrEqual(2147483648) || p.lessThan(-2147483648)) throw new TypeError("int64 is not supported");
          } else {
            if (m !== a.onnx.TensorProto.DataType.UINT32 && m !== c.TensorDataType.UINT32 && m !== a.onnx.TensorProto.DataType.UINT64 && m !== c.TensorDataType.UINT64) throw new TypeError(`not a LONG type: ${a.onnx.TensorProto.DataType[m]}`);
            if (p.greaterThanOrEqual(4294967296) || p.lessThan(0)) throw new TypeError("uint64 is not supported");
          }
          return p.toNumber();
        }
        function i(p, m, _) {
          switch (m) {
            case a.onnx.TensorProto.DataType.BOOL:
            case a.onnx.TensorProto.DataType.UINT8:
              return p.getUint8(_);
            case a.onnx.TensorProto.DataType.INT8:
              return p.getInt8(_);
            case a.onnx.TensorProto.DataType.UINT16:
              return p.getUint16(_, !0);
            case a.onnx.TensorProto.DataType.INT16:
              return p.getInt16(_, !0);
            case a.onnx.TensorProto.DataType.FLOAT:
              return p.getFloat32(_, !0);
            case a.onnx.TensorProto.DataType.INT32:
              return p.getInt32(_, !0);
            case a.onnx.TensorProto.DataType.UINT32:
              return p.getUint32(_, !0);
            case a.onnx.TensorProto.DataType.INT64:
              return r(h.default.fromBits(p.getUint32(_, !0), p.getUint32(_ + 4, !0), !1), m);
            case a.onnx.TensorProto.DataType.DOUBLE:
              return p.getFloat64(_, !0);
            case a.onnx.TensorProto.DataType.UINT64:
              return r(h.default.fromBits(p.getUint32(_, !0), p.getUint32(_ + 4, !0), !0), m);
            default:
              throw new Error(`cannot read from DataView for type ${a.onnx.TensorProto.DataType[m]}`);
          }
        }
        n.Tensor = s;
      }, 2517: function(d, n, o) {
        var u = this && this.__importDefault || function(m) {
          return m && m.__esModule ? m : { default: m };
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), n.decodeUtf8String = n.MAX_CLIP = n.MIN_CLIP = n.PoolConvUtil = n.ReduceUtil = n.SplitUtil = n.MathUtil = n.ShapeUtil = n.LongUtil = n.ProtoUtil = n.GemmUtil = n.arrayCopyHelper = n.BroadcastUtil = n.MatMulUtil = n.ArrayUtil = n.assert = n.checkInputsShape = void 0;
        const l = o(5686), h = u(o(3720)), a = o(1446), f = o(9162);
        n.checkInputsShape = function(m, ..._) {
          if (!m || m.length !== _.length) return !1;
          for (let b = 0; b < m.length; b++) if (!m[b].dims || m[b].dims.length !== _[b]) return !1;
          return !0;
        }, n.assert = function(m, _) {
          if (!m) throw new Error(typeof _ == "string" ? _ : _());
        }, n.ArrayUtil = class {
          static arraysEqual(m, _) {
            if (m.length !== _.length) return !1;
            for (let b = 0; b < m.length; b++) if (m[b] !== _[b]) return !1;
            return !0;
          }
        };
        class g {
          static preprocessInputShapes(_, b) {
            return [_.length === 1 ? [1, _[0]] : _, b.length === 1 ? [b[0], 1] : b];
          }
          static postprocessOutputShape(_, b, y) {
            b === 1 && _.splice(_.length - 2, 1), y === 1 && _.pop();
          }
          static calcMatMulShape(_, b) {
            return _[1] !== b[0] ? void 0 : [_[0], b[1]];
          }
        }
        n.MatMulUtil = g;
        class c {
          static calcShape(_, b, y = !1) {
            const w = _.length, T = b.length;
            if (w === 0) return b;
            if (T === 0) return _;
            const S = Math.max(_.length, b.length), E = new Array(S);
            if (y) {
              if (w < 2 || T < 2) return;
              const O = g.calcMatMulShape([_[w - 2], _[w - 1]], [b[T - 2], b[T - 1]]);
              if (O === void 0) return;
              [E[S - 2], E[S - 1]] = O;
            }
            for (let O = y ? 3 : 1; O <= S; O++) {
              const v = w - O < 0 ? 1 : _[w - O], A = T - O < 0 ? 1 : b[T - O];
              if (v !== A && v > 1 && A > 1) return;
              E[S - O] = Math.max(v, A);
            }
            return E;
          }
          static index(_, b) {
            const y = new Array(b.length);
            return c.fillIndex(_, b, y), y;
          }
          static fillIndex(_, b, y) {
            const w = _.length - b.length;
            for (let T = 0; T < b.length; T++) y[T] = _[w + T] % b[T];
          }
          static calc(_, b, y, w, T) {
            const S = c.calcShape(_.dims, b.dims);
            if (S) {
              if (w && !e.areEqual(S, _.dims)) return;
              const E = e.size(S), O = w ? _ : new f.Tensor(S, T || _.type);
              if (S.length === 0) O.set([], y(_.get([]), b.get([])));
              else {
                const v = new Array(S.length), A = new Array(_.dims.length), L = new Array(b.dims.length);
                let j, B = 0, F = 0, D = !1, I = !1;
                _.dims.length === 0 && (B = _.get([]), D = !0), b.dims.length === 0 && (F = b.get([]), I = !0);
                for (let $ = 0; $ < E; $++) {
                  j = $;
                  for (let Q = S.length - 1; Q >= 0; Q--) v[Q] = j % S[Q], j = Math.floor(j / S[Q]);
                  D || (c.fillIndex(v, _.dims, A), B = _.get(A)), I || (c.fillIndex(v, b.dims, L), F = b.get(L)), O.set(v, y(B, F));
                }
              }
              return O;
            }
          }
          static isValidBroadcast(_, b) {
            const y = _.length, w = b.length;
            if (y > w) return !1;
            for (let T = 1; T <= y; T++) if (_[y - T] !== 1 && _[y - T] !== b[w - T]) return !1;
            return !0;
          }
          static getBroadcastDims(_, b) {
            const y = _.length, w = [];
            for (let T = 0; T < y; T++) {
              const S = y - 1 - T, E = _[S] || 1;
              (b[b.length - 1 - T] || 1) > 1 && E === 1 && w.unshift(S);
            }
            return w;
          }
        }
        n.BroadcastUtil = c, n.arrayCopyHelper = function(m, _, b, y, w) {
          if (y < 0 || y >= _.length) throw new Error("sourceIndex out of bounds");
          if (b < 0 || b >= m.length) throw new Error("targetIndex out of bounds");
          if (y + w > _.length) throw new Error("source indices to be copied are outside bounds");
          if (b + w > m.length) throw new Error("target array is too small to hold result");
          for (let T = 0; T < w; T++) m[b + T] = _[y + T];
        }, n.GemmUtil = class {
          static getShapeOfGemmResult(m, _, b, y, w) {
            if (m.length !== 2 || b.length !== 2) throw new Error("shape need to be of size 2");
            let T, S, E;
            _ ? (T = m[1], S = m[0]) : (T = m[0], S = m[1]);
            let O = -1;
            if (y ? (E = b[0], O = 1) : (E = b[1], O = 0), b[O] !== S) throw new Error("dimension mismatch");
            if (T <= 0 || E <= 0 || S <= 0) throw new Error("invalid shape specified");
            if (w && !c.isValidBroadcast(w, [T, E])) throw new Error("gemm: invalid bias shape for broadcast");
            return [T, E, S];
          }
        };
        class s {
          static tensorDataTypeFromProto(_) {
            switch (_) {
              case a.onnx.TensorProto.DataType.INT8:
                return "int8";
              case a.onnx.TensorProto.DataType.UINT8:
                return "uint8";
              case a.onnx.TensorProto.DataType.BOOL:
                return "bool";
              case a.onnx.TensorProto.DataType.INT16:
                return "int16";
              case a.onnx.TensorProto.DataType.UINT16:
                return "uint16";
              case a.onnx.TensorProto.DataType.INT32:
                return "int32";
              case a.onnx.TensorProto.DataType.UINT32:
                return "uint32";
              case a.onnx.TensorProto.DataType.FLOAT:
                return "float32";
              case a.onnx.TensorProto.DataType.DOUBLE:
                return "float64";
              case a.onnx.TensorProto.DataType.STRING:
                return "string";
              case a.onnx.TensorProto.DataType.INT64:
                return "int32";
              case a.onnx.TensorProto.DataType.UINT64:
                return "uint32";
              default:
                throw new Error(`unsupported data type: ${a.onnx.TensorProto.DataType[_]}`);
            }
          }
          static tensorDataTypeStringToEnum(_) {
            switch (_) {
              case "int8":
                return a.onnx.TensorProto.DataType.INT8;
              case "uint8":
                return a.onnx.TensorProto.DataType.UINT8;
              case "bool":
                return a.onnx.TensorProto.DataType.BOOL;
              case "int16":
                return a.onnx.TensorProto.DataType.INT16;
              case "uint16":
                return a.onnx.TensorProto.DataType.UINT16;
              case "int32":
                return a.onnx.TensorProto.DataType.INT32;
              case "uint32":
                return a.onnx.TensorProto.DataType.UINT32;
              case "float32":
                return a.onnx.TensorProto.DataType.FLOAT;
              case "float64":
                return a.onnx.TensorProto.DataType.DOUBLE;
              case "string":
                return a.onnx.TensorProto.DataType.STRING;
              case "int64":
                return a.onnx.TensorProto.DataType.INT64;
              case "uint64":
                return a.onnx.TensorProto.DataType.UINT64;
              default:
                throw new Error(`unsupported data type: ${_}`);
            }
          }
          static tensorDimsFromProto(_) {
            return _.map(((b) => h.default.isLong(b) ? b.toNumber() : b));
          }
          static tensorValueTypeFromProto(_) {
            return { tensorType: s.tensorDataTypeFromProto(_.elemType), shape: { dims: s.tensorDimsFromProto(_.shape.dim.map(((b) => b.dimValue))) } };
          }
          static tensorDimsFromORTFormat(_) {
            const b = [];
            for (let y = 0; y < _.dimsLength(); y++) b.push(t.longToNumber(_.dims(y)));
            return b;
          }
          static tensorAttributesFromORTFormat(_) {
            const b = [];
            for (let y = 0; y < _.attributesLength(); y++) b.push(_.attributes(y));
            return b;
          }
        }
        n.ProtoUtil = s;
        class t {
          static longToNumber(_, b) {
            return h.default.isLong(_) ? _.toNumber() : _ instanceof l.flatbuffers.Long ? h.default.fromValue({ low: _.low, high: _.high, unsigned: b != null && b }).toNumber() : _;
          }
          static isLong(_) {
            return h.default.isLong(_) || _ instanceof l.flatbuffers.Long;
          }
        }
        n.LongUtil = t;
        class e {
          static size(_) {
            return e.getSizeFromDimensionRange(_, 0, _.length);
          }
          static sizeFromDimension(_, b) {
            if (b < 0 || b > _.length) throw new Error(`invalid dimension of ${b} for sizeFromDimension as Tensor has ${_.length} dimensions.`);
            return e.getSizeFromDimensionRange(_, b, _.length);
          }
          static sizeToDimension(_, b) {
            if (b < 0 || b > _.length) throw new Error(`invalid dimension of ${b} for sizeToDimension as Tensor has ${_.length} dimensions.`);
            return e.getSizeFromDimensionRange(_, 0, b);
          }
          static getSizeFromDimensionRange(_, b, y) {
            let w = 1;
            for (let T = b; T < y; T++) {
              if (_[T] <= 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");
              w *= _[T];
            }
            return w;
          }
          static computeStrides(_) {
            const b = _.length;
            if (b === 0) return [];
            if (b === 1) return [1];
            const y = new Array(b);
            y[b - 1] = 1, y[b - 2] = _[b - 1];
            for (let w = b - 3; w >= 0; --w) y[w] = y[w + 1] * _[w + 1];
            return y;
          }
          static transpose(_) {
            return _.slice().reverse();
          }
          static indicesToOffset(_, b, y) {
            y === void 0 && (y = _.length);
            let w = 0;
            for (let T = 0; T < y; ++T) w += b[T] * _[T];
            return w;
          }
          static offsetToIndices(_, b) {
            const y = b.length;
            if (y === 0) return [];
            if (y === 1) return [_ * b[0]];
            const w = new Array(b.length);
            for (let T = 0; T < w.length - 1; ++T) w[T] = Math.floor(_ / b[T]), _ -= w[T] * b[T];
            return w[w.length - 1] = _, w;
          }
          static normalizeAxis(_, b) {
            if (_ < -b && _ >= b) throw new Error("unsupported axis for this operation.");
            return _ < 0 ? _ + b : _;
          }
          static normalizeAxes(_, b) {
            return _.map(((y) => this.normalizeAxis(y, b)));
          }
          static incrementIndex(_, b, y) {
            if (b.length === 0 || _.length === 0) throw new Error("Index incrementing unsupported for scalar Tensor");
            if (y === void 0) y = b.length;
            else if (y <= 0 || y > b.length) throw new Error("Incorrect axis to increment on");
            for (let w = y - 1; w >= 0 && (_[w]++, !(_[w] < b[w])); --w) _[w] = 0;
          }
          static calculateReshapedDims(_, b) {
            if (b.length === 0) {
              if (_.length === 0 || e.size(_) === 1) return [];
              throw new Error("cannot reshape to a scalar Tensor");
            }
            const y = b.length, w = new Array(y);
            let T = -1, S = 1;
            for (let O = 0; O < y; O++) {
              if (b[O] < -1) throw new Error("a dimension in shape hints cannot be less than -1");
              if (b[O] === -1) {
                if (T !== -1) throw new Error("at most one dimension in shape hints can be -1");
                T = O;
              } else {
                if (b[O] === 0) {
                  if (O >= _.length) throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");
                  w[O] = _[O];
                } else w[O] = b[O];
                S *= w[O];
              }
            }
            const E = e.size(_);
            if (T !== -1) {
              if (E % S != 0) throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${_}] Output shape: [${b}]`);
              w[T] = E / S;
            } else if (S !== E) throw new Error("reshapedDims and originalDims don't have matching sizes");
            return w;
          }
          static sortBasedOnPerm(_, b) {
            return b ? b.map(((y) => _[y])) : _.slice().reverse();
          }
          static padShape(_, b) {
            const y = _.length;
            return _.map(((w, T) => w + b[T] + b[T + y]));
          }
          static areEqual(_, b) {
            return _.length === b.length && _.every(((y, w) => y === b[w]));
          }
          static validateDimsAndCalcSize(_) {
            if (_.length > 6) throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");
            let b = 1;
            for (const y of _) {
              if (!Number.isInteger(y)) throw new TypeError(`Invalid shape: ${y} is not an integer`);
              if (y < 0 || y > 2147483647) throw new TypeError(`Invalid shape: length ${y} is not allowed`);
              b *= y;
            }
            return b;
          }
          static flattenShape(_, b) {
            b < 0 && (b += _.length);
            const y = _.reduce(((T, S) => T * S), 1), w = _.slice(b).reduce(((T, S) => T * S), 1);
            return [y / w, w];
          }
          static squeezeShape(_, b) {
            const y = new Array();
            b = e.normalizeAxes(b, _.length);
            for (let w = 0; w < _.length; w++) {
              const T = b.indexOf(w) >= 0;
              if (T && _[w] !== 1) throw new Error("squeeze an axis of size different than 1");
              (b.length === 0 && _[w] > 1 || b.length > 0 && !T) && y.push(_[w]);
            }
            return y;
          }
          static unsqueezeShape(_, b) {
            const y = new Array(_.length + b.length);
            y.fill(0);
            for (let T = 0; T < b.length; T++) {
              const S = e.normalizeAxis(b[T], y.length);
              if (S >= y.length) throw new Error("'axes' has an out of range axis");
              if (y[S] !== 0) throw new Error("'axes' has a duplicate axis");
              y[S] = 1;
            }
            let w = 0;
            for (let T = 0; T < y.length; T++) y[T] === 0 && (y[T] = _[w++]);
            if (w !== _.length) throw new Error("the unsqueezed dimension could not be established");
            return y;
          }
        }
        n.ShapeUtil = e, n.MathUtil = class {
          static sqr(m, _, b, y, w) {
            if (y < 0 || y >= _.length) throw new Error("sourceIndex out of bounds");
            if (b < 0 || b >= m.length) throw new Error("targetIndex out of bounds");
            if (y + w > _.length) throw new Error("source indices to be copied are outside bounds");
            if (b + w > m.length) throw new Error("target array is too small to hold result");
            for (let T = 0; T < w; T++) m[b + T] += Math.pow(_[y + T], 2);
          }
          static axpy(m, _, b, y, w, T) {
            if (y < 0 || y >= _.length) throw new Error("sourceIndex out of bounds");
            if (b < 0 || b >= m.length) throw new Error("targetIndex out of bounds");
            if (y + w > _.length) throw new Error("source indices to be copied are outside bounds");
            if (b + w > m.length) throw new Error("target array is too small to hold result");
            for (let S = 0; S < w; S++) m[b + S] += T * _[y + S];
          }
          static powx(m, _, b, y, w, T) {
            if (y < 0 || y >= _.length) throw new Error("sourceIndex out of bounds");
            if (b < 0 || b >= m.length) throw new Error("targetIndex out of bounds");
            if (y + w > _.length) throw new Error("source indices to be copied are outside bounds");
            if (b + w > m.length) throw new Error("target array is too small to hold result");
            for (let S = 0; S < w; S++) m[b + S] = Math.pow(_[y + S], T);
          }
          static mul(m, _, b, y, w) {
            if (y < 0 || y >= _.length) throw new Error("sourceIndex out of bounds");
            if (b < 0 || b >= m.length) throw new Error("targetIndex out of bounds");
            if (y + w > _.length) throw new Error("source indices to be copied are outside bounds");
            if (b + w > m.length) throw new Error("target array is too small to hold result");
            for (let T = 0; T < w; T++) m[b + T] = _[y + T] * m[b + T];
          }
        };
        class r {
          static splitShape(_, b, y, w) {
            if (y.length === 0) {
              if (!w) throw new Error("need to know number of outputs when the 'split' attribute is not specified");
              r.determineSplit(_[b], w, y);
            }
            const T = [], S = [0];
            for (let E = 0; E < y.length; ++E) {
              E !== 0 && S.push(S[E - 1] + y[E - 1]);
              const O = _.slice();
              O[b] = y[E], T.push(O);
            }
            return [T, S];
          }
          static determineSplit(_, b, y) {
            if (_ % b != 0) throw new Error("cannot split tensor to equal sized parts");
            for (let w = 0; w < b; ++w) y.push(_ / b);
          }
        }
        n.SplitUtil = r;
        class i {
          static calcReduce(_, b, y, w, T) {
            const S = _.dims.slice(0);
            b.length === 0 && S.forEach(((B, F) => b.push(F)));
            const E = i.calcReduceShape(S, b, !0), O = e.size(E), v = new f.Tensor(E, _.type), A = e.computeStrides(E), L = e.computeStrides(S), j = new Array(S.length);
            for (let B = 0; B < O; B++) {
              const F = e.offsetToIndices(B, A);
              c.fillIndex(F, S, j), v.set(F, i.calcReduceByAxis(_.numberData, b, S, 0, e.indicesToOffset(j, L), w, T));
            }
            return y ? v : new f.Tensor(i.calcReduceShape(S, b, y), v.type, void 0, void 0, v.data, v.dataId);
          }
          static calcReduceByAxis(_, b, y, w, T, S, E) {
            let O = 0;
            if (w >= b.length) return S(_[T]);
            const v = b[w], A = v >= y.length ? 1 : e.size(y.slice(v + 1));
            for (let L = 0; L < y[v]; L++) O = L === 0 ? i.calcReduceByAxis(_, b, y, w + 1, T, S, E) : E(O, i.calcReduceByAxis(_, b, y, w + 1, T, S, E)), T += A;
            return O;
          }
          static calcReduceShape(_, b, y) {
            const w = _.slice();
            for (let T = 0; T < b.length; T++) w[b[T]] = y ? 1 : 0;
            return w.filter(((T) => T !== 0));
          }
        }
        n.ReduceUtil = i;
        class p {
          static adjustPoolAttributes(_, b, y, w, T, S) {
            if (!_ && y.length !== b.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");
            if (_) for (let E = 0; E < b.length - 2; E++) E >= y.length ? y.push(b[E + 2]) : y[E] = b[E + 2];
            for (let E = 0; E < y.length; E++) if (E < w.length) {
              if (w[E] < 0) throw new Error("strides should be greater than or equal to 1");
            } else w.push(1);
            for (let E = 0; E < y.length; E++) if (E < T.length) {
              if (T[E] < 0) throw new Error("dilations should be greater than or equal to 1");
            } else T.push(1);
            for (let E = 0; E < 2 * y.length; E++) if (E < S.length) {
              if (S[E] < 0) throw new Error("pad should be greater than or equal to 1");
            } else S.push(0);
            for (let E = 0; E < y.length; E++) {
              if (y[E] <= 0) throw new Error("kernel shapes need to be greater than 0");
              if (S[E] >= y[E] || S[E + y.length] >= y[E]) throw new Error("pads should be smaller than kernel");
            }
          }
          static adjustPadsBasedOnAutoPad(_, b, y, w, T, S) {
            if (S) {
              if (T.length !== 2 * (_.length - 2)) throw new Error("length of pads should be twice the length of data dimensions");
              if (b.length !== _.length - 2) throw new Error("length of strides should be the length of data dimensions");
              if (w.length !== _.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions");
              for (let E = 0; E < _.length - 2; E++) p.adjustPadAndReturnShape(_[E + 2], b[E], y[E], w[E], T, E, E + _.length - 2, S);
            }
          }
          static computePoolOutputShape(_, b, y, w, T, S, E) {
            if (b.length <= 0) throw new Error("input shape must be of size greater than 0");
            const O = [b[0], b[1]];
            return p.computeShapeHelper(_, b, O, y, w, T, S, E), O;
          }
          static computeConvOutputShape(_, b, y, w, T, S, E) {
            if (_.length <= 0 || b.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims");
            const O = [_[0], b[0]];
            return p.computeShapeHelper(!1, _, O, y, w, T, S, E), O;
          }
          static computeShapeHelper(_, b, y, w, T, S, E, O) {
            if (_) for (let v = 0; v < b.length - 2; v++) y.push(1);
            else for (let v = 0; v < b.length - 2; v++) y.push(p.adjustPadAndReturnShape(b[v + 2], w[v], T[v], S[v], E, v, v + b.length - 2, O));
          }
          static adjustPadAndReturnShape(_, b, y, w, T, S, E, O) {
            const v = y * (w - 1) + 1;
            if (!O || O === "NOTSET") return Math.floor((_ + T[S] + T[E] - v) / b + 1);
            switch (O) {
              case "VALID":
                return T[S] = 0, T[E] = 0, Math.floor((_ - v) / b + 1);
              case "SAME_LOWER":
              case "SAME_UPPER":
                if (y !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");
                {
                  const A = ((_ + b - 1) / b - 1) * b + w - _;
                  return T[S] = Math.floor(O === "SAME_LOWER" ? (A + 1) / 2 : A / 2), T[E] = A - T[S], Math.floor((_ + A - w) / b + 1);
                }
              default:
                throw new Error("Unsupported AutoPad type");
            }
          }
        }
        n.PoolConvUtil = p, n.MIN_CLIP = -34028234663852886e22, n.MAX_CLIP = 34028234663852886e22, n.decodeUtf8String = function(m) {
          return new TextDecoder().decode(m);
        };
      }, 7967: (d, n) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.iterateExtraOptions = void 0, n.iterateExtraOptions = (o, u, l, h) => {
          if (typeof o == "object" && o !== null) {
            if (l.has(o)) throw new Error("Circular reference in options");
            l.add(o);
          }
          Object.entries(o).forEach((([a, f]) => {
            const g = u ? u + a : a;
            if (typeof f == "object") (0, n.iterateExtraOptions)(f, g + ".", l, h);
            else if (typeof f == "string" || typeof f == "number") h(g, f.toString());
            else {
              if (typeof f != "boolean") throw new Error("Can't handle extra config type: " + typeof f);
              h(g, f ? "1" : "0");
            }
          }));
        };
      }, 2157: function(d, n, o) {
        var u, l = this && this.__createBinding || (Object.create ? function(A, L, j, B) {
          B === void 0 && (B = j);
          var F = Object.getOwnPropertyDescriptor(L, j);
          F && !("get" in F ? !L.__esModule : F.writable || F.configurable) || (F = { enumerable: !0, get: function() {
            return L[j];
          } }), Object.defineProperty(A, B, F);
        } : function(A, L, j, B) {
          B === void 0 && (B = j), A[B] = L[j];
        }), h = this && this.__setModuleDefault || (Object.create ? function(A, L) {
          Object.defineProperty(A, "default", { enumerable: !0, value: L });
        } : function(A, L) {
          A.default = L;
        }), a = this && this.__importStar || function(A) {
          if (A && A.__esModule) return A;
          var L = {};
          if (A != null) for (var j in A) j !== "default" && Object.prototype.hasOwnProperty.call(A, j) && l(L, A, j);
          return h(L, A), L;
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), n.endProfiling = n.run = n.releaseSession = n.createSession = n.createSessionFinalize = n.createSessionAllocate = n.initOrt = n.initWasm = void 0;
        const f = o(1670), g = a(o(349)), c = o(6361), s = () => !!f.env.wasm.proxy && typeof document < "u";
        let t, e, r, i = !1, p = !1, m = !1;
        const _ = [], b = [], y = [], w = [], T = [], S = [], E = () => {
          if (i || !p || m || !t) throw new Error("worker not ready");
        }, O = (A) => {
          switch (A.data.type) {
            case "init-wasm":
              i = !1, A.data.err ? (m = !0, e[1](A.data.err)) : (p = !0, e[0]());
              break;
            case "init-ort":
              A.data.err ? r[1](A.data.err) : r[0]();
              break;
            case "create_allocate":
              A.data.err ? _.shift()[1](A.data.err) : _.shift()[0](A.data.out);
              break;
            case "create_finalize":
              A.data.err ? b.shift()[1](A.data.err) : b.shift()[0](A.data.out);
              break;
            case "create":
              A.data.err ? y.shift()[1](A.data.err) : y.shift()[0](A.data.out);
              break;
            case "release":
              A.data.err ? w.shift()[1](A.data.err) : w.shift()[0]();
              break;
            case "run":
              A.data.err ? T.shift()[1](A.data.err) : T.shift()[0](A.data.out);
              break;
            case "end-profiling":
              A.data.err ? S.shift()[1](A.data.err) : S.shift()[0]();
          }
        }, v = typeof document < "u" ? (u = document?.currentScript) === null || u === void 0 ? void 0 : u.src : void 0;
        n.initWasm = async () => {
          if (s()) {
            if (p) return;
            if (i) throw new Error("multiple calls to 'initWasm()' detected.");
            if (m) throw new Error("previous call to 'initWasm()' failed.");
            return i = !0, f.env.wasm.wasmPaths === void 0 && v && v.indexOf("blob:") !== 0 && (f.env.wasm.wasmPaths = v.substr(0, +v.lastIndexOf("/") + 1)), new Promise(((A, L) => {
              t?.terminate(), t = o(9710).Z(), t.onmessage = O, e = [A, L];
              const j = { type: "init-wasm", in: f.env.wasm };
              t.postMessage(j);
            }));
          }
          return (0, c.initializeWebAssembly)(f.env.wasm);
        }, n.initOrt = async (A, L) => {
          if (s()) return E(), new Promise(((j, B) => {
            r = [j, B];
            const F = { type: "init-ort", in: { numThreads: A, loggingLevel: L } };
            t.postMessage(F);
          }));
          g.initOrt(A, L);
        }, n.createSessionAllocate = async (A) => s() ? (E(), new Promise(((L, j) => {
          _.push([L, j]);
          const B = { type: "create_allocate", in: { model: A } };
          t.postMessage(B, [A.buffer]);
        }))) : g.createSessionAllocate(A), n.createSessionFinalize = async (A, L) => s() ? (E(), new Promise(((j, B) => {
          b.push([j, B]);
          const F = { type: "create_finalize", in: { modeldata: A, options: L } };
          t.postMessage(F);
        }))) : g.createSessionFinalize(A, L), n.createSession = async (A, L) => s() ? (E(), new Promise(((j, B) => {
          y.push([j, B]);
          const F = { type: "create", in: { model: A, options: L } };
          t.postMessage(F, [A.buffer]);
        }))) : g.createSession(A, L), n.releaseSession = async (A) => {
          if (s()) return E(), new Promise(((L, j) => {
            w.push([L, j]);
            const B = { type: "release", in: A };
            t.postMessage(B);
          }));
          g.releaseSession(A);
        }, n.run = async (A, L, j, B, F) => s() ? (E(), new Promise(((D, I) => {
          T.push([D, I]);
          const $ = { type: "run", in: { sessionId: A, inputIndices: L, inputs: j, outputIndices: B, options: F } };
          t.postMessage($, g.extractTransferableBuffers(j));
        }))) : g.run(A, L, j, B, F), n.endProfiling = async (A) => {
          if (s()) return E(), new Promise(((L, j) => {
            S.push([L, j]);
            const B = { type: "end-profiling", in: A };
            t.postMessage(B);
          }));
          g.endProfiling(A);
        };
      }, 586: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.setRunOptions = void 0;
        const u = o(7967), l = o(4983), h = o(6361);
        n.setRunOptions = (a) => {
          const f = (0, h.getInstance)();
          let g = 0;
          const c = [], s = a || {};
          try {
            if (a?.logSeverityLevel === void 0) s.logSeverityLevel = 2;
            else if (typeof a.logSeverityLevel != "number" || !Number.isInteger(a.logSeverityLevel) || a.logSeverityLevel < 0 || a.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${a.logSeverityLevel}`);
            if (a?.logVerbosityLevel === void 0) s.logVerbosityLevel = 0;
            else if (typeof a.logVerbosityLevel != "number" || !Number.isInteger(a.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);
            a?.terminate === void 0 && (s.terminate = !1);
            let t = 0;
            if (a?.tag !== void 0 && (t = (0, l.allocWasmString)(a.tag, c)), g = f._OrtCreateRunOptions(s.logSeverityLevel, s.logVerbosityLevel, !!s.terminate, t), g === 0) throw new Error("Can't create run options");
            return a?.extra !== void 0 && (0, u.iterateExtraOptions)(a.extra, "", /* @__PURE__ */ new WeakSet(), ((e, r) => {
              const i = (0, l.allocWasmString)(e, c), p = (0, l.allocWasmString)(r, c);
              if (f._OrtAddRunConfigEntry(g, i, p) !== 0) throw new Error(`Can't set a run config entry: ${e} - ${r}`);
            })), [g, c];
          } catch (t) {
            throw g !== 0 && f._OrtReleaseRunOptions(g), c.forEach(f._free), t;
          }
        };
      }, 2306: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.OnnxruntimeWebAssemblySessionHandler = void 0;
        const u = o(2806), l = o(1670), h = o(2850), a = o(2157);
        let f;
        n.OnnxruntimeWebAssemblySessionHandler = class {
          async createSessionAllocate(g) {
            const c = await fetch(g), s = await c.arrayBuffer();
            return (0, a.createSessionAllocate)(new Uint8Array(s));
          }
          async loadModel(g, c) {
            if (f || (await (0, a.initOrt)(l.env.wasm.numThreads, ((s) => {
              switch (s) {
                case "verbose":
                  return 0;
                case "info":
                  return 1;
                case "warning":
                  return 2;
                case "error":
                  return 3;
                case "fatal":
                  return 4;
                default:
                  throw new Error(`unsupported logging level: ${s}`);
              }
            })(l.env.logLevel)), f = !0), typeof g == "string") if (typeof fetch > "u") {
              const s = await (0, h.promisify)(u.readFile)(g);
              [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(s, c);
            } else {
              const s = await this.createSessionAllocate(g);
              [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSessionFinalize)(s, c);
            }
            else [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(g, c);
          }
          async dispose() {
            return (0, a.releaseSession)(this.sessionId);
          }
          async run(g, c, s) {
            const t = [], e = [];
            Object.entries(g).forEach(((m) => {
              const _ = m[0], b = m[1], y = this.inputNames.indexOf(_);
              if (y === -1) throw new Error(`invalid input '${_}'`);
              t.push(b), e.push(y);
            }));
            const r = [];
            Object.entries(c).forEach(((m) => {
              const _ = m[0], b = this.outputNames.indexOf(_);
              if (b === -1) throw new Error(`invalid output '${_}'`);
              r.push(b);
            }));
            const i = await (0, a.run)(this.sessionId, e, t.map(((m) => [m.type, m.dims, m.data])), r, s), p = {};
            for (let m = 0; m < i.length; m++) p[this.outputNames[r[m]]] = new l.Tensor(i[m][0], i[m][2], i[m][1]);
            return p;
          }
          startProfiling() {
          }
          endProfiling() {
            (0, a.endProfiling)(this.sessionId);
          }
        };
      }, 4919: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.setSessionOptions = void 0;
        const u = o(7967), l = o(4983), h = o(6361);
        n.setSessionOptions = (a) => {
          const f = (0, h.getInstance)();
          let g = 0;
          const c = [], s = a || {};
          ((t) => {
            t.extra || (t.extra = {}), t.extra.session || (t.extra.session = {});
            const e = t.extra.session;
            e.use_ort_model_bytes_directly || (e.use_ort_model_bytes_directly = "1");
          })(s);
          try {
            a?.graphOptimizationLevel === void 0 && (s.graphOptimizationLevel = "all");
            const t = ((i) => {
              switch (i) {
                case "disabled":
                  return 0;
                case "basic":
                  return 1;
                case "extended":
                  return 2;
                case "all":
                  return 99;
                default:
                  throw new Error(`unsupported graph optimization level: ${i}`);
              }
            })(s.graphOptimizationLevel);
            a?.enableCpuMemArena === void 0 && (s.enableCpuMemArena = !0), a?.enableMemPattern === void 0 && (s.enableMemPattern = !0), a?.executionMode === void 0 && (s.executionMode = "sequential");
            const e = ((i) => {
              switch (i) {
                case "sequential":
                  return 0;
                case "parallel":
                  return 1;
                default:
                  throw new Error(`unsupported execution mode: ${i}`);
              }
            })(s.executionMode);
            let r = 0;
            if (a?.logId !== void 0 && (r = (0, l.allocWasmString)(a.logId, c)), a?.logSeverityLevel === void 0) s.logSeverityLevel = 2;
            else if (typeof a.logSeverityLevel != "number" || !Number.isInteger(a.logSeverityLevel) || a.logSeverityLevel < 0 || a.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${a.logSeverityLevel}`);
            if (a?.logVerbosityLevel === void 0) s.logVerbosityLevel = 0;
            else if (typeof a.logVerbosityLevel != "number" || !Number.isInteger(a.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);
            if (a?.enableProfiling === void 0 && (s.enableProfiling = !1), g = f._OrtCreateSessionOptions(t, !!s.enableCpuMemArena, !!s.enableMemPattern, e, !!s.enableProfiling, 0, r, s.logSeverityLevel, s.logVerbosityLevel), g === 0) throw new Error("Can't create session options");
            return a?.executionProviders && ((i, p, m) => {
              for (const _ of p) {
                let b = typeof _ == "string" ? _ : _.name;
                switch (b) {
                  case "xnnpack":
                    b = "XNNPACK";
                    break;
                  case "wasm":
                  case "cpu":
                    continue;
                  default:
                    throw new Error(`not supported EP: ${b}`);
                }
                const y = (0, l.allocWasmString)(b, m);
                if ((0, h.getInstance)()._OrtAppendExecutionProvider(i, y) !== 0) throw new Error(`Can't append execution provider: ${b}`);
              }
            })(g, a.executionProviders, c), a?.extra !== void 0 && (0, u.iterateExtraOptions)(a.extra, "", /* @__PURE__ */ new WeakSet(), ((i, p) => {
              const m = (0, l.allocWasmString)(i, c), _ = (0, l.allocWasmString)(p, c);
              if (f._OrtAddSessionConfigEntry(g, m, _) !== 0) throw new Error(`Can't set a session config entry: ${i} - ${p}`);
            })), [g, c];
          } catch (t) {
            throw g !== 0 && f._OrtReleaseSessionOptions(g), c.forEach(f._free), t;
          }
        };
      }, 4983: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.allocWasmString = void 0;
        const u = o(6361);
        n.allocWasmString = (l, h) => {
          const a = (0, u.getInstance)(), f = a.lengthBytesUTF8(l) + 1, g = a._malloc(f);
          return a.stringToUTF8(l, g, f), h.push(g), g;
        };
      }, 349: (d, n, o) => {
        Object.defineProperty(n, "__esModule", { value: !0 }), n.extractTransferableBuffers = n.endProfiling = n.run = n.releaseSession = n.createSession = n.createSessionFinalize = n.createSessionAllocate = n.initOrt = void 0;
        const u = o(586), l = o(4919), h = o(4983), a = o(6361);
        n.initOrt = (t, e) => {
          const r = (0, a.getInstance)()._OrtInit(t, e);
          if (r !== 0) throw new Error(`Can't initialize onnxruntime. error code = ${r}`);
        };
        const f = /* @__PURE__ */ new Map();
        n.createSessionAllocate = (t) => {
          const e = (0, a.getInstance)(), r = e._malloc(t.byteLength);
          return e.HEAPU8.set(t, r), [r, t.byteLength];
        }, n.createSessionFinalize = (t, e) => {
          const r = (0, a.getInstance)();
          let i = 0, p = 0, m = [];
          try {
            if ([p, m] = (0, l.setSessionOptions)(e), i = r._OrtCreateSession(t[0], t[1], p), i === 0) throw new Error("Can't create a session");
          } finally {
            r._free(t[0]), r._OrtReleaseSessionOptions(p), m.forEach(r._free);
          }
          const _ = r._OrtGetInputCount(i), b = r._OrtGetOutputCount(i), y = [], w = [], T = [], S = [];
          for (let E = 0; E < _; E++) {
            const O = r._OrtGetInputName(i, E);
            if (O === 0) throw new Error("Can't get an input name");
            w.push(O), y.push(r.UTF8ToString(O));
          }
          for (let E = 0; E < b; E++) {
            const O = r._OrtGetOutputName(i, E);
            if (O === 0) throw new Error("Can't get an output name");
            S.push(O), T.push(r.UTF8ToString(O));
          }
          return f.set(i, [i, w, S]), [i, y, T];
        }, n.createSession = (t, e) => {
          const r = (0, n.createSessionAllocate)(t);
          return (0, n.createSessionFinalize)(r, e);
        }, n.releaseSession = (t) => {
          const e = (0, a.getInstance)(), r = f.get(t);
          if (!r) throw new Error("invalid session id");
          const i = r[0], p = r[1], m = r[2];
          p.forEach(e._OrtFree), m.forEach(e._OrtFree), e._OrtReleaseSession(i), f.delete(t);
        };
        const g = (t) => {
          switch (t) {
            case "int8":
              return 3;
            case "uint8":
              return 2;
            case "bool":
              return 9;
            case "int16":
              return 5;
            case "uint16":
              return 4;
            case "int32":
              return 6;
            case "uint32":
              return 12;
            case "float32":
              return 1;
            case "float64":
              return 11;
            case "string":
              return 8;
            case "int64":
              return 7;
            case "uint64":
              return 13;
            default:
              throw new Error(`unsupported data type: ${t}`);
          }
        }, c = (t) => {
          switch (t) {
            case 3:
              return "int8";
            case 2:
              return "uint8";
            case 9:
              return "bool";
            case 5:
              return "int16";
            case 4:
              return "uint16";
            case 6:
              return "int32";
            case 12:
              return "uint32";
            case 1:
              return "float32";
            case 11:
              return "float64";
            case 8:
              return "string";
            case 7:
              return "int64";
            case 13:
              return "uint64";
            default:
              throw new Error(`unsupported data type: ${t}`);
          }
        }, s = (t) => {
          switch (t) {
            case "float32":
              return Float32Array;
            case "uint8":
            case "bool":
              return Uint8Array;
            case "int8":
              return Int8Array;
            case "uint16":
              return Uint16Array;
            case "int16":
              return Int16Array;
            case "int32":
              return Int32Array;
            case "float64":
              return Float64Array;
            case "uint32":
              return Uint32Array;
            case "int64":
              return BigInt64Array;
            case "uint64":
              return BigUint64Array;
            default:
              throw new Error(`unsupported type: ${t}`);
          }
        };
        n.run = (t, e, r, i, p) => {
          const m = (0, a.getInstance)(), _ = f.get(t);
          if (!_) throw new Error("invalid session id");
          const b = _[0], y = _[1], w = _[2], T = e.length, S = i.length;
          let E = 0, O = [];
          const v = [], A = [];
          try {
            [E, O] = (0, u.setRunOptions)(p);
            for (let I = 0; I < T; I++) {
              const $ = r[I][0], Q = r[I][1], Y = r[I][2];
              let te, ne;
              if (Array.isArray(Y)) {
                ne = 4 * Y.length, te = m._malloc(ne), A.push(te);
                let Ee = te / 4;
                for (let ce = 0; ce < Y.length; ce++) {
                  if (typeof Y[ce] != "string") throw new TypeError(`tensor data at index ${ce} is not a string`);
                  m.HEAPU32[Ee++] = (0, h.allocWasmString)(Y[ce], A);
                }
              } else ne = Y.byteLength, te = m._malloc(ne), A.push(te), m.HEAPU8.set(new Uint8Array(Y.buffer, Y.byteOffset, ne), te);
              const me = m.stackSave(), Ae = m.stackAlloc(4 * Q.length);
              try {
                let Ee = Ae / 4;
                Q.forEach(((ve) => m.HEAP32[Ee++] = ve));
                const ce = m._OrtCreateTensor(g($), te, ne, Ae, Q.length);
                if (ce === 0) throw new Error("Can't create a tensor");
                v.push(ce);
              } finally {
                m.stackRestore(me);
              }
            }
            const L = m.stackSave(), j = m.stackAlloc(4 * T), B = m.stackAlloc(4 * T), F = m.stackAlloc(4 * S), D = m.stackAlloc(4 * S);
            try {
              let I = j / 4, $ = B / 4, Q = F / 4, Y = D / 4;
              for (let me = 0; me < T; me++) m.HEAPU32[I++] = v[me], m.HEAPU32[$++] = y[e[me]];
              for (let me = 0; me < S; me++) m.HEAPU32[Q++] = 0, m.HEAPU32[Y++] = w[i[me]];
              let te = m._OrtRun(b, B, j, T, D, S, F, E);
              const ne = [];
              if (te === 0) for (let me = 0; me < S; me++) {
                const Ae = m.HEAPU32[F / 4 + me], Ee = m.stackSave(), ce = m.stackAlloc(16);
                let ve, ye = 0;
                try {
                  if (te = m._OrtGetTensorData(Ae, ce, ce + 4, ce + 8, ce + 12), te !== 0) throw new Error(`Can't access output tensor data. error code = ${te}`);
                  let Le = ce / 4;
                  const We = m.HEAPU32[Le++];
                  ye = m.HEAPU32[Le++];
                  const Oe = m.HEAPU32[Le++], Ne = m.HEAPU32[Le++], Ce = [];
                  for (let Te = 0; Te < Ne; Te++) Ce.push(m.HEAPU32[Oe / 4 + Te]);
                  m._OrtFree(Oe);
                  const Pe = Ce.length === 0 ? 1 : Ce.reduce(((Te, Be) => Te * Be));
                  if (ve = c(We), ve === "string") {
                    const Te = [];
                    let Be = ye / 4;
                    for (let Ve = 0; Ve < Pe; Ve++) {
                      const ze = m.HEAPU32[Be++], He = Ve === Pe - 1 ? void 0 : m.HEAPU32[Be] - ze;
                      Te.push(m.UTF8ToString(ze, He));
                    }
                    ne.push([ve, Ce, Te]);
                  } else {
                    const Te = new (s(ve))(Pe);
                    new Uint8Array(Te.buffer, Te.byteOffset, Te.byteLength).set(m.HEAPU8.subarray(ye, ye + Te.byteLength)), ne.push([ve, Ce, Te]);
                  }
                } finally {
                  m.stackRestore(Ee), ve === "string" && ye && m._free(ye), m._OrtReleaseTensor(Ae);
                }
              }
              if (te === 0) return ne;
              throw new Error(`failed to call OrtRun(). error code = ${te}.`);
            } finally {
              m.stackRestore(L);
            }
          } finally {
            v.forEach(m._OrtReleaseTensor), A.forEach(m._free), m._OrtReleaseRunOptions(E), O.forEach(m._free);
          }
        }, n.endProfiling = (t) => {
          const e = (0, a.getInstance)(), r = f.get(t);
          if (!r) throw new Error("invalid session id");
          const i = r[0], p = e._OrtEndProfiling(i);
          if (p === 0) throw new Error("Can't get an profile file name");
          e._OrtFree(p);
        }, n.extractTransferableBuffers = (t) => {
          const e = [];
          for (const r of t) {
            const i = r[2];
            !Array.isArray(i) && i.buffer && e.push(i.buffer);
          }
          return e;
        };
      }, 6361: function(d, n, o) {
        var u = this && this.__createBinding || (Object.create ? function(p, m, _, b) {
          b === void 0 && (b = _);
          var y = Object.getOwnPropertyDescriptor(m, _);
          y && !("get" in y ? !m.__esModule : y.writable || y.configurable) || (y = { enumerable: !0, get: function() {
            return m[_];
          } }), Object.defineProperty(p, b, y);
        } : function(p, m, _, b) {
          b === void 0 && (b = _), p[b] = m[_];
        }), l = this && this.__setModuleDefault || (Object.create ? function(p, m) {
          Object.defineProperty(p, "default", { enumerable: !0, value: m });
        } : function(p, m) {
          p.default = m;
        }), h = this && this.__importStar || function(p) {
          if (p && p.__esModule) return p;
          var m = {};
          if (p != null) for (var _ in p) _ !== "default" && Object.prototype.hasOwnProperty.call(p, _) && u(m, p, _);
          return l(m, p), m;
        }, a = this && this.__importDefault || function(p) {
          return p && p.__esModule ? p : { default: p };
        };
        Object.defineProperty(n, "__esModule", { value: !0 }), n.dispose = n.getInstance = n.initializeWebAssembly = void 0;
        const f = h(o(6449)), g = a(o(932)), c = o(3474);
        let s, t = !1, e = !1, r = !1;
        const i = (p, m) => m ? p ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-threaded.wasm" : p ? "ort-wasm-simd.wasm" : "ort-wasm.wasm";
        n.initializeWebAssembly = async (p) => {
          if (t) return Promise.resolve();
          if (e) throw new Error("multiple calls to 'initializeWebAssembly()' detected.");
          if (r) throw new Error("previous call to 'initializeWebAssembly()' failed.");
          e = !0;
          const m = p.initTimeout, _ = p.numThreads, b = p.simd, y = _ > 1 && (() => {
            try {
              return typeof SharedArrayBuffer < "u" && (typeof MessageChannel < "u" && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11])));
            } catch {
              return !1;
            }
          })(), w = b && (() => {
            try {
              return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11]));
            } catch {
              return !1;
            }
          })(), T = typeof p.wasmPaths == "string" ? p.wasmPaths : void 0, S = i(!1, y), E = i(w, y), O = typeof p.wasmPaths == "object" ? p.wasmPaths[E] : void 0;
          let v = !1;
          const A = [];
          if (m > 0 && A.push(new Promise(((L) => {
            setTimeout((() => {
              v = !0, L();
            }), m);
          }))), A.push(new Promise(((L, j) => {
            const B = y ? c : g.default, F = { locateFile: (D, I) => y && D.endsWith(".worker.js") && typeof Blob < "u" ? URL.createObjectURL(new Blob([o(4154)], { type: "text/javascript" })) : D === S ? O ?? (T ?? I) + E : I + D };
            if (y) if (typeof Blob > "u") F.mainScriptUrlOrBlob = f.join("/", "ort-wasm-threaded.js");
            else {
              const D = `var ortWasmThreaded=(function(){var _scriptDir;return ${B.toString()}})();`;
              F.mainScriptUrlOrBlob = new Blob([D], { type: "text/javascript" });
            }
            B(F).then(((D) => {
              e = !1, t = !0, s = D, L();
            }), ((D) => {
              e = !1, r = !0, j(D);
            }));
          }))), await Promise.race(A), v) throw new Error(`WebAssembly backend initializing failed due to timeout: ${m}ms`);
        }, n.getInstance = () => {
          if (t && s) return s;
          throw new Error("WebAssembly is not initialized yet.");
        }, n.dispose = () => {
          var p;
          !t || e || r || (e = !0, (p = s.PThread) === null || p === void 0 || p.terminateAllThreads(), s = void 0, e = !1, t = !1, r = !0);
        };
      }, 9710: (d, n, o) => {
        o.d(n, { Z: () => h });
        var u = o(477), l = o.n(u);
        function h() {
          return l()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(m=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof ct))throw t})),process.on("unhandledRejection",(function(t){throw t})),g=(t,e)=>{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&L)return L.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0<t.length;)t.shift()(u)}function yt(t){var e=Ee();return t=t(),Me(e),t}function bt(t){if(O)return $t(2,0,t);try{pt(t)}catch(t){t instanceof ct||"unwind"==t||g(1,t)}}u.PThread=ht,u.establishStackSpace=function(){var t=he(),e=a()[t+44>>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s<o?(i()[n>>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u<n;u++){var c=r[2+u];o()[i+u>>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u<a.length;++u)e()[o++>>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u<n;u++){var c=i()[e>>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l<s;l++)ae(t,r()[c+l>>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function u(t,e){return o(t,e,"0")}function c(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function s(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function l(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ue(t.getFullYear())?ce:se)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12<t&&(t-=12),u(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(ue(t.Xb+1900)?ce:se)[n++]);return u(t.jc+e,3)},"%m":function(t){return u(t.ec+1,2)},"%M":function(t){return u(t.Kc,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.dc&&12>t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&gt(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},l:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},h:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},t:Tt,M:function(){var t=_t.pop();t||at("no exception to throw");var e=t.Zb;throw t.kc()||(_t.push(t),t.ic(!0),t.hc(!1),Ot++),At=e,e},c:function(t,e,n){throw new St(t).fc(e,n),At=t,Ot++,t},pa:function(){return Ot},Fa:function(t){ge(t,!w,1,!v),ht.pc()},T:function(t){O?postMessage({cmd:"cleanupThread",thread:t}):st(t)},xa:Mt,j:function(t){throw At||(At=t),t},H:Ct,Ma:xt,ua:Rt,wa:jt,oa:kt,Ka:Dt,Ca:Pt,Ja:Ut,V:Ft,va:It,sa:Wt,La:Ht,ta:Lt,Ta:function(){},X:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout((()=>zt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0<n!=(c==r)&&(o=Math.max(u,o),e.setTime(e.getTime()+6e4*((0<n?c:o)-r))),a()[t+24>>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r<e;r++)Xt[r]=o()[n+r>>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760<t)return!1;for(var n=1;4>=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i<a;i++)e()[r+i>>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0<et))if(O)c(u),O||dt(X),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)K();dt(q),0<et||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),t()}),1)):t())}}if(u.UTF8ToString=Y,u.stringToUTF8=function(t,e,n){return B(t,r(),e,n)},u.lengthBytesUTF8=G,u.keepRuntimeAlive=Q,u.wasmMemory=j,u.stackSave=Ee,u.stackRestore=Me,u.stackAlloc=Ce,u.ExitStatus=ct,u.PThread=ht,rt=function t(){ve||ze(),ve||(rt=t)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return ze(),t.ready});t.exports=r},932:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof J))throw t})),process.on("unhandledRejection",(function(t){throw t})),h=(t,e)=>{if(_||0<L)throw process.exitCode=t,e;e instanceof J||w("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(d||y)&&(y?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),_scriptDir&&(m=_scriptDir),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&x)return x.decode(t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0<t.length;)t.shift()(e)}var Q=[],K=0,tt=0;function et(t){this.Db=t,this.zb=t-24,this.Ub=function(t){M[this.zb+4>>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function i(t,e){return a(t,e,"0")}function o(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function u(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function c(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(pt(t.getFullYear())?ht:dt)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12<t&&(t-=12),i(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(pt(t.Cb+1900)?ht:dt)[n++]);return i(t.Kb+e,3)},"%m":function(t){return i(t.Hb+1,2)},"%M":function(t){return i(t.Zb,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.Gb&&12>t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},k:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},g:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},s:nt,L:function(){var t=Q.pop();t||V("no exception to throw");var e=t.Db;throw t.Lb()||(Q.push(t),t.Jb(!0),t.Ib(!1),K++),tt=e,e},b:function(t,e,n){throw new et(t).Rb(e,n),tt=t,K++,t},la:function(){return K},i:function(t){throw tt||(tt=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0<n!=(u==r)&&(i=Math.max(o,i),e.setTime(e.getTime()+6e4*((0<n?u:i)-r))),E[t+24>>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u<a?(M[n>>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i<r.length;++i)S[a++>>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0<L||(_t(),Z(W),wt(0),st[1].length&&lt(1,10),st[2].length&&lt(2,10)),_||0<L||(e.onExit&&e.onExit(t),C=!0),h(t,new J(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var a=0,i=0;i<n;i++){var o=M[e>>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c<u;c++)lt(t,T[o+c>>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a<r;a++)S[e+a>>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0<B)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)z();Z(F),0<B||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),t()}),1)):t())}}if(e.UTF8ToString=j,e.stringToUTF8=function(t,e,n){return k(t,T,e,n)},e.lengthBytesUTF8=D,e.stackSave=At,e.stackRestore=St,e.stackAlloc=Tt,N=function t(){mt||Wt(),mt||(N=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return Wt(),t.ready});t.exports=r},967:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t<s;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can\'t get an input name");p.push(e),f.push(n.UTF8ToString(e))}for(let t=0;t<l;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can\'t get an output name");d.push(e),h.push(n.UTF8ToString(e))}return u.set(r,[r,p,d]),[r,f,h]},e.createSession=(t,n)=>{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;t<m;t++){const e=n[t][0],r=n[t][1],a=n[t][2];let o,u;if(Array.isArray(a)){u=4*a.length,o=p._malloc(u),O.push(o);let t=o/4;for(let e=0;e<a.length;e++){if("string"!=typeof a[e])throw new TypeError(`tensor data at index ${e} is not a string`);p.HEAPU32[t++]=(0,i.allocWasmString)(a[e],O)}}else u=a.byteLength,o=p._malloc(u),O.push(o),p.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),o);const s=p.stackSave(),l=p.stackAlloc(4*r.length);try{let t=l/4;r.forEach((e=>p.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;t<m;t++)p.HEAPU32[n++]=_[t],p.HEAPU32[r++]=y[e[t]];for(let t=0;t<g;t++)p.HEAPU32[i++]=0,p.HEAPU32[c++]=b[a[t]];let f=p._OrtRun(d,u,o,m,A,g,h,v);const w=[];if(0===f)for(let t=0;t<g;t++){const e=p.HEAPU32[h/4+t],n=p.stackSave(),r=p.stackAlloc(16);let a,i=0;try{if(f=p._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==f)throw new Error(`Can\'t access output tensor data. error code = ${f}`);let t=r/4;const o=p.HEAPU32[t++];i=p.HEAPU32[t++];const u=p.HEAPU32[t++],c=p.HEAPU32[t++],h=[];for(let t=0;t<c;t++)h.push(p.HEAPU32[u/4+t]);p._OrtFree(u);const d=0===h.length?1:h.reduce(((t,e)=>t*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n<d;n++){const r=p.HEAPU32[e++],a=n===d-1?void 0:p.HEAPU32[e]-r;t.push(p.UTF8ToString(r,a))}w.push([a,h,t])}else{const t=new(l(a))(d);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(p.HEAPU8.subarray(i,i+t.byteLength)),w.push([a,h,t])}}finally{p.stackRestore(n),"string"===a&&i&&p._free(i),p._OrtReleaseTensor(e)}}if(0===f)return w;throw new Error(`failed to call OrtRun(). error code = ${f}.`)}finally{p.stackRestore(t)}}finally{_.forEach(p._OrtReleaseTensor),O.forEach(p._free),p._OrtReleaseRunOptions(v),w.forEach(p._free)}},e.endProfiling=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n', "Worker", void 0, void 0);
        }
      }, 477: (d) => {
        d.exports = function(n, o, u, l) {
          var h = self || window;
          try {
            try {
              var a;
              try {
                a = new h.Blob([n]);
              } catch {
                (a = new (h.BlobBuilder || h.WebKitBlobBuilder || h.MozBlobBuilder || h.MSBlobBuilder)()).append(n), a = a.getBlob();
              }
              var f = h.URL || h.webkitURL, g = f.createObjectURL(a), c = new h[o](g, u);
              return f.revokeObjectURL(g), c;
            } catch {
              return new h[o]("data:application/javascript,".concat(encodeURIComponent(n)), u);
            }
          } catch {
            if (!l) throw Error("Inline worker is not supported");
            return new h[o](l, u);
          }
        };
      }, 4154: (d) => {
        d.exports = `"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};
`;
      }, 1670: (d) => {
        d.exports = __WEBPACK_EXTERNAL_MODULE__1670__;
      }, 7067: () => {
      }, 1296: () => {
      }, 1384: () => {
      }, 3993: () => {
      }, 908: () => {
      }, 6953: () => {
      }, 9925: () => {
      }, 2806: () => {
      }, 6449: () => {
      }, 2850: () => {
      }, 5381: () => {
      }, 5686: (d, n, o) => {
        o.r(n), o.d(n, { flatbuffers: () => u });
        var u = {};
        u.Offset, u.Table, u.SIZEOF_SHORT = 2, u.SIZEOF_INT = 4, u.FILE_IDENTIFIER_LENGTH = 4, u.SIZE_PREFIX_LENGTH = 4, u.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }, u.int32 = new Int32Array(2), u.float32 = new Float32Array(u.int32.buffer), u.float64 = new Float64Array(u.int32.buffer), u.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1, u.Long = function(l, h) {
          this.low = 0 | l, this.high = 0 | h;
        }, u.Long.create = function(l, h) {
          return l == 0 && h == 0 ? u.Long.ZERO : new u.Long(l, h);
        }, u.Long.prototype.toFloat64 = function() {
          return (this.low >>> 0) + 4294967296 * this.high;
        }, u.Long.prototype.equals = function(l) {
          return this.low == l.low && this.high == l.high;
        }, u.Long.ZERO = new u.Long(0, 0), u.Builder = function(l) {
          if (l) h = l;
          else var h = 1024;
          this.bb = u.ByteBuffer.allocate(h), this.space = h, this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = !1, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = !1;
        }, u.Builder.prototype.clear = function() {
          this.bb.clear(), this.space = this.bb.capacity(), this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = !1, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = !1;
        }, u.Builder.prototype.forceDefaults = function(l) {
          this.force_defaults = l;
        }, u.Builder.prototype.dataBuffer = function() {
          return this.bb;
        }, u.Builder.prototype.asUint8Array = function() {
          return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
        }, u.Builder.prototype.prep = function(l, h) {
          l > this.minalign && (this.minalign = l);
          for (var a = 1 + ~(this.bb.capacity() - this.space + h) & l - 1; this.space < a + l + h; ) {
            var f = this.bb.capacity();
            this.bb = u.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - f;
          }
          this.pad(a);
        }, u.Builder.prototype.pad = function(l) {
          for (var h = 0; h < l; h++) this.bb.writeInt8(--this.space, 0);
        }, u.Builder.prototype.writeInt8 = function(l) {
          this.bb.writeInt8(this.space -= 1, l);
        }, u.Builder.prototype.writeInt16 = function(l) {
          this.bb.writeInt16(this.space -= 2, l);
        }, u.Builder.prototype.writeInt32 = function(l) {
          this.bb.writeInt32(this.space -= 4, l);
        }, u.Builder.prototype.writeInt64 = function(l) {
          this.bb.writeInt64(this.space -= 8, l);
        }, u.Builder.prototype.writeFloat32 = function(l) {
          this.bb.writeFloat32(this.space -= 4, l);
        }, u.Builder.prototype.writeFloat64 = function(l) {
          this.bb.writeFloat64(this.space -= 8, l);
        }, u.Builder.prototype.addInt8 = function(l) {
          this.prep(1, 0), this.writeInt8(l);
        }, u.Builder.prototype.addInt16 = function(l) {
          this.prep(2, 0), this.writeInt16(l);
        }, u.Builder.prototype.addInt32 = function(l) {
          this.prep(4, 0), this.writeInt32(l);
        }, u.Builder.prototype.addInt64 = function(l) {
          this.prep(8, 0), this.writeInt64(l);
        }, u.Builder.prototype.addFloat32 = function(l) {
          this.prep(4, 0), this.writeFloat32(l);
        }, u.Builder.prototype.addFloat64 = function(l) {
          this.prep(8, 0), this.writeFloat64(l);
        }, u.Builder.prototype.addFieldInt8 = function(l, h, a) {
          (this.force_defaults || h != a) && (this.addInt8(h), this.slot(l));
        }, u.Builder.prototype.addFieldInt16 = function(l, h, a) {
          (this.force_defaults || h != a) && (this.addInt16(h), this.slot(l));
        }, u.Builder.prototype.addFieldInt32 = function(l, h, a) {
          (this.force_defaults || h != a) && (this.addInt32(h), this.slot(l));
        }, u.Builder.prototype.addFieldInt64 = function(l, h, a) {
          !this.force_defaults && h.equals(a) || (this.addInt64(h), this.slot(l));
        }, u.Builder.prototype.addFieldFloat32 = function(l, h, a) {
          (this.force_defaults || h != a) && (this.addFloat32(h), this.slot(l));
        }, u.Builder.prototype.addFieldFloat64 = function(l, h, a) {
          (this.force_defaults || h != a) && (this.addFloat64(h), this.slot(l));
        }, u.Builder.prototype.addFieldOffset = function(l, h, a) {
          (this.force_defaults || h != a) && (this.addOffset(h), this.slot(l));
        }, u.Builder.prototype.addFieldStruct = function(l, h, a) {
          h != a && (this.nested(h), this.slot(l));
        }, u.Builder.prototype.nested = function(l) {
          if (l != this.offset()) throw new Error("FlatBuffers: struct must be serialized inline.");
        }, u.Builder.prototype.notNested = function() {
          if (this.isNested) throw new Error("FlatBuffers: object serialization must not be nested.");
        }, u.Builder.prototype.slot = function(l) {
          this.vtable[l] = this.offset();
        }, u.Builder.prototype.offset = function() {
          return this.bb.capacity() - this.space;
        }, u.Builder.growByteBuffer = function(l) {
          var h = l.capacity();
          if (3221225472 & h) throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
          var a = h << 1, f = u.ByteBuffer.allocate(a);
          return f.setPosition(a - h), f.bytes().set(l.bytes(), a - h), f;
        }, u.Builder.prototype.addOffset = function(l) {
          this.prep(u.SIZEOF_INT, 0), this.writeInt32(this.offset() - l + u.SIZEOF_INT);
        }, u.Builder.prototype.startObject = function(l) {
          this.notNested(), this.vtable == null && (this.vtable = []), this.vtable_in_use = l;
          for (var h = 0; h < l; h++) this.vtable[h] = 0;
          this.isNested = !0, this.object_start = this.offset();
        }, u.Builder.prototype.endObject = function() {
          if (this.vtable == null || !this.isNested) throw new Error("FlatBuffers: endObject called without startObject");
          this.addInt32(0);
          for (var l = this.offset(), h = this.vtable_in_use - 1; h >= 0 && this.vtable[h] == 0; h--) ;
          for (var a = h + 1; h >= 0; h--) this.addInt16(this.vtable[h] != 0 ? l - this.vtable[h] : 0);
          this.addInt16(l - this.object_start);
          var f = (a + 2) * u.SIZEOF_SHORT;
          this.addInt16(f);
          var g = 0, c = this.space;
          e: for (h = 0; h < this.vtables.length; h++) {
            var s = this.bb.capacity() - this.vtables[h];
            if (f == this.bb.readInt16(s)) {
              for (var t = u.SIZEOF_SHORT; t < f; t += u.SIZEOF_SHORT) if (this.bb.readInt16(c + t) != this.bb.readInt16(s + t)) continue e;
              g = this.vtables[h];
              break;
            }
          }
          return g ? (this.space = this.bb.capacity() - l, this.bb.writeInt32(this.space, g - l)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - l, this.offset() - l)), this.isNested = !1, l;
        }, u.Builder.prototype.finish = function(l, h, a) {
          var f = a ? u.SIZE_PREFIX_LENGTH : 0;
          if (h) {
            var g = h;
            if (this.prep(this.minalign, u.SIZEOF_INT + u.FILE_IDENTIFIER_LENGTH + f), g.length != u.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + u.FILE_IDENTIFIER_LENGTH);
            for (var c = u.FILE_IDENTIFIER_LENGTH - 1; c >= 0; c--) this.writeInt8(g.charCodeAt(c));
          }
          this.prep(this.minalign, u.SIZEOF_INT + f), this.addOffset(l), f && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space);
        }, u.Builder.prototype.finishSizePrefixed = function(l, h) {
          this.finish(l, h, !0);
        }, u.Builder.prototype.requiredField = function(l, h) {
          var a = this.bb.capacity() - l, f = a - this.bb.readInt32(a);
          if (this.bb.readInt16(f + h) == 0) throw new Error("FlatBuffers: field " + h + " must be set");
        }, u.Builder.prototype.startVector = function(l, h, a) {
          this.notNested(), this.vector_num_elems = h, this.prep(u.SIZEOF_INT, l * h), this.prep(a, l * h);
        }, u.Builder.prototype.endVector = function() {
          return this.writeInt32(this.vector_num_elems), this.offset();
        }, u.Builder.prototype.createString = function(l) {
          if (l instanceof Uint8Array) var h = l;
          else {
            h = [];
            for (var a = 0; a < l.length; ) {
              var f, g = l.charCodeAt(a++);
              (f = g < 55296 || g >= 56320 ? g : (g << 10) + l.charCodeAt(a++) + -56613888) < 128 ? h.push(f) : (f < 2048 ? h.push(f >> 6 & 31 | 192) : (f < 65536 ? h.push(f >> 12 & 15 | 224) : h.push(f >> 18 & 7 | 240, f >> 12 & 63 | 128), h.push(f >> 6 & 63 | 128)), h.push(63 & f | 128));
            }
          }
          this.addInt8(0), this.startVector(1, h.length, 1), this.bb.setPosition(this.space -= h.length), a = 0;
          for (var c = this.space, s = this.bb.bytes(); a < h.length; a++) s[c++] = h[a];
          return this.endVector();
        }, u.Builder.prototype.createLong = function(l, h) {
          return u.Long.create(l, h);
        }, u.ByteBuffer = function(l) {
          this.bytes_ = l, this.position_ = 0;
        }, u.ByteBuffer.allocate = function(l) {
          return new u.ByteBuffer(new Uint8Array(l));
        }, u.ByteBuffer.prototype.clear = function() {
          this.position_ = 0;
        }, u.ByteBuffer.prototype.bytes = function() {
          return this.bytes_;
        }, u.ByteBuffer.prototype.position = function() {
          return this.position_;
        }, u.ByteBuffer.prototype.setPosition = function(l) {
          this.position_ = l;
        }, u.ByteBuffer.prototype.capacity = function() {
          return this.bytes_.length;
        }, u.ByteBuffer.prototype.readInt8 = function(l) {
          return this.readUint8(l) << 24 >> 24;
        }, u.ByteBuffer.prototype.readUint8 = function(l) {
          return this.bytes_[l];
        }, u.ByteBuffer.prototype.readInt16 = function(l) {
          return this.readUint16(l) << 16 >> 16;
        }, u.ByteBuffer.prototype.readUint16 = function(l) {
          return this.bytes_[l] | this.bytes_[l + 1] << 8;
        }, u.ByteBuffer.prototype.readInt32 = function(l) {
          return this.bytes_[l] | this.bytes_[l + 1] << 8 | this.bytes_[l + 2] << 16 | this.bytes_[l + 3] << 24;
        }, u.ByteBuffer.prototype.readUint32 = function(l) {
          return this.readInt32(l) >>> 0;
        }, u.ByteBuffer.prototype.readInt64 = function(l) {
          return new u.Long(this.readInt32(l), this.readInt32(l + 4));
        }, u.ByteBuffer.prototype.readUint64 = function(l) {
          return new u.Long(this.readUint32(l), this.readUint32(l + 4));
        }, u.ByteBuffer.prototype.readFloat32 = function(l) {
          return u.int32[0] = this.readInt32(l), u.float32[0];
        }, u.ByteBuffer.prototype.readFloat64 = function(l) {
          return u.int32[u.isLittleEndian ? 0 : 1] = this.readInt32(l), u.int32[u.isLittleEndian ? 1 : 0] = this.readInt32(l + 4), u.float64[0];
        }, u.ByteBuffer.prototype.writeInt8 = function(l, h) {
          this.bytes_[l] = h;
        }, u.ByteBuffer.prototype.writeUint8 = function(l, h) {
          this.bytes_[l] = h;
        }, u.ByteBuffer.prototype.writeInt16 = function(l, h) {
          this.bytes_[l] = h, this.bytes_[l + 1] = h >> 8;
        }, u.ByteBuffer.prototype.writeUint16 = function(l, h) {
          this.bytes_[l] = h, this.bytes_[l + 1] = h >> 8;
        }, u.ByteBuffer.prototype.writeInt32 = function(l, h) {
          this.bytes_[l] = h, this.bytes_[l + 1] = h >> 8, this.bytes_[l + 2] = h >> 16, this.bytes_[l + 3] = h >> 24;
        }, u.ByteBuffer.prototype.writeUint32 = function(l, h) {
          this.bytes_[l] = h, this.bytes_[l + 1] = h >> 8, this.bytes_[l + 2] = h >> 16, this.bytes_[l + 3] = h >> 24;
        }, u.ByteBuffer.prototype.writeInt64 = function(l, h) {
          this.writeInt32(l, h.low), this.writeInt32(l + 4, h.high);
        }, u.ByteBuffer.prototype.writeUint64 = function(l, h) {
          this.writeUint32(l, h.low), this.writeUint32(l + 4, h.high);
        }, u.ByteBuffer.prototype.writeFloat32 = function(l, h) {
          u.float32[0] = h, this.writeInt32(l, u.int32[0]);
        }, u.ByteBuffer.prototype.writeFloat64 = function(l, h) {
          u.float64[0] = h, this.writeInt32(l, u.int32[u.isLittleEndian ? 0 : 1]), this.writeInt32(l + 4, u.int32[u.isLittleEndian ? 1 : 0]);
        }, u.ByteBuffer.prototype.getBufferIdentifier = function() {
          if (this.bytes_.length < this.position_ + u.SIZEOF_INT + u.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
          for (var l = "", h = 0; h < u.FILE_IDENTIFIER_LENGTH; h++) l += String.fromCharCode(this.readInt8(this.position_ + u.SIZEOF_INT + h));
          return l;
        }, u.ByteBuffer.prototype.__offset = function(l, h) {
          var a = l - this.readInt32(l);
          return h < this.readInt16(a) ? this.readInt16(a + h) : 0;
        }, u.ByteBuffer.prototype.__union = function(l, h) {
          return l.bb_pos = h + this.readInt32(h), l.bb = this, l;
        }, u.ByteBuffer.prototype.__string = function(l, h) {
          l += this.readInt32(l);
          var a = this.readInt32(l), f = "", g = 0;
          if (l += u.SIZEOF_INT, h === u.Encoding.UTF8_BYTES) return this.bytes_.subarray(l, l + a);
          for (; g < a; ) {
            var c, s = this.readUint8(l + g++);
            if (s < 192) c = s;
            else {
              var t = this.readUint8(l + g++);
              if (s < 224) c = (31 & s) << 6 | 63 & t;
              else {
                var e = this.readUint8(l + g++);
                c = s < 240 ? (15 & s) << 12 | (63 & t) << 6 | 63 & e : (7 & s) << 18 | (63 & t) << 12 | (63 & e) << 6 | 63 & this.readUint8(l + g++);
              }
            }
            c < 65536 ? f += String.fromCharCode(c) : (c -= 65536, f += String.fromCharCode(55296 + (c >> 10), 56320 + (1023 & c)));
          }
          return f;
        }, u.ByteBuffer.prototype.__indirect = function(l) {
          return l + this.readInt32(l);
        }, u.ByteBuffer.prototype.__vector = function(l) {
          return l + this.readInt32(l) + u.SIZEOF_INT;
        }, u.ByteBuffer.prototype.__vector_len = function(l) {
          return this.readInt32(l + this.readInt32(l));
        }, u.ByteBuffer.prototype.__has_identifier = function(l) {
          if (l.length != u.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + u.FILE_IDENTIFIER_LENGTH);
          for (var h = 0; h < u.FILE_IDENTIFIER_LENGTH; h++) if (l.charCodeAt(h) != this.readInt8(this.position_ + u.SIZEOF_INT + h)) return !1;
          return !0;
        }, u.ByteBuffer.prototype.createLong = function(l, h) {
          return u.Long.create(l, h);
        };
      } }, __webpack_module_cache__ = {};
      function __webpack_require__(d) {
        var n = __webpack_module_cache__[d];
        if (n !== void 0) return n.exports;
        var o = __webpack_module_cache__[d] = { exports: {} };
        return __webpack_modules__[d].call(o.exports, o, o.exports, __webpack_require__), o.exports;
      }
      __webpack_require__.n = (d) => {
        var n = d && d.__esModule ? () => d.default : () => d;
        return __webpack_require__.d(n, { a: n }), n;
      }, __webpack_require__.d = (d, n) => {
        for (var o in n) __webpack_require__.o(n, o) && !__webpack_require__.o(d, o) && Object.defineProperty(d, o, { enumerable: !0, get: n[o] });
      }, __webpack_require__.g = (function() {
        if (typeof globalThis == "object") return globalThis;
        try {
          return this || new Function("return this")();
        } catch {
          if (typeof window == "object") return window;
        }
      })(), __webpack_require__.o = (d, n) => Object.prototype.hasOwnProperty.call(d, n), __webpack_require__.r = (d) => {
        typeof Symbol < "u" && Symbol.toStringTag && Object.defineProperty(d, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(d, "__esModule", { value: !0 });
      };
      var __webpack_exports__ = __webpack_require__(6018);
      return __webpack_exports__;
    })()));
  })(ortWeb_min$1)), ortWeb_min$1.exports;
}
var ortWeb_minExports = requireOrtWeb_min();
const ortWeb_min = /* @__PURE__ */ getDefaultExportFromCjs(ortWeb_minExports), ONNX_WEB = /* @__PURE__ */ _mergeNamespaces({
  __proto__: null,
  default: ortWeb_min
}, [ortWeb_minExports]);
let ONNX;
const executionProviders = [
  // 'webgpu',
  "wasm"
];
typeof process < "u" && process?.release?.name === "node" ? (ONNX = sharp ?? ONNX_NODE, executionProviders.unshift("cpu")) : (ONNX = ortWeb_min ?? ONNX_WEB, typeof navigator < "u" && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent) && (ONNX.env.wasm.simd = !1));
const { env: onnx_env } = ONNX, VERSION = "2.17.2", WEB_CACHE_AVAILABLE = typeof self < "u" && "caches" in self, FS_AVAILABLE = !isEmpty(sharp), PATH_AVAILABLE = !isEmpty(sharp), RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE, __dirname$1 = RUNNING_LOCALLY ? sharp.dirname(sharp.dirname(sharp.fileURLToPath(import.meta.url))) : "./", DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? sharp.join(__dirname$1, "/.cache/") : null, DEFAULT_LOCAL_MODEL_PATH = "/models/", localModelPath = RUNNING_LOCALLY ? sharp.join(__dirname$1, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH;
onnx_env?.wasm && (onnx_env.wasm.wasmPaths = RUNNING_LOCALLY ? sharp.join(__dirname$1, "/dist/") : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`);
const env$1 = {
  /////////////////// Backends settings ///////////////////
  backends: {
    // onnxruntime-web/onnxruntime-node
    onnx: onnx_env
  },
  version: VERSION,
  /////////////////// Model settings ///////////////////
  allowRemoteModels: !0,
  remoteHost: "https://huggingface.co/",
  remotePathTemplate: "{model}/resolve/{revision}/",
  allowLocalModels: !0,
  localModelPath,
  useFS: FS_AVAILABLE,
  /////////////////// Cache settings ///////////////////
  useBrowserCache: WEB_CACHE_AVAILABLE,
  useFSCache: FS_AVAILABLE,
  cacheDir: DEFAULT_CACHE_DIR,
  useCustomCache: !1,
  customCache: null
  //////////////////////////////////////////////////////
};
function isEmpty(d) {
  return Object.keys(d).length === 0;
}
class FileResponse {
  /**
   * Mapping from file extensions to MIME types.
   */
  _CONTENT_TYPE_MAP = {
    txt: "text/plain",
    html: "text/html",
    css: "text/css",
    js: "text/javascript",
    json: "application/json",
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif"
  };
  /**
   * Creates a new `FileResponse` object.
   * @param {string|URL} filePath
   */
  constructor(n) {
    if (this.filePath = n, this.headers = new Headers(), this.exists = sharp.existsSync(n), this.exists) {
      this.status = 200, this.statusText = "OK";
      let o = sharp.statSync(n);
      this.headers.set("content-length", o.size.toString()), this.updateContentType();
      let u = this;
      this.body = new ReadableStream({
        start(l) {
          u.arrayBuffer().then((h) => {
            l.enqueue(new Uint8Array(h)), l.close();
          });
        }
      });
    } else
      this.status = 404, this.statusText = "Not Found", this.body = null;
  }
  /**
   * Updates the 'content-type' header property of the response based on the extension of
   * the file specified by the filePath property of the current object.
   * @returns {void}
   */
  updateContentType() {
    const n = this.filePath.toString().split(".").pop().toLowerCase();
    this.headers.set("content-type", this._CONTENT_TYPE_MAP[n] ?? "application/octet-stream");
  }
  /**
   * Clone the current FileResponse object.
   * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
   */
  clone() {
    let n = new FileResponse(this.filePath);
    return n.exists = this.exists, n.status = this.status, n.statusText = this.statusText, n.headers = new Headers(this.headers), n;
  }
  /**
   * Reads the contents of the file specified by the filePath property and returns a Promise that
   * resolves with an ArrayBuffer containing the file's contents.
   * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
   * @throws {Error} If the file cannot be read.
   */
  async arrayBuffer() {
    return (await sharp.promises.readFile(this.filePath)).buffer;
  }
  /**
   * Reads the contents of the file specified by the filePath property and returns a Promise that
   * resolves with a Blob containing the file's contents.
   * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
   * @throws {Error} If the file cannot be read.
   */
  async blob() {
    const n = await sharp.promises.readFile(this.filePath);
    return new Blob([n], { type: this.headers.get("content-type") });
  }
  /**
   * Reads the contents of the file specified by the filePath property and returns a Promise that
   * resolves with a string containing the file's contents.
   * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
   * @throws {Error} If the file cannot be read.
   */
  async text() {
    return await sharp.promises.readFile(this.filePath, "utf8");
  }
  /**
   * Reads the contents of the file specified by the filePath property and returns a Promise that
   * resolves with a parsed JavaScript object containing the file's contents.
   * 
   * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
   * @throws {Error} If the file cannot be read.
   */
  async json() {
    return JSON.parse(await this.text());
  }
}
function isValidUrl(d, n = null, o = null) {
  let u;
  try {
    u = new URL(d);
  } catch {
    return !1;
  }
  return !(n && !n.includes(u.protocol) || o && !o.includes(u.hostname));
}
async function getFile(d) {
  if (env$1.useFS && !isValidUrl(d, ["http:", "https:", "blob:"]))
    return new FileResponse(d);
  if (typeof process < "u" && process?.release?.name === "node") {
    const n = !!process.env?.TESTING_REMOTELY, o = env$1.version, u = new Headers();
    if (u.set("User-Agent", `transformers.js/${o}; is_ci/${n};`), isValidUrl(d, ["http:", "https:"], ["huggingface.co", "hf.co"])) {
      const h = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;
      h && u.set("Authorization", `Bearer ${h}`);
    }
    return fetch(d, { headers: u });
  } else
    return fetch(d);
}
const ERROR_MAPPING = {
  // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)
  400: "Bad request error occurred while trying to load file",
  401: "Unauthorized access to file",
  403: "Forbidden access to file",
  404: "Could not locate file",
  408: "Request timeout error occurred while trying to load file",
  // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)
  500: "Internal server error error occurred while trying to load file",
  502: "Bad gateway error occurred while trying to load file",
  503: "Service unavailable error occurred while trying to load file",
  504: "Gateway timeout error occurred while trying to load file"
};
function handleError(d, n, o) {
  if (!o)
    return null;
  const u = ERROR_MAPPING[d] ?? `Error (${d}) occurred while trying to load file`;
  throw Error(`${u}: "${n}".`);
}
class FileCache {
  /**
   * Instantiate a `FileCache` object.
   * @param {string} path 
   */
  constructor(n) {
    this.path = n;
  }
  /**
   * Checks whether the given request is in the cache.
   * @param {string} request 
   * @returns {Promise<FileResponse | undefined>}
   */
  async match(n) {
    let o = sharp.join(this.path, n), u = new FileResponse(o);
    if (u.exists)
      return u;
  }
  /**
   * Adds the given response to the cache.
   * @param {string} request 
   * @param {Response|FileResponse} response 
   * @returns {Promise<void>}
   */
  async put(n, o) {
    const u = Buffer.from(await o.arrayBuffer());
    let l = sharp.join(this.path, n);
    try {
      await sharp.promises.mkdir(sharp.dirname(l), { recursive: !0 }), await sharp.promises.writeFile(l, u);
    } catch (h) {
      console.warn("An error occurred while writing the file to cache:", h);
    }
  }
  // TODO add the rest?
  // addAll(requests: RequestInfo[]): Promise<void>;
  // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
  // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;
  // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
  // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;
}
async function tryCache(d, ...n) {
  for (let o of n)
    try {
      let u = await d.match(o);
      if (u) return u;
    } catch {
      continue;
    }
}
async function getModelFile(d, n, o = !0, u = {}) {
  if (!env$1.allowLocalModels) {
    if (u.local_files_only)
      throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");
    if (!env$1.allowRemoteModels)
      throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.");
  }
  dispatchCallback(u.progress_callback, {
    status: "initiate",
    name: d,
    file: n
  });
  let l;
  if (!l && env$1.useBrowserCache) {
    if (typeof caches > "u")
      throw Error("Browser cache is not available in this environment.");
    try {
      l = await caches.open("transformers-cache");
    } catch (_) {
      console.warn("An error occurred while opening the browser cache:", _);
    }
  }
  if (!l && env$1.useFSCache && (l = new FileCache(u.cache_dir ?? env$1.cacheDir)), !l && env$1.useCustomCache) {
    if (!env$1.customCache)
      throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");
    if (!env$1.customCache.match || !env$1.customCache.put)
      throw new Error(
        "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache"
      );
    l = env$1.customCache;
  }
  const h = u.revision ?? "main";
  let a = pathJoin(d, n), f = pathJoin(env$1.localModelPath, a), g = pathJoin(
    env$1.remoteHost,
    env$1.remotePathTemplate.replaceAll("{model}", d).replaceAll("{revision}", encodeURIComponent(h)),
    n
  ), c = h === "main" ? a : pathJoin(d, h, n), s, t = l instanceof FileCache ? c : g, e = !1, r;
  l && (r = await tryCache(l, f, t));
  const i = r !== void 0;
  if (r === void 0) {
    if (env$1.allowLocalModels)
      if (isValidUrl(a, ["http:", "https:"])) {
        if (u.local_files_only)
          throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);
        if (!env$1.allowRemoteModels)
          throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`);
      } else try {
        r = await getFile(f), s = f;
      } catch (b) {
        console.warn(`Unable to load from local path "${f}": "${b}"`);
      }
    if (r === void 0 || r.status === 404) {
      if (u.local_files_only || !env$1.allowRemoteModels) {
        if (o)
          throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${f}".`);
        return null;
      }
      if (r = await getFile(g), r.status !== 200)
        return handleError(r.status, g, o);
      s = t;
    }
    e = l && typeof Response < "u" && r instanceof Response && r.status === 200;
  }
  dispatchCallback(u.progress_callback, {
    status: "download",
    name: d,
    file: n
  });
  const p = {
    status: "progress",
    name: d,
    file: n
  };
  let m;
  return u.progress_callback ? i && typeof navigator < "u" && /firefox/i.test(navigator.userAgent) ? (m = new Uint8Array(await r.arrayBuffer()), dispatchCallback(u.progress_callback, {
    ...p,
    progress: 100,
    loaded: m.length,
    total: m.length
  })) : m = await readResponse(r, (_) => {
    dispatchCallback(u.progress_callback, {
      ...p,
      ..._
    });
  }) : m = new Uint8Array(await r.arrayBuffer()), // Only cache web responses
  // i.e., do not cache FileResponses (prevents duplication)
  e && s && // Check again whether request is in cache. If not, we add the response to the cache
  await l.match(s) === void 0 && await l.put(s, new Response(m, {
    headers: r.headers
  })).catch((_) => {
    console.warn(`Unable to add response to browser cache: ${_}.`);
  }), dispatchCallback(u.progress_callback, {
    status: "done",
    name: d,
    file: n
  }), m;
}
async function getModelJSON(d, n, o = !0, u = {}) {
  let l = await getModelFile(d, n, o, u);
  if (l === null)
    return {};
  let a = new TextDecoder("utf-8").decode(l);
  return JSON.parse(a);
}
async function readResponse(d, n) {
  const o = d.headers.get("Content-Length");
  o === null && console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");
  let u = parseInt(o ?? "0"), l = new Uint8Array(u), h = 0;
  const a = d.body.getReader();
  async function f() {
    const { done: g, value: c } = await a.read();
    if (g) return;
    let s = h + c.length;
    if (s > u) {
      u = s;
      let e = new Uint8Array(u);
      e.set(l), l = e;
    }
    l.set(c, h), h = s;
    const t = h / u * 100;
    return n({
      progress: t,
      loaded: h,
      total: u
    }), f();
  }
  return await f(), l;
}
function pathJoin(...d) {
  return d = d.map((n, o) => (o && (n = n.replace(new RegExp("^/"), "")), o !== d.length - 1 && (n = n.replace(new RegExp("/$"), "")), n)), d.join("/");
}
function permute_data(d, n, o) {
  const u = new Array(o.length), l = new Array(o.length);
  for (let f = o.length - 1, g = 1; f >= 0; --f)
    l[f] = g, u[f] = n[o[f]], g *= u[f];
  const h = o.map((f, g) => l[o.indexOf(g)]), a = new d.constructor(d.length);
  for (let f = 0; f < d.length; ++f) {
    let g = 0;
    for (let c = n.length - 1, s = f; c >= 0; --c)
      g += s % n[c] * h[c], s = Math.floor(s / n[c]);
    a[g] = d[f];
  }
  return [a, u];
}
function softmax(d) {
  const n = max(d)[0], o = d.map((h) => Math.exp(h - n)), u = o.reduce((h, a) => h + a, 0);
  return o.map((h) => h / u);
}
function log_softmax(d) {
  return softmax(d).map((u) => Math.log(u));
}
function getTopItems(d, n = 0) {
  return d = Array.from(d).map((o, u) => [u, o]).sort((o, u) => u[1] - o[1]), n !== null && n > 0 && (d = d.slice(0, n)), d;
}
function min(d) {
  if (d.length === 0) throw Error("Array must not be empty");
  let n = d[0], o = 0;
  for (let u = 1; u < d.length; ++u)
    d[u] < n && (n = d[u], o = u);
  return [n, o];
}
function max(d) {
  if (d.length === 0) throw Error("Array must not be empty");
  let n = d[0], o = 0;
  for (let u = 1; u < d.length; ++u)
    d[u] > n && (n = d[u], o = u);
  return [Number(n), o];
}
function medianFilter(d, n) {
  if (n % 2 === 0 || n <= 0)
    throw new Error("Window size must be a positive odd number");
  const o = new d.constructor(d.length), u = new d.constructor(n), l = Math.floor(n / 2);
  for (let h = 0; h < d.length; ++h) {
    let a = 0;
    for (let f = -l; f <= l; ++f) {
      let g = h + f;
      g < 0 ? g = Math.abs(g) : g >= d.length && (g = 2 * (d.length - 1) - g), u[a++] = d[g];
    }
    u.sort(), o[h] = u[l];
  }
  return o;
}
function round(d, n) {
  const o = Math.pow(10, n);
  return Math.round(d * o) / o;
}
const DataTypeMap = Object.freeze({
  float32: Float32Array,
  float64: Float64Array,
  string: Array,
  // string[]
  int8: Int8Array,
  uint8: Uint8Array,
  int16: Int16Array,
  uint16: Uint16Array,
  int32: Int32Array,
  uint32: Uint32Array,
  int64: BigInt64Array,
  uint64: BigUint64Array,
  bool: Uint8Array
}), ONNXTensor$1 = ONNX.Tensor;
class Tensor {
  /** @type {number[]} Dimensions of the tensor. */
  dims;
  /** @type {DataType} Type of the tensor. */
  type;
  /** @type {DataArray} The data stored in the tensor. */
  data;
  /** @type {number} The number of elements in the tensor. */
  size;
  /**
   * Create a new Tensor or copy an existing Tensor.
   * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
   */
  constructor(...n) {
    return n[0] instanceof ONNXTensor$1 ? Object.assign(this, n[0]) : Object.assign(this, new ONNXTensor$1(
      /** @type {DataType} */
      n[0],
      /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */
      n[1],
      n[2]
    )), new Proxy(this, {
      get: (o, u) => {
        if (typeof u == "string") {
          let l = Number(u);
          if (Number.isInteger(l))
            return o._getitem(l);
        }
        return o[u];
      },
      set: (o, u, l) => o[u] = l
    });
  }
  /**
   * Returns an iterator object for iterating over the tensor data in row-major order.
   * If the tensor has more than one dimension, the iterator will yield subarrays.
   * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
   */
  *[Symbol.iterator]() {
    const [n, ...o] = this.dims;
    if (o.length > 0) {
      const u = o.reduce((l, h) => l * h);
      for (let l = 0; l < n; ++l)
        yield this._subarray(l, u, o);
    } else
      yield* this.data;
  }
  /**
   * Index into a Tensor object.
   * @param {number} index The index to access.
   * @returns {Tensor} The data at the specified index.
   */
  _getitem(n) {
    const [o, ...u] = this.dims;
    if (n = safeIndex(n, o), u.length > 0) {
      const l = u.reduce((h, a) => h * a);
      return this._subarray(n, l, u);
    } else
      return new Tensor(this.type, [this.data[n]], u);
  }
  /**
   * @param {number|bigint} item The item to search for in the tensor
   * @returns {number} The index of the first occurrence of item in the tensor data.
   */
  indexOf(n) {
    for (let o = 0; o < this.data.length; ++o)
      if (this.data[o] == n)
        return o;
    return -1;
  }
  /**
   * @param {number} index 
   * @param {number} iterSize 
   * @param {any} iterDims 
   * @returns {Tensor}
   */
  _subarray(n, o, u) {
    const l = n * o, h = (n + 1) * o, a = "subarray" in this.data ? this.data.subarray(l, h) : this.data.slice(l, h);
    return new Tensor(this.type, a, u);
  }
  /**
   * Returns the value of this tensor as a standard JavaScript Number. This only works
   * for tensors with one element. For other cases, see `Tensor.tolist()`.
   * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
   * @throws {Error} If the tensor has more than one element.
   */
  item() {
    if (this.data.length !== 1)
      throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`);
    return this.data[0];
  }
  /**
   * Convert tensor data to a n-dimensional JS list
   * @returns {Array}
   */
  tolist() {
    return reshape(this.data, this.dims);
  }
  /**
   * Return a new Tensor with the sigmoid function applied to each element.
   * @returns {Tensor} The tensor with the sigmoid function applied.
   */
  sigmoid() {
    return this.clone().sigmoid_();
  }
  /**
   * Applies the sigmoid function to the tensor in place.
   * @returns {Tensor} Returns `this`.
   */
  sigmoid_() {
    for (let n = 0; n < this.data.length; ++n)
      this.data[n] = 1 / (1 + Math.exp(-this.data[n]));
    return this;
  }
  /**
   * Return a new Tensor with every element multiplied by a constant.
   * @param {number} val The value to multiply by.
   * @returns {Tensor} The new tensor.
   */
  mul(n) {
    return this.clone().mul_(n);
  }
  /**
   * Multiply the tensor by a constant in place.
   * @param {number} val The value to multiply by.
   * @returns {Tensor} Returns `this`.
   */
  mul_(n) {
    for (let o = 0; o < this.data.length; ++o)
      this.data[o] *= n;
    return this;
  }
  /**
   * Return a new Tensor with every element added by a constant.
   * @param {number} val The value to add by.
   * @returns {Tensor} The new tensor.
   */
  add(n) {
    return this.clone().add_(n);
  }
  /**
   * Add the tensor by a constant in place.
   * @param {number} val The value to add by.
   * @returns {Tensor} Returns `this`.
   */
  add_(n) {
    for (let o = 0; o < this.data.length; ++o)
      this.data[o] += n;
    return this;
  }
  clone() {
    return new Tensor(this.type, this.data.slice(), this.dims.slice());
  }
  slice(...n) {
    let o = [], u = [];
    for (let g = 0; g < this.dims.length; ++g) {
      let c = n[g];
      if (c == null)
        u.push([0, this.dims[g]]), o.push(this.dims[g]);
      else if (typeof c == "number")
        c = safeIndex(c, this.dims[g], g), u.push([c, c + 1]);
      else if (Array.isArray(c) && c.length === 2) {
        if (c[0] > c[1])
          throw new Error(`Invalid slice: ${c}`);
        let s = [
          Math.max(c[0], 0),
          Math.min(c[1], this.dims[g])
        ];
        u.push(s), o.push(s[1] - s[0]);
      } else
        throw new Error(`Invalid slice: ${c}`);
    }
    let l = u.map(([g, c]) => c - g), h = l.reduce((g, c) => g * c), a = new this.data.constructor(h);
    const f = this.stride();
    for (let g = 0; g < h; ++g) {
      let c = 0;
      for (let s = l.length - 1, t = g; s >= 0; --s) {
        const e = l[s];
        c += (t % e + u[s][0]) * f[s], t = Math.floor(t / e);
      }
      a[g] = this.data[c];
    }
    return new Tensor(this.type, a, o);
  }
  /**
   * Return a permuted version of this Tensor, according to the provided dimensions.
   * @param  {...number} dims Dimensions to permute.
   * @returns {Tensor} The permuted tensor.
   */
  permute(...n) {
    return permute(this, n);
  }
  // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()
  transpose(...n) {
    return this.permute(...n);
  }
  // TODO add .max() and .min() methods
  /**
   * Returns the sum of each row of the input tensor in the given dimension dim.
   * 
   * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
   * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
   * @returns The summed tensor
   */
  sum(n = null, o = !1) {
    return this.norm(1, n, o);
  }
  /**
   * Returns the matrix norm or vector norm of a given tensor.
   * @param {number|string} [p='fro'] The order of norm
   * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
   * If dim is None, the norm will be calculated across all dimensions of input.
   * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
   * @returns {Tensor} The norm of the tensor.
   */
  norm(n = "fro", o = null, u = !1) {
    if (n === "fro")
      n = 2;
    else if (typeof n == "string")
      throw Error(`Unsupported norm: ${n}`);
    if (o === null) {
      let a = this.data.reduce((f, g) => f + g ** n, 0) ** (1 / n);
      return new Tensor(this.type, [a], []);
    }
    o = safeIndex(o, this.dims.length);
    const l = this.dims.slice();
    l[o] = 1;
    const h = new this.data.constructor(this.data.length / this.dims[o]);
    for (let a = 0; a < this.data.length; ++a) {
      let f = 0;
      for (let g = this.dims.length - 1, c = a, s = 1; g >= 0; --g) {
        const t = this.dims[g];
        if (g !== o) {
          const e = c % t;
          f += e * s, s *= l[g];
        }
        c = Math.floor(c / t);
      }
      h[f] += this.data[a] ** n;
    }
    if (n !== 1)
      for (let a = 0; a < h.length; ++a)
        h[a] = h[a] ** (1 / n);
    return u || l.splice(o, 1), new Tensor(this.type, h, l);
  }
  /**
   * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
   * @param {number} [p=2] The exponent value in the norm formulation
   * @param {number} [dim=1] The dimension to reduce
   * @returns {Tensor} `this` for operation chaining.
   */
  normalize_(n = 2, o = 1) {
    o = safeIndex(o, this.dims.length);
    const u = this.norm(n, o, !0);
    for (let l = 0; l < this.data.length; ++l) {
      let h = 0;
      for (let a = this.dims.length - 1, f = l, g = 1; a >= 0; --a) {
        const c = this.dims[a];
        if (a !== o) {
          const s = f % c;
          h += s * g, g *= this.dims[a];
        }
        f = Math.floor(f / c);
      }
      this.data[l] /= u.data[h];
    }
    return this;
  }
  /**
   * Performs `L_p` normalization of inputs over specified dimension.
   * @param {number} [p=2] The exponent value in the norm formulation
   * @param {number} [dim=1] The dimension to reduce
   * @returns {Tensor} The normalized tensor.
   */
  normalize(n = 2, o = 1) {
    return this.clone().normalize_(n, o);
  }
  /**
   * Compute and return the stride of this tensor.
   * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
   * @returns {number[]} The stride of this tensor.
   */
  stride() {
    return dimsToStride(this.dims);
  }
  /**
   * Returns a tensor with all specified dimensions of input of size 1 removed.
   * 
   * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
   * If you would like a copy, use `tensor.clone()` before squeezing.
   * 
   * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
   * @returns The squeezed tensor
   */
  squeeze(n = null) {
    return new Tensor(
      this.type,
      this.data,
      calc_squeeze_dims(this.dims, n)
    );
  }
  /**
   * In-place version of @see {@link Tensor.squeeze}
   */
  squeeze_(n = null) {
    return this.dims = calc_squeeze_dims(this.dims, n), this;
  }
  /**
   * Returns a new tensor with a dimension of size one inserted at the specified position.
   * 
   * NOTE: The returned tensor shares the same underlying data with this tensor.
   * 
   * @param {number} dim The index at which to insert the singleton dimension
   * @returns The unsqueezed tensor
   */
  unsqueeze(n = null) {
    return new Tensor(
      this.type,
      this.data,
      calc_unsqueeze_dims(this.dims, n)
    );
  }
  /**
   * In-place version of @see {@link Tensor.unsqueeze}
   */
  unsqueeze_(n = null) {
    return this.dims = calc_unsqueeze_dims(this.dims, n), this;
  }
  /**
   * In-place version of @see {@link Tensor.flatten}
   */
  flatten_(n = 0, o = -1) {
    o = (o + this.dims.length) % this.dims.length;
    let u = this.dims.slice(0, n), l = this.dims.slice(n, o + 1), h = this.dims.slice(o + 1);
    return this.dims = [...u, l.reduce((a, f) => a * f, 1), ...h], this;
  }
  /**
   * Flattens input by reshaping it into a one-dimensional tensor.
   * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
   * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
   * @param {number} start_dim the first dim to flatten
   * @param {number} end_dim the last dim to flatten
   * @returns The flattened tensor.
   */
  flatten(n = 0, o = -1) {
    return this.clone().flatten_(n, o);
  }
  /**
   * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
   * @param  {...number} dims the desired size
   * @returns {Tensor} The tensor with the same data but different shape
   */
  view(...n) {
    let o = -1;
    for (let u = 0; u < n.length; ++u)
      if (n[u] === -1) {
        if (o !== -1)
          throw new Error("Only one dimension can be inferred");
        o = u;
      }
    if (o !== -1) {
      const u = n.reduce((l, h, a) => a !== o ? l * h : l, 1);
      n[o] = this.data.length / u;
    }
    return new Tensor(this.type, this.data, n);
  }
  neg_() {
    for (let n = 0; n < this.data.length; ++n)
      this.data[n] = -this.data[n];
    return this;
  }
  neg() {
    return this.clone().neg_();
  }
  /**
   * In-place version of @see {@link Tensor.clamp}
   */
  clamp_(n, o) {
    for (let u = 0; u < this.data.length; ++u)
      this.data[u] = Math.min(Math.max(this.data[u], n), o);
    return this;
  }
  /**
   * Clamps all elements in input into the range [ min, max ]
   * @param {number} min lower-bound of the range to be clamped to
   * @param {number} max upper-bound of the range to be clamped to
   * @returns the output tensor.
   */
  clamp(n, o) {
    return this.clone().clamp_(n, o);
  }
  /**
   * In-place version of @see {@link Tensor.round}
   */
  round_() {
    for (let n = 0; n < this.data.length; ++n)
      this.data[n] = Math.round(this.data[n]);
    return this;
  }
  /**
   * Rounds elements of input to the nearest integer.
   * @returns the output tensor.
   */
  round() {
    return this.clone().round_();
  }
  /**
   * Performs Tensor dtype conversion.
   * @param {DataType} type The desired data type.
   * @returns {Tensor} The converted tensor.
   */
  to(n) {
    if (this.type === n) return this;
    if (!DataTypeMap.hasOwnProperty(n))
      throw new Error(`Unsupported type: ${n}`);
    return new Tensor(n, DataTypeMap[n].from(this.data), this.dims);
  }
}
function reshape(d, n) {
  const o = d.length, u = n.reduce((h, a) => h * a);
  if (o !== u)
    throw Error(`cannot reshape array of size ${o} into shape (${n})`);
  let l = d;
  for (let h = n.length - 1; h >= 0; h--)
    l = l.reduce((a, f) => {
      let g = a[a.length - 1];
      return g.length < n[h] ? g.push(f) : a.push([f]), a;
    }, [[]]);
  return l[0];
}
function permute(d, n) {
  const [o, u] = permute_data(d.data, d.dims, n);
  return new Tensor(d.type, o, u);
}
function calc_squeeze_dims(d, n) {
  return d = d.slice(), n === null ? d = d.filter((o) => o !== 1) : typeof n == "number" ? d[n] === 1 && d.splice(n, 1) : Array.isArray(n) && (d = d.filter((o, u) => o !== 1 || !n.includes(u))), d;
}
function calc_unsqueeze_dims(d, n) {
  return n = safeIndex(n, d.length + 1), d = d.slice(), d.splice(n, 0, 1), d;
}
function safeIndex(d, n, o = null) {
  if (d < -n || d >= n)
    throw new Error(`IndexError: index ${d} is out of bounds for dimension${o === null ? "" : " " + o} with size ${n}`);
  return d < 0 && (d = (d % n + n) % n), d;
}
function cat(d, n = 0) {
  n = safeIndex(n, d[0].dims.length);
  const o = d[0].dims.slice();
  o[n] = d.reduce((a, f) => a + f.dims[n], 0);
  const u = o.reduce((a, f) => a * f, 1), l = new d[0].data.constructor(u), h = d[0].type;
  if (n === 0) {
    let a = 0;
    for (let f of d)
      l.set(f.data, a), a += f.data.length;
  } else {
    let a = 0;
    for (let f = 0; f < d.length; ++f) {
      let g = d[f];
      for (let c = 0; c < g.data.length; ++c) {
        let s = 0;
        for (let t = g.dims.length - 1, e = c, r = 1; t >= 0; --t) {
          const i = g.dims[t];
          let p = e % i;
          t === n && (p += a), s += p * r, r *= o[t], e = Math.floor(e / i);
        }
        l[s] = g.data[c];
      }
      a += g.dims[n];
    }
  }
  return new Tensor(h, l, o);
}
function stack(d, n = 0) {
  return cat(d.map((o) => o.unsqueeze(n)), n);
}
function std_mean(d, n = null, o = 1, u = !1) {
  if (n === null) {
    const c = d.data.reduce((r, i) => r + i, 0) / d.data.length, s = Math.sqrt(d.data.reduce((r, i) => r + (i - c) ** 2, 0) / (d.data.length - o)), t = new Tensor(d.type, [c], [
      /* scalar */
    ]);
    return [new Tensor(d.type, [s], [
      /* scalar */
    ]), t];
  }
  n = safeIndex(n, d.dims.length);
  const l = mean(d, n, u), h = d.dims.slice();
  h[n] = 1;
  const a = new d.data.constructor(d.data.length / d.dims[n]);
  for (let g = 0; g < d.data.length; ++g) {
    let c = 0;
    for (let s = d.dims.length - 1, t = g, e = 1; s >= 0; --s) {
      const r = d.dims[s];
      if (s !== n) {
        const i = t % r;
        c += i * e, e *= h[s];
      }
      t = Math.floor(t / r);
    }
    a[c] += (d.data[g] - l.data[c]) ** 2;
  }
  for (let g = 0; g < a.length; ++g)
    a[g] = Math.sqrt(a[g] / (d.dims[n] - o));
  return u || h.splice(n, 1), [new Tensor(d.type, a, h), l];
}
function mean(d, n = null, o = !1) {
  if (n === null) {
    let h = d.data.reduce((a, f) => a + f, 0);
    return new Tensor(d.type, [h / d.data.length], [
      /* scalar */
    ]);
  }
  n = safeIndex(n, d.dims.length);
  const u = d.dims.slice();
  u[n] = 1;
  const l = new d.data.constructor(d.data.length / d.dims[n]);
  for (let h = 0; h < d.data.length; ++h) {
    let a = 0;
    for (let f = d.dims.length - 1, g = h, c = 1; f >= 0; --f) {
      const s = d.dims[f];
      if (f !== n) {
        const t = g % s;
        a += t * c, c *= u[f];
      }
      g = Math.floor(g / s);
    }
    l[a] += d.data[h];
  }
  if (d.dims[n] !== 1)
    for (let h = 0; h < l.length; ++h)
      l[h] = l[h] / d.dims[n];
  return o || u.splice(n, 1), new Tensor(d.type, l, u);
}
function dynamicTimeWarping(d) {
  const [n, o] = d.dims, u = [n + 1, o + 1], l = new Tensor(
    "float32",
    new Float32Array(u[0] * u[1]).fill(1 / 0),
    u
  ), h = new Tensor(
    "float32",
    new Float32Array(u[0] * u[1]).fill(-1),
    u
  );
  l[0].data[0] = 0;
  for (let s = 1; s < o + 1; ++s)
    for (let t = 1; t < n + 1; ++t) {
      const e = l[t - 1][s - 1].item(), r = l[t - 1][s].item(), i = l[t][s - 1].item();
      let p, m;
      e < r && e < i ? (p = e, m = 0) : r < e && r < i ? (p = r, m = 1) : (p = i, m = 2), l[t].data[s] = d[t - 1][s - 1].item() + p, h[t].data[s] = m;
    }
  let a = n, f = o;
  h.data.fill(2, 0, u[1]);
  for (let s = 0; s < u[0]; ++s)
    h[s].data[0] = 1;
  let g = [], c = [];
  for (; a > 0 || f > 0; )
    switch (g.push(a - 1), c.push(f - 1), h[a][f].item()) {
      case 0:
        --a, --f;
        break;
      case 1:
        --a;
        break;
      case 2:
        --f;
        break;
      default:
        throw new Error(
          `Internal error in dynamic time warping. Unexpected trace[${a}, ${f}]. Please file a bug report.`
        );
    }
  return g.reverse(), c.reverse(), [g, c];
}
function dimsToStride(d) {
  const n = new Array(d.length);
  for (let o = d.length - 1, u = 1; o >= 0; --o)
    n[o] = u, u *= d[o];
  return n;
}
function ones(d) {
  const n = d.reduce((o, u) => o * u, 1);
  return new Tensor(
    "int64",
    new BigInt64Array(n).fill(1n),
    d
  );
}
function ones_like(d) {
  return ones(d.dims);
}
class PriorityQueue {
  /**
   * Create a new PriorityQueue.
   * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
   */
  constructor(n = (o, u) => o > u) {
    this._heap = [], this._comparator = n;
  }
  /**
   * The size of the queue
   */
  get size() {
    return this._heap.length;
  }
  /**
   * Check if the queue is empty.
   * @returns {boolean} `true` if the queue is empty, `false` otherwise.
   */
  isEmpty() {
    return this.size === 0;
  }
  /**
   * Return the element with the highest priority in the queue.
   * @returns {any} The highest priority element in the queue.
   */
  peek() {
    return this._heap[0];
  }
  /**
   * Add one or more elements to the queue.
   * @param  {...any} values The values to push into the queue.
   * @returns {number} The new size of the queue.
   */
  push(...n) {
    return this.extend(n);
  }
  /**
   * Add multiple elements to the queue.
   * @param {any[]} values The values to push into the queue.
   * @returns {number} The new size of the queue.
   */
  extend(n) {
    for (const o of n)
      this._heap.push(o), this._siftUp();
    return this.size;
  }
  /**
   * Remove and return the element with the highest priority in the queue.
   * @returns {any} The element with the highest priority in the queue.
   */
  pop() {
    const n = this.peek(), o = this.size - 1;
    return o > 0 && this._swap(0, o), this._heap.pop(), this._siftDown(), n;
  }
  /**
   * Replace the element with the highest priority in the queue with a new value.
   * @param {*} value The new value.
   * @returns {*} The replaced value.
   */
  replace(n) {
    const o = this.peek();
    return this._heap[0] = n, this._siftDown(), o;
  }
  /**
   * Compute the index for the parent of the node at index `i`.
   * @param {number} i The index of the node to get the parent of.
   * @returns {number} The index of the parent node.
   * @private
   */
  _parent(n) {
    return (n + 1 >>> 1) - 1;
  }
  /**
   * Compute the index for the left child of the node at index `i`.
   * @param {number} i The index of the node to get the left child of.
   * @returns {number} The index of the left child.
   * @private
   */
  _left(n) {
    return (n << 1) + 1;
  }
  /**
   * Compute the index for the right child of the node at index `i`.
   * @param {number} i The index of the node to get the right child of.
   * @returns {number} The index of the right child.
   * @private
   */
  _right(n) {
    return n + 1 << 1;
  }
  /**
   * Check if the element at index `i` is greater than the element at index `j`.
   * @param {number} i The index of the first element to compare.
   * @param {number} j The index of the second element to compare.
   * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
   * @private
   */
  _greater(n, o) {
    return this._comparator(this._heap[n], this._heap[o]);
  }
  /**
   * Swap the elements at indices `i` and `j`.
   * @param {number} i The index of the first element to swap.
   * @param {number} j The index of the second element to swap.
   * @private
   */
  _swap(n, o) {
    const u = this._heap[n];
    this._heap[n] = this._heap[o], this._heap[o] = u;
  }
  /**
   * Maintain the heap property by updating positions in the heap,
   * starting at the last element and moving up the heap.
   * @private
   */
  _siftUp() {
    let n = this.size - 1;
    for (; n > 0 && this._greater(n, this._parent(n)); )
      this._swap(n, this._parent(n)), n = this._parent(n);
  }
  /**
   * Maintain the heap property by updating positions in the heap,
   * starting at the first element and moving down the heap.
   * @private
   */
  _siftDown() {
    let n = 0;
    for (; this._left(n) < this.size && this._greater(this._left(n), n) || this._right(n) < this.size && this._greater(this._right(n), n); ) {
      const o = this._right(n) < this.size && this._greater(this._right(n), this._left(n)) ? this._right(n) : this._left(n);
      this._swap(n, o), n = o;
    }
  }
}
class CharTrie {
  constructor() {
    this.root = CharTrieNode.default();
  }
  /**
   * Adds one or more `texts` to the trie.
   * @param {string[]} texts The strings to add to the trie.
   */
  extend(n) {
    for (let o of n)
      this.push(o);
  }
  /**
   * Adds text to the trie.
   * @param {string} text The string to add to the trie.
   */
  push(n) {
    let o = this.root;
    for (let u of n) {
      let l = o.children.get(u);
      l === void 0 && (l = CharTrieNode.default(), o.children.set(u, l)), o = l;
    }
    o.isLeaf = !0;
  }
  /**
   * Searches the trie for all strings with a common prefix of `text`.
   * @param {string} text The common prefix to search for.
   * @yields {string} Each string in the trie that has `text` as a prefix.
   */
  *commonPrefixSearch(n) {
    let o = this.root, u = "";
    for (let l = 0; l < n.length && o !== void 0; ++l) {
      const h = n[l];
      u += h, o = o.children.get(h), o !== void 0 && o.isLeaf && (yield u);
    }
  }
}
class CharTrieNode {
  /**
   * Create a new CharTrieNode.
   * @param {boolean} isLeaf Whether the node is a leaf node or not.
   * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
   */
  constructor(n, o) {
    this.isLeaf = n, this.children = o;
  }
  /**
   * Returns a new `CharTrieNode` instance with default values.
   * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
   */
  static default() {
    return new CharTrieNode(!1, /* @__PURE__ */ new Map());
  }
}
class TokenLattice {
  /**
   * Creates a new TokenLattice instance.
   *
   * @param {string} sentence The input sentence to be tokenized.
   * @param {number} bosTokenId The beginning-of-sequence token ID.
   * @param {number} eosTokenId The end-of-sequence token ID.
   */
  constructor(n, o, u) {
    this.sentence = n, this.len = n.length, this.bosTokenId = o, this.eosTokenId = u, this.nodes = [], this.beginNodes = Array.from({ length: this.len + 1 }, () => []), this.endNodes = Array.from({ length: this.len + 1 }, () => []);
    const l = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0), h = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0);
    this.nodes.push(l.clone()), this.nodes.push(h.clone()), this.beginNodes[this.len].push(h), this.endNodes[0].push(l);
  }
  /**
   * Inserts a new token node into the token lattice.
   *
   * @param {number} pos The starting position of the token.
   * @param {number} length The length of the token.
   * @param {number} score The score of the token.
   * @param {number} tokenId The token ID of the token.
   */
  insert(n, o, u, l) {
    const h = this.nodes.length, a = new TokenLatticeNode(l, h, n, o, u);
    this.beginNodes[n].push(a), this.endNodes[n + o].push(a), this.nodes.push(a);
  }
  /**
   * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
   *
   * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
   */
  viterbi() {
    const n = this.len;
    let o = 0;
    for (; o <= n; ) {
      if (this.beginNodes[o].length == 0)
        return [];
      for (let f of this.beginNodes[o]) {
        f.prev = null;
        let g = 0, c = null;
        for (let s of this.endNodes[o]) {
          const t = s.backtraceScore + f.score;
          (c === null || t > g) && (c = s.clone(), g = t);
        }
        if (c !== null)
          f.prev = c, f.backtraceScore = g;
        else
          return [];
      }
      ++o;
    }
    const u = [], h = this.beginNodes[n][0].prev;
    if (h === null)
      return [];
    let a = h.clone();
    for (; a.prev !== null; )
      u.push(a.clone()), a = a.clone().prev.clone();
    return u.reverse(), u;
  }
  /**
   * @param {TokenLatticeNode} node
   * @returns {string} The array of nodes representing the most likely sequence of tokens.
   */
  piece(n) {
    return this.sentence.slice(n.pos, n.pos + n.length);
  }
  /**
   * @returns {Array} The array of nodes representing the most likely sequence of tokens.
   */
  tokens() {
    return this.viterbi().map((o) => this.piece(o));
  }
  /**
   * @returns {Array} The array of nodes representing the most likely sequence of tokens.
   */
  tokenIds() {
    return this.viterbi().map((o) => o.tokenId);
  }
}
class TokenLatticeNode {
  /**
   * Represents a node in a token lattice for a given sentence.
   * @param {number} tokenId The ID of the token associated with this node.
   * @param {number} nodeId The ID of this node.
   * @param {number} pos The starting position of the token in the sentence.
   * @param {number} length The length of the token.
   * @param {number} score The score associated with the token.
   */
  constructor(n, o, u, l, h) {
    this.tokenId = n, this.nodeId = o, this.pos = u, this.length = l, this.score = h, this.prev = null, this.backtraceScore = 0;
  }
  /**
   * Returns a clone of this node.
   * @returns {TokenLatticeNode} A clone of this node.
   */
  clone() {
    const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);
    return n.prev = this.prev, n.backtraceScore = this.backtraceScore, n;
  }
}
var TOKEN_TYPES = Object.freeze({
  Text: "Text",
  // The text between Jinja statements or expressions
  NumericLiteral: "NumericLiteral",
  // e.g., 123
  BooleanLiteral: "BooleanLiteral",
  // true or false
  StringLiteral: "StringLiteral",
  // 'string'
  Identifier: "Identifier",
  // Variables, functions, etc.
  Equals: "Equals",
  // =
  OpenParen: "OpenParen",
  // (
  CloseParen: "CloseParen",
  // )
  OpenStatement: "OpenStatement",
  // {%
  CloseStatement: "CloseStatement",
  // %}
  OpenExpression: "OpenExpression",
  // {{
  CloseExpression: "CloseExpression",
  // }}
  OpenSquareBracket: "OpenSquareBracket",
  // [
  CloseSquareBracket: "CloseSquareBracket",
  // ]
  OpenCurlyBracket: "OpenCurlyBracket",
  // {
  CloseCurlyBracket: "CloseCurlyBracket",
  // }
  Comma: "Comma",
  // ,
  Dot: "Dot",
  // .
  Colon: "Colon",
  // :
  Pipe: "Pipe",
  // |
  CallOperator: "CallOperator",
  // ()
  AdditiveBinaryOperator: "AdditiveBinaryOperator",
  // + -
  MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator",
  // * / %
  ComparisonBinaryOperator: "ComparisonBinaryOperator",
  // < > <= >= == !=
  UnaryOperator: "UnaryOperator",
  // ! - +
  // Keywords
  Set: "Set",
  If: "If",
  For: "For",
  In: "In",
  Is: "Is",
  NotIn: "NotIn",
  Else: "Else",
  EndIf: "EndIf",
  ElseIf: "ElseIf",
  EndFor: "EndFor",
  And: "And",
  Or: "Or",
  Not: "UnaryOperator"
}), KEYWORDS = Object.freeze({
  set: TOKEN_TYPES.Set,
  for: TOKEN_TYPES.For,
  in: TOKEN_TYPES.In,
  is: TOKEN_TYPES.Is,
  if: TOKEN_TYPES.If,
  else: TOKEN_TYPES.Else,
  endif: TOKEN_TYPES.EndIf,
  elif: TOKEN_TYPES.ElseIf,
  endfor: TOKEN_TYPES.EndFor,
  and: TOKEN_TYPES.And,
  or: TOKEN_TYPES.Or,
  not: TOKEN_TYPES.Not,
  "not in": TOKEN_TYPES.NotIn,
  // Literals
  true: TOKEN_TYPES.BooleanLiteral,
  false: TOKEN_TYPES.BooleanLiteral
}), Token = class {
  /**
   * Constructs a new Token.
   * @param {string} value The raw value as seen inside the source code.
   * @param {TokenType} type The type of token.
   */
  constructor(d, n) {
    this.value = d, this.type = n;
  }
};
function isWord(d) {
  return /\w/.test(d);
}
function isInteger(d) {
  return /[0-9]/.test(d);
}
var ORDERED_MAPPING_TABLE = [
  // Control sequences
  ["{%", TOKEN_TYPES.OpenStatement],
  ["%}", TOKEN_TYPES.CloseStatement],
  ["{{", TOKEN_TYPES.OpenExpression],
  ["}}", TOKEN_TYPES.CloseExpression],
  // Single character tokens
  ["(", TOKEN_TYPES.OpenParen],
  [")", TOKEN_TYPES.CloseParen],
  ["{", TOKEN_TYPES.OpenCurlyBracket],
  ["}", TOKEN_TYPES.CloseCurlyBracket],
  ["[", TOKEN_TYPES.OpenSquareBracket],
  ["]", TOKEN_TYPES.CloseSquareBracket],
  [",", TOKEN_TYPES.Comma],
  [".", TOKEN_TYPES.Dot],
  [":", TOKEN_TYPES.Colon],
  ["|", TOKEN_TYPES.Pipe],
  // Comparison operators
  ["<=", TOKEN_TYPES.ComparisonBinaryOperator],
  [">=", TOKEN_TYPES.ComparisonBinaryOperator],
  ["==", TOKEN_TYPES.ComparisonBinaryOperator],
  ["!=", TOKEN_TYPES.ComparisonBinaryOperator],
  ["<", TOKEN_TYPES.ComparisonBinaryOperator],
  [">", TOKEN_TYPES.ComparisonBinaryOperator],
  // Arithmetic operators
  ["+", TOKEN_TYPES.AdditiveBinaryOperator],
  ["-", TOKEN_TYPES.AdditiveBinaryOperator],
  ["*", TOKEN_TYPES.MultiplicativeBinaryOperator],
  ["/", TOKEN_TYPES.MultiplicativeBinaryOperator],
  ["%", TOKEN_TYPES.MultiplicativeBinaryOperator],
  // Assignment operator
  ["=", TOKEN_TYPES.Equals]
], ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([
  ["n", `
`],
  // New line
  ["t", "	"],
  // Horizontal tab
  ["r", "\r"],
  // Carriage return
  ["b", "\b"],
  // Backspace
  ["f", "\f"],
  // Form feed
  ["v", "\v"],
  // Vertical tab
  ["'", "'"],
  // Single quote
  ['"', '"'],
  // Double quote
  ["\\", "\\"]
  // Backslash
]);
function preprocess(d, n = {}) {
  return d.endsWith(`
`) && (d = d.slice(0, -1)), d = d.replace(/{#.*?#}/gs, "{##}"), n.lstrip_blocks && (d = d.replace(/^[ \t]*({[#%])/gm, "$1")), n.trim_blocks && (d = d.replace(/([#%]})\n/g, "$1")), d.replace(/{##}/g, "").replace(/-%}\s*/g, "%}").replace(/\s*{%-/g, "{%").replace(/-}}\s*/g, "}}").replace(/\s*{{-/g, "{{");
}
function tokenize(d, n = {}) {
  const o = [], u = preprocess(d, n);
  let l = 0;
  const h = (a) => {
    let f = "";
    for (; a(u[l]); ) {
      if (u[l] === "\\") {
        if (++l, l >= u.length)
          throw new SyntaxError("Unexpected end of input");
        const g = u[l++], c = ESCAPE_CHARACTERS.get(g);
        if (c === void 0)
          throw new SyntaxError(`Unexpected escaped character: ${g}`);
        f += c;
        continue;
      }
      if (f += u[l++], l >= u.length)
        throw new SyntaxError("Unexpected end of input");
    }
    return f;
  };
  e:
    for (; l < u.length; ) {
      const a = o.at(-1)?.type;
      if (a === void 0 || a === TOKEN_TYPES.CloseStatement || a === TOKEN_TYPES.CloseExpression) {
        let g = "";
        for (; l < u.length && // Keep going until we hit the next Jinja statement or expression
        !(u[l] === "{" && (u[l + 1] === "%" || u[l + 1] === "{")); )
          g += u[l++];
        if (g.length > 0) {
          o.push(new Token(g, TOKEN_TYPES.Text));
          continue;
        }
      }
      h((g) => /\s/.test(g));
      const f = u[l];
      if (f === "-" || f === "+") {
        const g = o.at(-1)?.type;
        if (g === TOKEN_TYPES.Text || g === void 0)
          throw new SyntaxError(`Unexpected character: ${f}`);
        switch (g) {
          case TOKEN_TYPES.Identifier:
          case TOKEN_TYPES.NumericLiteral:
          case TOKEN_TYPES.BooleanLiteral:
          case TOKEN_TYPES.StringLiteral:
          case TOKEN_TYPES.CloseParen:
          case TOKEN_TYPES.CloseSquareBracket:
            break;
          default: {
            ++l;
            const c = h(isInteger);
            o.push(
              new Token(`${f}${c}`, c.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)
            );
            continue;
          }
        }
      }
      for (const [g, c] of ORDERED_MAPPING_TABLE)
        if (u.slice(l, l + g.length) === g) {
          o.push(new Token(g, c)), l += g.length;
          continue e;
        }
      if (f === "'" || f === '"') {
        ++l;
        const g = h((c) => c !== f);
        o.push(new Token(g, TOKEN_TYPES.StringLiteral)), ++l;
        continue;
      }
      if (isInteger(f)) {
        const g = h(isInteger);
        o.push(new Token(g, TOKEN_TYPES.NumericLiteral));
        continue;
      }
      if (isWord(f)) {
        const g = h(isWord), c = Object.hasOwn(KEYWORDS, g) ? KEYWORDS[g] : TOKEN_TYPES.Identifier;
        c === TOKEN_TYPES.In && o.at(-1)?.type === TOKEN_TYPES.Not ? (o.pop(), o.push(new Token("not in", TOKEN_TYPES.NotIn))) : o.push(new Token(g, c));
        continue;
      }
      throw new SyntaxError(`Unexpected character: ${f}`);
    }
  return o;
}
var Statement = class {
  type = "Statement";
}, Program = class extends Statement {
  constructor(d) {
    super(), this.body = d;
  }
  type = "Program";
}, If = class extends Statement {
  constructor(d, n, o) {
    super(), this.test = d, this.body = n, this.alternate = o;
  }
  type = "If";
}, For = class extends Statement {
  constructor(d, n, o) {
    super(), this.loopvar = d, this.iterable = n, this.body = o;
  }
  type = "For";
}, SetStatement = class extends Statement {
  constructor(d, n) {
    super(), this.assignee = d, this.value = n;
  }
  type = "Set";
}, Expression = class extends Statement {
  type = "Expression";
}, MemberExpression = class extends Expression {
  constructor(d, n, o) {
    super(), this.object = d, this.property = n, this.computed = o;
  }
  type = "MemberExpression";
}, CallExpression = class extends Expression {
  constructor(d, n) {
    super(), this.callee = d, this.args = n;
  }
  type = "CallExpression";
}, Identifier = class extends Expression {
  /**
   * @param {string} value The name of the identifier
   */
  constructor(d) {
    super(), this.value = d;
  }
  type = "Identifier";
}, Literal = class extends Expression {
  constructor(d) {
    super(), this.value = d;
  }
  type = "Literal";
}, NumericLiteral = class extends Literal {
  type = "NumericLiteral";
}, StringLiteral = class extends Literal {
  type = "StringLiteral";
}, BooleanLiteral = class extends Literal {
  type = "BooleanLiteral";
}, ArrayLiteral = class extends Literal {
  type = "ArrayLiteral";
}, TupleLiteral = class extends Literal {
  type = "TupleLiteral";
}, ObjectLiteral = class extends Literal {
  type = "ObjectLiteral";
}, BinaryExpression = class extends Expression {
  constructor(d, n, o) {
    super(), this.operator = d, this.left = n, this.right = o;
  }
  type = "BinaryExpression";
}, FilterExpression = class extends Expression {
  constructor(d, n) {
    super(), this.operand = d, this.filter = n;
  }
  type = "FilterExpression";
}, TestExpression = class extends Expression {
  constructor(d, n, o) {
    super(), this.operand = d, this.negate = n, this.test = o;
  }
  type = "TestExpression";
}, UnaryExpression = class extends Expression {
  constructor(d, n) {
    super(), this.operator = d, this.argument = n;
  }
  type = "UnaryExpression";
}, SliceExpression = class extends Expression {
  constructor(d = void 0, n = void 0, o = void 0) {
    super(), this.start = d, this.stop = n, this.step = o;
  }
  type = "SliceExpression";
}, KeywordArgumentExpression = class extends Expression {
  constructor(d, n) {
    super(), this.key = d, this.value = n;
  }
  type = "KeywordArgumentExpression";
};
function parse(d) {
  const n = new Program([]);
  let o = 0;
  function u(D, I) {
    const $ = d[o++];
    if (!$ || $.type !== D)
      throw new Error(`Parser Error: ${I}. ${$.type} !== ${D}.`);
    return $;
  }
  function l() {
    switch (d[o].type) {
      case TOKEN_TYPES.Text:
        return f();
      case TOKEN_TYPES.OpenStatement:
        return g();
      case TOKEN_TYPES.OpenExpression:
        return c();
      default:
        throw new SyntaxError(`Unexpected token type: ${d[o].type}`);
    }
  }
  function h(...D) {
    return o + D.length <= d.length && D.some((I, $) => I !== d[o + $].type);
  }
  function a(...D) {
    return o + D.length <= d.length && D.every((I, $) => I === d[o + $].type);
  }
  function f() {
    return new StringLiteral(u(TOKEN_TYPES.Text, "Expected text token").value);
  }
  function g() {
    u(TOKEN_TYPES.OpenStatement, "Expected opening statement token");
    let D;
    switch (d[o].type) {
      case TOKEN_TYPES.Set:
        ++o, D = s(), u(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
        break;
      case TOKEN_TYPES.If:
        ++o, D = t(), u(TOKEN_TYPES.OpenStatement, "Expected {% token"), u(TOKEN_TYPES.EndIf, "Expected endif token"), u(TOKEN_TYPES.CloseStatement, "Expected %} token");
        break;
      case TOKEN_TYPES.For:
        ++o, D = r(), u(TOKEN_TYPES.OpenStatement, "Expected {% token"), u(TOKEN_TYPES.EndFor, "Expected endfor token"), u(TOKEN_TYPES.CloseStatement, "Expected %} token");
        break;
      default:
        throw new SyntaxError(`Unknown statement type: ${d[o].type}`);
    }
    return D;
  }
  function c() {
    u(TOKEN_TYPES.OpenExpression, "Expected opening expression token");
    const D = i();
    return u(TOKEN_TYPES.CloseExpression, "Expected closing expression token"), D;
  }
  function s() {
    const D = i();
    if (a(TOKEN_TYPES.Equals)) {
      ++o;
      const I = s();
      return new SetStatement(D, I);
    }
    return D;
  }
  function t() {
    const D = i();
    u(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
    const I = [], $ = [];
    for (; !(d[o]?.type === TOKEN_TYPES.OpenStatement && (d[o + 1]?.type === TOKEN_TYPES.ElseIf || d[o + 1]?.type === TOKEN_TYPES.Else || d[o + 1]?.type === TOKEN_TYPES.EndIf)); )
      I.push(l());
    if (d[o]?.type === TOKEN_TYPES.OpenStatement && d[o + 1]?.type !== TOKEN_TYPES.EndIf)
      if (++o, a(TOKEN_TYPES.ElseIf))
        u(TOKEN_TYPES.ElseIf, "Expected elseif token"), $.push(t());
      else
        for (u(TOKEN_TYPES.Else, "Expected else token"), u(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); !(d[o]?.type === TOKEN_TYPES.OpenStatement && d[o + 1]?.type === TOKEN_TYPES.EndIf); )
          $.push(l());
    return new If(D, I, $);
  }
  function e(D = !1) {
    const I = D ? F : i, $ = [I()], Q = a(TOKEN_TYPES.Comma);
    for (; Q && (++o, $.push(I()), !!a(TOKEN_TYPES.Comma)); )
      ;
    return Q ? new TupleLiteral($) : $[0];
  }
  function r() {
    const D = e(!0);
    if (!(D instanceof Identifier || D instanceof TupleLiteral))
      throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${D.type} instead`);
    u(TOKEN_TYPES.In, "Expected `in` keyword following loop variable");
    const I = i();
    u(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
    const $ = [];
    for (; h(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor); )
      $.push(l());
    return new For(D, I, $);
  }
  function i() {
    return p();
  }
  function p() {
    const D = m();
    if (a(TOKEN_TYPES.If)) {
      ++o;
      const I = m();
      u(TOKEN_TYPES.Else, "Expected else token");
      const $ = m();
      return new If(I, [D], [$]);
    }
    return D;
  }
  function m() {
    let D = _();
    for (; a(TOKEN_TYPES.Or); ) {
      const I = d[o];
      ++o;
      const $ = _();
      D = new BinaryExpression(I, D, $);
    }
    return D;
  }
  function _() {
    let D = b();
    for (; a(TOKEN_TYPES.And); ) {
      const I = d[o];
      ++o;
      const $ = b();
      D = new BinaryExpression(I, D, $);
    }
    return D;
  }
  function b() {
    let D;
    for (; a(TOKEN_TYPES.Not); ) {
      const I = d[o];
      ++o;
      const $ = b();
      D = new UnaryExpression(I, $);
    }
    return D ?? y();
  }
  function y() {
    let D = w();
    for (; a(TOKEN_TYPES.ComparisonBinaryOperator) || a(TOKEN_TYPES.In) || a(TOKEN_TYPES.NotIn); ) {
      const I = d[o];
      ++o;
      const $ = w();
      D = new BinaryExpression(I, D, $);
    }
    return D;
  }
  function w() {
    let D = L();
    for (; a(TOKEN_TYPES.AdditiveBinaryOperator); ) {
      const I = d[o];
      ++o;
      const $ = L();
      D = new BinaryExpression(I, D, $);
    }
    return D;
  }
  function T() {
    const D = A();
    return a(TOKEN_TYPES.OpenParen) ? S(D) : D;
  }
  function S(D) {
    let I = new CallExpression(D, E());
    return a(TOKEN_TYPES.OpenParen) && (I = S(I)), I;
  }
  function E() {
    u(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list");
    const D = O();
    return u(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list"), D;
  }
  function O() {
    const D = [];
    for (; !a(TOKEN_TYPES.CloseParen); ) {
      let I = i();
      if (a(TOKEN_TYPES.Equals)) {
        if (++o, !(I instanceof Identifier))
          throw new SyntaxError("Expected identifier for keyword argument");
        const $ = i();
        I = new KeywordArgumentExpression(I, $);
      }
      D.push(I), a(TOKEN_TYPES.Comma) && ++o;
    }
    return D;
  }
  function v() {
    const D = [];
    let I = !1;
    for (; !a(TOKEN_TYPES.CloseSquareBracket); )
      a(TOKEN_TYPES.Colon) ? (D.push(void 0), ++o, I = !0) : (D.push(i()), a(TOKEN_TYPES.Colon) && (++o, I = !0));
    if (D.length === 0)
      throw new SyntaxError("Expected at least one argument for member/slice expression");
    if (I) {
      if (D.length > 3)
        throw new SyntaxError("Expected 0-3 arguments for slice expression");
      return new SliceExpression(...D);
    }
    return D[0];
  }
  function A() {
    let D = F();
    for (; a(TOKEN_TYPES.Dot) || a(TOKEN_TYPES.OpenSquareBracket); ) {
      const I = d[o];
      ++o;
      let $;
      const Q = I.type !== TOKEN_TYPES.Dot;
      if (Q)
        $ = v(), u(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket");
      else if ($ = F(), $.type !== "Identifier")
        throw new SyntaxError("Expected identifier following dot operator");
      D = new MemberExpression(D, $, Q);
    }
    return D;
  }
  function L() {
    let D = j();
    for (; a(TOKEN_TYPES.MultiplicativeBinaryOperator); ) {
      const I = d[o];
      ++o;
      const $ = j();
      D = new BinaryExpression(I, D, $);
    }
    return D;
  }
  function j() {
    let D = B();
    for (; a(TOKEN_TYPES.Is); ) {
      ++o;
      const I = a(TOKEN_TYPES.Not);
      I && ++o;
      let $ = F();
      if ($ instanceof BooleanLiteral && ($ = new Identifier($.value.toString())), !($ instanceof Identifier))
        throw new SyntaxError("Expected identifier for the test");
      D = new TestExpression(D, I, $);
    }
    return D;
  }
  function B() {
    let D = T();
    for (; a(TOKEN_TYPES.Pipe); ) {
      ++o;
      let I = F();
      if (!(I instanceof Identifier))
        throw new SyntaxError("Expected identifier for the filter");
      a(TOKEN_TYPES.OpenParen) && (I = S(I)), D = new FilterExpression(D, I);
    }
    return D;
  }
  function F() {
    const D = d[o];
    switch (D.type) {
      case TOKEN_TYPES.NumericLiteral:
        return ++o, new NumericLiteral(Number(D.value));
      case TOKEN_TYPES.StringLiteral:
        return ++o, new StringLiteral(D.value);
      case TOKEN_TYPES.BooleanLiteral:
        return ++o, new BooleanLiteral(D.value === "true");
      case TOKEN_TYPES.Identifier:
        return ++o, new Identifier(D.value);
      case TOKEN_TYPES.OpenParen: {
        ++o;
        const I = e();
        if (d[o].type !== TOKEN_TYPES.CloseParen)
          throw new SyntaxError(`Expected closing parenthesis, got ${d[o].type} instead`);
        return ++o, I;
      }
      case TOKEN_TYPES.OpenSquareBracket: {
        ++o;
        const I = [];
        for (; !a(TOKEN_TYPES.CloseSquareBracket); )
          I.push(i()), a(TOKEN_TYPES.Comma) && ++o;
        return ++o, new ArrayLiteral(I);
      }
      case TOKEN_TYPES.OpenCurlyBracket: {
        ++o;
        const I = /* @__PURE__ */ new Map();
        for (; !a(TOKEN_TYPES.CloseCurlyBracket); ) {
          const $ = i();
          u(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal");
          const Q = i();
          I.set($, Q), a(TOKEN_TYPES.Comma) && ++o;
        }
        return ++o, new ObjectLiteral(I);
      }
      default:
        throw new SyntaxError(`Unexpected token: ${D.type}`);
    }
  }
  for (; o < d.length; )
    n.body.push(l());
  return n;
}
function range(d, n, o = 1) {
  n === void 0 && (n = d, d = 0);
  const u = [];
  for (let l = d; l < n; l += o)
    u.push(l);
  return u;
}
function slice(d, n, o, u = 1) {
  const l = Math.sign(u);
  l >= 0 ? (n = (n ??= 0) < 0 ? Math.max(d.length + n, 0) : Math.min(n, d.length), o = (o ??= d.length) < 0 ? Math.max(d.length + o, 0) : Math.min(o, d.length)) : (n = (n ??= d.length - 1) < 0 ? Math.max(d.length + n, -1) : Math.min(n, d.length - 1), o = (o ??= -1) < -1 ? Math.max(d.length + o, -1) : Math.min(o, d.length - 1));
  const h = [];
  for (let a = n; l * a < l * o; a += u)
    h.push(d[a]);
  return h;
}
function titleCase(d) {
  return d.replace(/\b\w/g, (n) => n.toUpperCase());
}
var RuntimeValue = class {
  type = "RuntimeValue";
  value;
  /**
   * A collection of built-in functions for this type.
   */
  builtins = /* @__PURE__ */ new Map();
  /**
   * Creates a new RuntimeValue.
   */
  constructor(d = void 0) {
    this.value = d;
  }
  /**
   * Determines truthiness or falsiness of the runtime value.
   * This function should be overridden by subclasses if it has custom truthiness criteria.
   * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.
   */
  __bool__() {
    return new BooleanValue(!!this.value);
  }
}, NumericValue = class extends RuntimeValue {
  type = "NumericValue";
}, StringValue = class extends RuntimeValue {
  type = "StringValue";
  builtins = /* @__PURE__ */ new Map([
    [
      "upper",
      new FunctionValue(() => new StringValue(this.value.toUpperCase()))
    ],
    [
      "lower",
      new FunctionValue(() => new StringValue(this.value.toLowerCase()))
    ],
    [
      "strip",
      new FunctionValue(() => new StringValue(this.value.trim()))
    ],
    [
      "title",
      new FunctionValue(() => new StringValue(titleCase(this.value)))
    ],
    ["length", new NumericValue(this.value.length)]
  ]);
}, BooleanValue = class extends RuntimeValue {
  type = "BooleanValue";
}, ObjectValue = class extends RuntimeValue {
  type = "ObjectValue";
  /**
   * NOTE: necessary to override since all JavaScript arrays are considered truthy,
   * while only non-empty Python arrays are consider truthy.
   *
   * e.g.,
   *  - JavaScript:  {} && 5 -> 5
   *  - Python:      {} and 5 -> {}
   */
  __bool__() {
    return new BooleanValue(this.value.size > 0);
  }
  builtins = /* @__PURE__ */ new Map([
    [
      "get",
      new FunctionValue(([d, n]) => {
        if (!(d instanceof StringValue))
          throw new Error(`Object key must be a string: got ${d.type}`);
        return this.value.get(d.value) ?? n ?? new NullValue();
      })
    ],
    [
      "items",
      new FunctionValue(() => new ArrayValue(
        Array.from(this.value.entries()).map(([d, n]) => new ArrayValue([new StringValue(d), n]))
      ))
    ]
  ]);
}, ArrayValue = class extends RuntimeValue {
  type = "ArrayValue";
  builtins = /* @__PURE__ */ new Map([["length", new NumericValue(this.value.length)]]);
  /**
   * NOTE: necessary to override since all JavaScript arrays are considered truthy,
   * while only non-empty Python arrays are consider truthy.
   *
   * e.g.,
   *  - JavaScript:  [] && 5 -> 5
   *  - Python:      [] and 5 -> []
   */
  __bool__() {
    return new BooleanValue(this.value.length > 0);
  }
}, TupleValue = class extends ArrayValue {
  type = "TupleValue";
}, FunctionValue = class extends RuntimeValue {
  type = "FunctionValue";
}, NullValue = class extends RuntimeValue {
  type = "NullValue";
}, UndefinedValue = class extends RuntimeValue {
  type = "UndefinedValue";
}, Environment = class {
  constructor(d) {
    this.parent = d;
  }
  /**
   * The variables declared in this environment.
   */
  variables = /* @__PURE__ */ new Map([
    [
      "namespace",
      new FunctionValue((d) => {
        if (d.length === 0)
          return new ObjectValue(/* @__PURE__ */ new Map());
        if (d.length !== 1 || !(d[0] instanceof ObjectValue))
          throw new Error("`namespace` expects either zero arguments or a single object argument");
        return d[0];
      })
    ]
  ]);
  /**
   * The tests available in this environment.
   */
  tests = /* @__PURE__ */ new Map([
    ["boolean", (d) => d.type === "BooleanValue"],
    ["callable", (d) => d instanceof FunctionValue],
    [
      "odd",
      (d) => {
        if (d.type !== "NumericValue")
          throw new Error(`Cannot apply test "odd" to type: ${d.type}`);
        return d.value % 2 !== 0;
      }
    ],
    [
      "even",
      (d) => {
        if (d.type !== "NumericValue")
          throw new Error(`Cannot apply test "even" to type: ${d.type}`);
        return d.value % 2 === 0;
      }
    ],
    ["false", (d) => d.type === "BooleanValue" && !d.value],
    ["true", (d) => d.type === "BooleanValue" && d.value],
    ["number", (d) => d.type === "NumericValue"],
    ["integer", (d) => d.type === "NumericValue" && Number.isInteger(d.value)],
    ["iterable", (d) => d instanceof ArrayValue || d instanceof StringValue],
    [
      "lower",
      (d) => {
        const n = d.value;
        return d.type === "StringValue" && n === n.toLowerCase();
      }
    ],
    [
      "upper",
      (d) => {
        const n = d.value;
        return d.type === "StringValue" && n === n.toUpperCase();
      }
    ],
    ["none", (d) => d.type === "NullValue"],
    ["defined", (d) => d.type !== "UndefinedValue"],
    ["undefined", (d) => d.type === "UndefinedValue"],
    ["equalto", (d, n) => d.value === n.value]
  ]);
  /**
   * Set the value of a variable in the current environment.
   */
  set(d, n) {
    return this.declareVariable(d, convertToRuntimeValues(n));
  }
  declareVariable(d, n) {
    if (this.variables.has(d))
      throw new SyntaxError(`Variable already declared: ${d}`);
    return this.variables.set(d, n), n;
  }
  // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {
  // 	const env = this.resolve(name);
  // 	env.variables.set(name, value);
  // 	return value;
  // }
  /**
   * Set variable in the current scope.
   * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.
   */
  setVariable(d, n) {
    return this.variables.set(d, n), n;
  }
  /**
   * Resolve the environment in which the variable is declared.
   * @param {string} name The name of the variable.
   * @returns {Environment} The environment in which the variable is declared.
   */
  resolve(d) {
    if (this.variables.has(d))
      return this;
    if (this.parent)
      return this.parent.resolve(d);
    throw new Error(`Unknown variable: ${d}`);
  }
  lookupVariable(d) {
    try {
      return this.resolve(d).variables.get(d) ?? new UndefinedValue();
    } catch {
      return new UndefinedValue();
    }
  }
}, Interpreter = class {
  global;
  constructor(d) {
    this.global = d ?? new Environment();
  }
  /**
   * Run the program.
   */
  run(d) {
    return this.evaluate(d, this.global);
  }
  /**
   * Evaluates expressions following the binary operation type.
   */
  evaluateBinaryExpression(d, n) {
    const o = this.evaluate(d.left, n);
    switch (d.operator.value) {
      case "and":
        return o.__bool__().value ? this.evaluate(d.right, n) : o;
      case "or":
        return o.__bool__().value ? o : this.evaluate(d.right, n);
    }
    const u = this.evaluate(d.right, n);
    switch (d.operator.value) {
      case "==":
        return new BooleanValue(o.value == u.value);
      case "!=":
        return new BooleanValue(o.value != u.value);
    }
    if (o instanceof UndefinedValue || u instanceof UndefinedValue)
      throw new Error("Cannot perform operation on undefined values");
    if (o instanceof NullValue || u instanceof NullValue)
      throw new Error("Cannot perform operation on null values");
    if (o instanceof NumericValue && u instanceof NumericValue)
      switch (d.operator.value) {
        case "+":
          return new NumericValue(o.value + u.value);
        case "-":
          return new NumericValue(o.value - u.value);
        case "*":
          return new NumericValue(o.value * u.value);
        case "/":
          return new NumericValue(o.value / u.value);
        case "%":
          return new NumericValue(o.value % u.value);
        case "<":
          return new BooleanValue(o.value < u.value);
        case ">":
          return new BooleanValue(o.value > u.value);
        case ">=":
          return new BooleanValue(o.value >= u.value);
        case "<=":
          return new BooleanValue(o.value <= u.value);
      }
    else if (o instanceof ArrayValue && u instanceof ArrayValue)
      switch (d.operator.value) {
        case "+":
          return new ArrayValue(o.value.concat(u.value));
      }
    else if (u instanceof ArrayValue) {
      const l = u.value.find((h) => h.value === o.value) !== void 0;
      switch (d.operator.value) {
        case "in":
          return new BooleanValue(l);
        case "not in":
          return new BooleanValue(!l);
      }
    }
    if (o instanceof StringValue || u instanceof StringValue)
      switch (d.operator.value) {
        case "+":
          return new StringValue(o.value.toString() + u.value.toString());
      }
    if (o instanceof StringValue && u instanceof StringValue)
      switch (d.operator.value) {
        case "in":
          return new BooleanValue(u.value.includes(o.value));
        case "not in":
          return new BooleanValue(!u.value.includes(o.value));
      }
    if (o instanceof StringValue && u instanceof ObjectValue)
      switch (d.operator.value) {
        case "in":
          return new BooleanValue(u.value.has(o.value));
        case "not in":
          return new BooleanValue(!u.value.has(o.value));
      }
    throw new SyntaxError(`Unknown operator "${d.operator.value}" between ${o.type} and ${u.type}`);
  }
  /**
   * Evaluates expressions following the filter operation type.
   */
  evaluateFilterExpression(d, n) {
    const o = this.evaluate(d.operand, n);
    if (d.filter.type === "Identifier") {
      const u = d.filter;
      if (o instanceof ArrayValue)
        switch (u.value) {
          case "list":
            return o;
          case "first":
            return o.value[0];
          case "last":
            return o.value[o.value.length - 1];
          case "length":
            return new NumericValue(o.value.length);
          case "reverse":
            return new ArrayValue(o.value.reverse());
          case "sort":
            return new ArrayValue(
              o.value.sort((l, h) => {
                if (l.type !== h.type)
                  throw new Error(`Cannot compare different types: ${l.type} and ${h.type}`);
                switch (l.type) {
                  case "NumericValue":
                    return l.value - h.value;
                  case "StringValue":
                    return l.value.localeCompare(h.value);
                  default:
                    throw new Error(`Cannot compare type: ${l.type}`);
                }
              })
            );
          default:
            throw new Error(`Unknown ArrayValue filter: ${u.value}`);
        }
      else if (o instanceof StringValue)
        switch (u.value) {
          case "length":
            return new NumericValue(o.value.length);
          case "upper":
            return new StringValue(o.value.toUpperCase());
          case "lower":
            return new StringValue(o.value.toLowerCase());
          case "title":
            return new StringValue(titleCase(o.value));
          case "capitalize":
            return new StringValue(o.value.charAt(0).toUpperCase() + o.value.slice(1));
          case "trim":
            return new StringValue(o.value.trim());
          default:
            throw new Error(`Unknown StringValue filter: ${u.value}`);
        }
      else if (o instanceof NumericValue)
        switch (u.value) {
          case "abs":
            return new NumericValue(Math.abs(o.value));
          default:
            throw new Error(`Unknown NumericValue filter: ${u.value}`);
        }
      else if (o instanceof ObjectValue)
        switch (u.value) {
          case "items":
            return new ArrayValue(
              Array.from(o.value.entries()).map(([l, h]) => new ArrayValue([new StringValue(l), h]))
            );
          case "length":
            return new NumericValue(o.value.size);
          default:
            throw new Error(`Unknown ObjectValue filter: ${u.value}`);
        }
      throw new Error(`Cannot apply filter "${u.value}" to type: ${o.type}`);
    } else if (d.filter.type === "CallExpression") {
      const u = d.filter;
      if (u.callee.type !== "Identifier")
        throw new Error(`Unknown filter: ${u.callee.type}`);
      const l = u.callee.value;
      if (o instanceof ArrayValue) {
        switch (l) {
          case "selectattr": {
            if (o.value.some((s) => !(s instanceof ObjectValue)))
              throw new Error("`selectattr` can only be applied to array of objects");
            if (u.args.some((s) => s.type !== "StringLiteral"))
              throw new Error("arguments of `selectattr` must be strings");
            const [h, a, f] = u.args.map((s) => this.evaluate(s, n));
            let g;
            if (a) {
              const s = n.tests.get(a.value);
              if (!s)
                throw new Error(`Unknown test: ${a.value}`);
              g = s;
            } else
              g = (...s) => s[0].__bool__().value;
            const c = o.value.filter((s) => {
              const t = s.value.get(h.value);
              return t ? g(t, f) : !1;
            });
            return new ArrayValue(c);
          }
        }
        throw new Error(`Unknown ArrayValue filter: ${l}`);
      } else
        throw new Error(`Cannot apply filter "${l}" to type: ${o.type}`);
    }
    throw new Error(`Unknown filter: ${d.filter.type}`);
  }
  /**
   * Evaluates expressions following the test operation type.
   */
  evaluateTestExpression(d, n) {
    const o = this.evaluate(d.operand, n), u = n.tests.get(d.test.value);
    if (!u)
      throw new Error(`Unknown test: ${d.test.value}`);
    const l = u(o);
    return new BooleanValue(d.negate ? !l : l);
  }
  /**
   * Evaluates expressions following the unary operation type.
   */
  evaluateUnaryExpression(d, n) {
    const o = this.evaluate(d.argument, n);
    switch (d.operator.value) {
      case "not":
        return new BooleanValue(!o.value);
      default:
        throw new SyntaxError(`Unknown operator: ${d.operator.value}`);
    }
  }
  evalProgram(d, n) {
    return this.evaluateBlock(d.body, n);
  }
  evaluateBlock(d, n) {
    let o = "";
    for (const u of d) {
      const l = this.evaluate(u, n);
      l.type !== "NullValue" && l.type !== "UndefinedValue" && (o += l.value);
    }
    return new StringValue(o);
  }
  evaluateIdentifier(d, n) {
    return n.lookupVariable(d.value);
  }
  evaluateCallExpression(d, n) {
    const o = [], u = /* @__PURE__ */ new Map();
    for (const h of d.args)
      if (h.type === "KeywordArgumentExpression") {
        const a = h;
        u.set(a.key.value, this.evaluate(a.value, n));
      } else
        o.push(this.evaluate(h, n));
    u.size > 0 && o.push(new ObjectValue(u));
    const l = this.evaluate(d.callee, n);
    if (l.type !== "FunctionValue")
      throw new Error(`Cannot call something that is not a function: got ${l.type}`);
    return l.value(o, n);
  }
  evaluateSliceExpression(d, n, o) {
    if (!(d instanceof ArrayValue || d instanceof StringValue))
      throw new Error("Slice object must be an array or string");
    const u = this.evaluate(n.start, o), l = this.evaluate(n.stop, o), h = this.evaluate(n.step, o);
    if (!(u instanceof NumericValue || u instanceof UndefinedValue))
      throw new Error("Slice start must be numeric or undefined");
    if (!(l instanceof NumericValue || l instanceof UndefinedValue))
      throw new Error("Slice stop must be numeric or undefined");
    if (!(h instanceof NumericValue || h instanceof UndefinedValue))
      throw new Error("Slice step must be numeric or undefined");
    return d instanceof ArrayValue ? new ArrayValue(slice(d.value, u.value, l.value, h.value)) : new StringValue(slice(Array.from(d.value), u.value, l.value, h.value).join(""));
  }
  evaluateMemberExpression(d, n) {
    const o = this.evaluate(d.object, n);
    let u;
    if (d.computed) {
      if (d.property.type === "SliceExpression")
        return this.evaluateSliceExpression(o, d.property, n);
      u = this.evaluate(d.property, n);
    } else
      u = new StringValue(d.property.value);
    let l;
    if (o instanceof ObjectValue) {
      if (!(u instanceof StringValue))
        throw new Error(`Cannot access property with non-string: got ${u.type}`);
      l = o.value.get(u.value) ?? o.builtins.get(u.value);
    } else if (o instanceof ArrayValue || o instanceof StringValue)
      if (u instanceof NumericValue)
        l = o.value.at(u.value), o instanceof StringValue && (l = new StringValue(o.value.at(u.value)));
      else if (u instanceof StringValue)
        l = o.builtins.get(u.value);
      else
        throw new Error(`Cannot access property with non-string/non-number: got ${u.type}`);
    else {
      if (!(u instanceof StringValue))
        throw new Error(`Cannot access property with non-string: got ${u.type}`);
      l = o.builtins.get(u.value);
    }
    return l instanceof RuntimeValue ? l : new UndefinedValue();
  }
  evaluateSet(d, n) {
    const o = this.evaluate(d.value, n);
    if (d.assignee.type === "Identifier") {
      const u = d.assignee.value;
      n.setVariable(u, o);
    } else if (d.assignee.type === "MemberExpression") {
      const u = d.assignee, l = this.evaluate(u.object, n);
      if (!(l instanceof ObjectValue))
        throw new Error("Cannot assign to member of non-object");
      if (u.property.type !== "Identifier")
        throw new Error("Cannot assign to member with non-identifier property");
      l.value.set(u.property.value, o);
    } else
      throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(d.assignee)}`);
    return new NullValue();
  }
  evaluateIf(d, n) {
    const o = this.evaluate(d.test, n);
    return this.evaluateBlock(o.__bool__().value ? d.body : d.alternate, n);
  }
  evaluateFor(d, n) {
    const o = new Environment(n), u = this.evaluate(d.iterable, o);
    if (!(u instanceof ArrayValue))
      throw new Error(`Expected iterable type in for loop: got ${u.type}`);
    let l = "";
    for (let h = 0; h < u.value.length; ++h) {
      const a = /* @__PURE__ */ new Map([
        ["index", new NumericValue(h + 1)],
        ["index0", new NumericValue(h)],
        ["revindex", new NumericValue(u.value.length - h)],
        ["revindex0", new NumericValue(u.value.length - h - 1)],
        ["first", new BooleanValue(h === 0)],
        ["last", new BooleanValue(h === u.value.length - 1)],
        ["length", new NumericValue(u.value.length)],
        ["previtem", h > 0 ? u.value[h - 1] : new UndefinedValue()],
        ["nextitem", h < u.value.length - 1 ? u.value[h + 1] : new UndefinedValue()]
      ]);
      o.setVariable("loop", new ObjectValue(a));
      const f = u.value[h];
      if (d.loopvar.type === "Identifier")
        o.setVariable(d.loopvar.value, f);
      else if (d.loopvar.type === "TupleLiteral") {
        const c = d.loopvar;
        if (f.type !== "ArrayValue")
          throw new Error(`Cannot unpack non-iterable type: ${f.type}`);
        const s = f;
        if (c.value.length !== s.value.length)
          throw new Error(`Too ${c.value.length > s.value.length ? "few" : "many"} items to unpack`);
        for (let t = 0; t < c.value.length; ++t) {
          if (c.value[t].type !== "Identifier")
            throw new Error(`Cannot unpack non-identifier type: ${c.value[t].type}`);
          o.setVariable(c.value[t].value, s.value[t]);
        }
      }
      const g = this.evaluateBlock(d.body, o);
      l += g.value;
    }
    return new StringValue(l);
  }
  evaluate(d, n) {
    if (d === void 0)
      return new UndefinedValue();
    switch (d.type) {
      case "Program":
        return this.evalProgram(d, n);
      case "Set":
        return this.evaluateSet(d, n);
      case "If":
        return this.evaluateIf(d, n);
      case "For":
        return this.evaluateFor(d, n);
      case "NumericLiteral":
        return new NumericValue(Number(d.value));
      case "StringLiteral":
        return new StringValue(d.value);
      case "BooleanLiteral":
        return new BooleanValue(d.value);
      case "ArrayLiteral":
        return new ArrayValue(d.value.map((o) => this.evaluate(o, n)));
      case "TupleLiteral":
        return new TupleValue(d.value.map((o) => this.evaluate(o, n)));
      case "ObjectLiteral": {
        const o = /* @__PURE__ */ new Map();
        for (const [u, l] of d.value) {
          const h = this.evaluate(u, n);
          if (!(h instanceof StringValue))
            throw new Error(`Object keys must be strings: got ${h.type}`);
          o.set(h.value, this.evaluate(l, n));
        }
        return new ObjectValue(o);
      }
      case "Identifier":
        return this.evaluateIdentifier(d, n);
      case "CallExpression":
        return this.evaluateCallExpression(d, n);
      case "MemberExpression":
        return this.evaluateMemberExpression(d, n);
      case "UnaryExpression":
        return this.evaluateUnaryExpression(d, n);
      case "BinaryExpression":
        return this.evaluateBinaryExpression(d, n);
      case "FilterExpression":
        return this.evaluateFilterExpression(d, n);
      case "TestExpression":
        return this.evaluateTestExpression(d, n);
      default:
        throw new SyntaxError(`Unknown node type: ${d.type}`);
    }
  }
};
function convertToRuntimeValues(d) {
  switch (typeof d) {
    case "number":
      return new NumericValue(d);
    case "string":
      return new StringValue(d);
    case "boolean":
      return new BooleanValue(d);
    case "object":
      return d === null ? new NullValue() : Array.isArray(d) ? new ArrayValue(d.map(convertToRuntimeValues)) : new ObjectValue(
        new Map(Object.entries(d).map(([n, o]) => [n, convertToRuntimeValues(o)]))
      );
    case "function":
      return new FunctionValue((n, o) => {
        const u = d(...n.map((l) => l.value)) ?? null;
        return convertToRuntimeValues(u);
      });
    default:
      throw new Error(`Cannot convert to runtime value: ${d}`);
  }
}
var Template = class {
  parsed;
  /**
   * @param {string} template The template string
   */
  constructor(d) {
    const n = tokenize(d, {
      lstrip_blocks: !0,
      trim_blocks: !0
    });
    this.parsed = parse(n);
  }
  render(d) {
    const n = new Environment();
    n.set("false", !1), n.set("true", !0), n.set("raise_exception", (l) => {
      throw new Error(l);
    }), n.set("range", range);
    for (const [l, h] of Object.entries(d))
      n.set(l, h);
    return new Interpreter(n).run(this.parsed).value;
  }
};
async function loadTokenizer(d, n) {
  const o = await Promise.all([
    getModelJSON(d, "tokenizer.json", !0, n),
    getModelJSON(d, "tokenizer_config.json", !0, n)
  ]);
  return n.legacy !== null && (o[1].legacy = n.legacy), o;
}
function regexSplit(d, n) {
  const o = [];
  let u = 0;
  for (const l of d.matchAll(n)) {
    const h = l[0];
    u < l.index && o.push(d.slice(u, l.index)), h.length > 0 && o.push(h), u = l.index + h.length;
  }
  return u < d.length && o.push(d.slice(u)), o;
}
function createPattern(d, n = !0) {
  if (d.Regex !== void 0) {
    let o = d.Regex.replace(/\\([#&~])/g, "$1");
    for (const [u, l] of PROBLEMATIC_REGEX_MAP)
      o = o.replaceAll(u, l);
    return new RegExp(o, "gu");
  } else if (d.String !== void 0) {
    const o = escapeRegExp(d.String);
    return new RegExp(n ? o : `(${o})`, "gu");
  } else
    return console.warn("Unknown pattern type:", d), null;
}
function objectToMap(d) {
  return new Map(Object.entries(d));
}
function prepareTensorForDecode(d) {
  const n = d.dims;
  switch (n.length) {
    case 1:
      return d.tolist();
    case 2:
      if (n[0] !== 1)
        throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");
      return d.tolist()[0];
    default:
      throw new Error(`Expected tensor to have 1-2 dimensions, got ${n.length}.`);
  }
}
function clean_up_tokenization(d) {
  return d.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n\'t/g, "n't").replace(/ \'m/g, "'m").replace(/ \'s/g, "'s").replace(/ \'ve/g, "'ve").replace(/ \'re/g, "'re");
}
function remove_accents(d) {
  return d.replace(/[\u0300-\u036f]/g, "");
}
function lowercase_and_remove_accent(d) {
  return remove_accents(d.toLowerCase());
}
function fuse(d, n, o) {
  const u = [];
  let l = 0;
  for (; l < d.length; ) {
    if (u.push(d[l]), (o.get(d[l]) ?? n) !== n) {
      ++l;
      continue;
    }
    for (; l < d.length && (o.get(d[l]) ?? n) === n; )
      ++l;
  }
  return u;
}
function whitespace_split(d) {
  return d.match(/\S+/g) || [];
}
const PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E", PROBLEMATIC_REGEX_MAP = /* @__PURE__ */ new Map([
  // This uses the case insensitive group modifier, which is not supported in JavaScript.
  // When parsing the regex, an "Invalid group" error is thrown.
  ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"]
]);
class AddedToken {
  /**
   * Creates a new instance of AddedToken.
   * @param {Object} config Added token configuration object.
   * @param {string} config.content The content of the added token.
   * @param {number} config.id The id of the added token.
   * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
   * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
   * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
   * @param {boolean} [config.normalized=false] Whether this token should be normalized.
   * @param {boolean} [config.special=false] Whether this token is special.
   */
  constructor(n) {
    this.content = n.content, this.id = n.id, this.single_word = n.single_word ?? !1, this.lstrip = n.lstrip ?? !1, this.rstrip = n.rstrip ?? !1, this.special = n.special ?? !1, this.normalized = n.normalized ?? null;
  }
}
class TokenizerModel extends Callable {
  /**
   * Creates a new instance of TokenizerModel.
   * @param {Object} config The configuration object for the TokenizerModel.
   */
  constructor(n) {
    super(), this.config = n, this.vocab = [], this.tokens_to_ids = /* @__PURE__ */ new Map(), this.unk_token_id = void 0, this.unk_token = void 0, this.end_of_word_suffix = void 0, this.fuse_unk = this.config.fuse_unk ?? !1;
  }
  /**
   * Instantiates a new TokenizerModel instance based on the configuration object provided.
   * @param {Object} config The configuration object for the TokenizerModel.
   * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
   * @returns {TokenizerModel} A new instance of a TokenizerModel.
   * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
   */
  static fromConfig(n, ...o) {
    switch (n.type) {
      case "WordPiece":
        return new WordPieceTokenizer(n);
      case "Unigram":
        return new Unigram(n, ...o);
      case "BPE":
        return new BPE(n);
      default:
        if (n.vocab)
          return new LegacyTokenizerModel(n, ...o);
        throw new Error(`Unknown TokenizerModel type: ${n.type}`);
    }
  }
  /**
   * Internal function to call the TokenizerModel instance.
   * @param {string[]} tokens The tokens to encode.
   * @returns {string[]} The encoded token IDs.
   */
  _call(n) {
    let o = this.encode(n);
    return this.fuse_unk && (o = fuse(o, this.unk_token_id, this.tokens_to_ids)), o;
  }
  /**
   * Encodes a list of tokens into a list of token IDs.
   * @param {string[]} tokens The tokens to encode.
   * @returns {string[]} The encoded tokens.
   * @throws Will throw an error if not implemented in a subclass.
   */
  encode(n) {
    throw Error("encode should be implemented in subclass.");
  }
  /**
   * Converts a list of tokens into a list of token IDs.
   * @param {string[]} tokens The tokens to convert.
   * @returns {number[]} The converted token IDs.
   */
  convert_tokens_to_ids(n) {
    return n.map((o) => this.tokens_to_ids.get(o) ?? this.unk_token_id);
  }
  /**
   * Converts a list of token IDs into a list of tokens.
   * @param {number[]} ids The token IDs to convert.
   * @returns {string[]} The converted tokens.
   */
  convert_ids_to_tokens(n) {
    return n.map((o) => this.vocab[o] ?? this.unk_token);
  }
}
class WordPieceTokenizer extends TokenizerModel {
  /**
   * @param {Object} config The configuration object.
   * @param {Object} config.vocab A mapping of tokens to ids.
   * @param {string} config.unk_token The unknown token string.
   * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.
   * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.
   */
  constructor(n) {
    super(n), this.tokens_to_ids = objectToMap(n.vocab), this.unk_token_id = this.tokens_to_ids.get(n.unk_token), this.unk_token = n.unk_token, this.max_input_chars_per_word = n.max_input_chars_per_word ?? 100, this.vocab = new Array(this.tokens_to_ids.size);
    for (const [o, u] of this.tokens_to_ids)
      this.vocab[u] = o;
  }
  /**
   * Encodes an array of tokens using WordPiece encoding.
   * @param {string[]} tokens The tokens to encode.
   * @returns {string[]} An array of encoded tokens.
   */
  encode(n) {
    const o = [];
    for (const u of n) {
      const l = [...u];
      if (l.length > this.max_input_chars_per_word) {
        o.push(this.unk_token);
        continue;
      }
      let h = !1, a = 0;
      const f = [];
      for (; a < l.length; ) {
        let g = l.length, c = null;
        for (; a < g; ) {
          let s = l.slice(a, g).join("");
          if (a > 0 && (s = this.config.continuing_subword_prefix + s), this.tokens_to_ids.has(s)) {
            c = s;
            break;
          }
          --g;
        }
        if (c === null) {
          h = !0;
          break;
        }
        f.push(c), a = g;
      }
      h ? o.push(this.unk_token) : o.push(...f);
    }
    return o;
  }
}
class Unigram extends TokenizerModel {
  /**
   * Create a new Unigram tokenizer model.
   * @param {Object} config The configuration object for the Unigram model.
   * @param {number} config.unk_id The ID of the unknown token
   * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.
   * @param {Object} moreConfig Additional configuration object for the Unigram model.
   */
  constructor(n, o) {
    super(n);
    const u = n.vocab.length;
    this.vocab = new Array(u), this.scores = new Array(u);
    for (let l = 0; l < u; ++l) {
      const h = n.vocab[l];
      this.vocab[l] = h[0], this.scores[l] = h[1];
    }
    this.unk_token_id = n.unk_id, this.unk_token = this.vocab[n.unk_id], this.tokens_to_ids = new Map(this.vocab.map((l, h) => [l, h])), this.bosToken = " ", this.bosTokenId = this.tokens_to_ids.get(this.bosToken), this.eosToken = o.eos_token, this.eosTokenId = this.tokens_to_ids.get(this.eosToken), this.unkToken = this.vocab[this.unk_token_id], this.minScore = min(this.scores)[0], this.unkScore = this.minScore - 10, this.scores[this.unk_token_id] = this.unkScore, this.trie = new CharTrie(), this.trie.extend(this.vocab), this.fuse_unk = !0;
  }
  /**
   * Populates lattice nodes.
   * @param {TokenLattice} lattice The token lattice to populate with nodes.
   */
  populateNodes(n) {
    const o = n.sentence, u = o.length;
    let l = 0;
    for (; l < u; ) {
      let a = !1;
      for (let f of this.trie.commonPrefixSearch(o.slice(l))) {
        const g = this.tokens_to_ids.get(f), c = this.scores[g], s = f.length;
        n.insert(l, s, c, g), !a && s === 1 && (a = !0);
      }
      a || n.insert(l, 1, this.unkScore, this.unk_token_id), l += 1;
    }
  }
  /**
   * Encodes an array of tokens into an array of subtokens using the unigram model.
   *
   * @param {string} normalized The normalized string.
   * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.
   */
  tokenize(n) {
    const o = new TokenLattice(n, this.bosTokenId, this.eosTokenId);
    return this.populateNodes(o), o.tokens();
  }
  /**
   * Encodes an array of tokens using Unigram encoding.
   * @param {string[]} tokens The tokens to encode.
   * @returns {string[]} An array of encoded tokens.
   */
  encode(n) {
    const o = [];
    for (const u of n) {
      const l = this.tokenize(u);
      o.push(...l);
    }
    return o;
  }
}
const BYTES_TO_UNICODE = (() => {
  const d = [
    ...Array.from({ length: 94 }, (l, h) => h + 33),
    ...Array.from({ length: 12 }, (l, h) => h + 161),
    ...Array.from({ length: 82 }, (l, h) => h + 174)
  ], n = d.slice();
  let o = 0;
  for (let l = 0; l < 256; ++l)
    d.includes(l) || (d.push(l), n.push(256 + o), o += 1);
  const u = n.map((l) => String.fromCharCode(l));
  return Object.fromEntries(d.map((l, h) => [l, u[h]]));
})(), UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);
class BPE extends TokenizerModel {
  /**
   * Create a BPE instance.
   * @param {Object} config The configuration object for BPE.
   * @param {Object} config.vocab A mapping of tokens to ids.
   * @param {string[]} config.merges An array of BPE merges as strings.
   * @param {string} config.unk_token The unknown token used for out of vocabulary words.
   * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.
   * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.
   * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)
   * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.
   */
  constructor(n) {
    super(n), this.BPE_SPLIT_TOKEN = " ", this.tokens_to_ids = objectToMap(n.vocab), this.unk_token_id = this.tokens_to_ids.get(n.unk_token), this.unk_token = n.unk_token, this.vocab = new Array(this.tokens_to_ids.size);
    for (const [o, u] of this.tokens_to_ids)
      this.vocab[u] = o;
    this.bpe_ranks = new Map(n.merges.map((o, u) => [o, u])), this.merges = n.merges.map((o) => o.split(this.BPE_SPLIT_TOKEN)), this.end_of_word_suffix = n.end_of_word_suffix, this.continuing_subword_suffix = n.continuing_subword_suffix ?? null, this.byte_fallback = this.config.byte_fallback ?? !1, this.byte_fallback && (this.text_encoder = new TextEncoder()), this.ignore_merges = this.config.ignore_merges ?? !1, this.cache = /* @__PURE__ */ new Map();
  }
  /**
   * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
   * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
   * @param {string} token The token to encode.
   * @returns {string[]} The BPE encoded tokens.
   */
  bpe(n) {
    if (n.length === 0)
      return [];
    const o = this.cache.get(n);
    if (o !== void 0)
      return o;
    const u = Array.from(n);
    this.end_of_word_suffix && (u[u.length - 1] += this.end_of_word_suffix);
    let l = [];
    if (u.length > 1) {
      const h = new PriorityQueue((g, c) => g.score < c.score);
      let a = {
        token: u[0],
        bias: 0,
        prev: null,
        next: null
      }, f = a;
      for (let g = 1; g < u.length; ++g) {
        const c = {
          bias: g / u.length,
          // Add fractional component to break ties
          token: u[g],
          prev: f,
          next: null
        };
        f.next = c, this._add_node(h, f), f = c;
      }
      for (; !h.isEmpty(); ) {
        const g = h.pop();
        if (g.deleted || !g.next || g.next.deleted) continue;
        if (g.deleted = !0, g.next.deleted = !0, g.prev) {
          const s = { ...g.prev };
          g.prev.deleted = !0, g.prev = s, s.prev ? s.prev.next = s : a = s;
        }
        const c = {
          token: g.token + g.next.token,
          bias: g.bias,
          prev: g.prev,
          next: g.next.next
        };
        c.prev ? (c.prev.next = c, this._add_node(h, c.prev)) : a = c, c.next && (c.next.prev = c, this._add_node(h, c));
      }
      for (let g = a; g !== null; g = g.next)
        l.push(g.token);
    } else
      l = u;
    if (this.continuing_subword_suffix)
      for (let h = 0; h < l.length - 1; ++h)
        l[h] += this.continuing_subword_suffix;
    return this.cache.set(n, l), l;
  }
  /**
   * Helper function to add a node to the priority queue.
   * @param {PriorityQueue} queue 
   * @param {BPENode} node
   * @private
   */
  _add_node(n, o) {
    const u = this.bpe_ranks.get(o.token + this.BPE_SPLIT_TOKEN + o.next.token);
    u !== void 0 && (o.score = u + o.bias, n.push(o));
  }
  /**
   * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
   * @param {string[]} tokens The input sequence of tokens to encode.
   * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
   */
  encode(n) {
    const o = [];
    for (const u of n) {
      if (this.ignore_merges && this.tokens_to_ids.has(u)) {
        o.push(u);
        continue;
      }
      const l = this.bpe(u);
      for (const h of l)
        this.tokens_to_ids.has(h) ? o.push(h) : this.byte_fallback ? o.push(
          ...Array.from(this.text_encoder.encode(h)).map((a) => `<0x${a.toString(16).toUpperCase().padStart(2, "0")}>`)
        ) : o.push(this.unk_token);
    }
    return o;
  }
}
class LegacyTokenizerModel extends TokenizerModel {
  /**
   * Create a LegacyTokenizerModel instance.
   * @param {Object} config The configuration object for LegacyTokenizerModel.
   * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.
   * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.
   */
  constructor(n, o) {
    super(n), this.tokens_to_ids = objectToMap(
      o.target_lang ? n.vocab[o.target_lang] : n.vocab
    ), this.bos_token = o.bos_token, this.bos_token_id = this.tokens_to_ids.get(this.bos_token), this.eos_token = o.eos_token, this.eos_token_id = this.tokens_to_ids.get(this.eos_token), this.pad_token = o.pad_token, this.pad_token_id = this.tokens_to_ids.get(this.pad_token), this.unk_token = o.unk_token, this.unk_token_id = this.tokens_to_ids.get(this.unk_token), this.vocab = new Array(this.tokens_to_ids.size);
    for (const [u, l] of this.tokens_to_ids)
      this.vocab[l] = u;
  }
  encode(n) {
    return n;
  }
}
class Normalizer extends Callable {
  /**
   * @param {Object} config The configuration object for the normalizer.
   */
  constructor(n) {
    super(), this.config = n;
  }
  /**
   * Factory method for creating normalizers from config objects.
   * @static
   * @param {Object} config The configuration object for the normalizer.
   * @returns {Normalizer} A Normalizer object.
   * @throws {Error} If an unknown Normalizer type is specified in the config.
   */
  static fromConfig(n) {
    if (n === null) return null;
    switch (n.type) {
      case "BertNormalizer":
        return new BertNormalizer(n);
      case "Precompiled":
        return new Precompiled(n);
      case "Sequence":
        return new NormalizerSequence(n);
      case "Replace":
        return new Replace(n);
      case "NFC":
        return new NFC(n);
      case "NFKC":
        return new NFKC(n);
      case "NFKD":
        return new NFKD(n);
      case "Strip":
        return new StripNormalizer(n);
      case "StripAccents":
        return new StripAccents(n);
      case "Lowercase":
        return new Lowercase(n);
      case "Prepend":
        return new Prepend(n);
      default:
        throw new Error(`Unknown Normalizer type: ${n.type}`);
    }
  }
  /**
   * Normalize the input text.
   * @abstract
   * @param {string} text The text to normalize.
   * @returns {string} The normalized text.
   * @throws {Error} If this method is not implemented in a subclass.
   */
  normalize(n) {
    throw Error("normalize should be implemented in subclass.");
  }
  /**
   * Alias for {@link Normalizer#normalize}.
   * @param {string} text The text to normalize.
   * @returns {string} The normalized text.
   */
  _call(n) {
    return this.normalize(n);
  }
}
class Replace extends Normalizer {
  /**
   * Normalize the input text by replacing the pattern with the content.
   * @param {string} text The input text to be normalized.
   * @returns {string} The normalized text after replacing the pattern with the content.
   */
  normalize(n) {
    const o = createPattern(this.config.pattern);
    return o === null ? n : n.replaceAll(o, this.config.content);
  }
}
class NFC extends Normalizer {
  /**
   * Normalize the input text by applying Unicode normalization form C (NFC).
   * @param {string} text The input text to be normalized.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return n = n.normalize("NFC"), n;
  }
}
class NFKC extends Normalizer {
  /**
   * Normalize text using NFKC normalization.
   * @param {string} text The text to be normalized.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return n = n.normalize("NFKC"), n;
  }
}
class NFKD extends Normalizer {
  /**
   * Normalize text using NFKD normalization.
   * @param {string} text The text to be normalized.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return n = n.normalize("NFKD"), n;
  }
}
class StripNormalizer extends Normalizer {
  /**
   * Strip leading and/or trailing whitespace from the input text.
   * @param {string} text The input text.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return this.config.strip_left && this.config.strip_right ? n = n.trim() : (this.config.strip_left && (n = n.trimStart()), this.config.strip_right && (n = n.trimEnd())), n;
  }
}
class StripAccents extends Normalizer {
  /**
   * Remove all accents from the text.
   * @param {string} text The input text.
   * @returns {string} The normalized text without accents.
   */
  normalize(n) {
    return n = remove_accents(n), n;
  }
}
class Lowercase extends Normalizer {
  /**
   * Lowercases the input string.
   * @param {string} text The text to normalize.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return n = n.toLowerCase(), n;
  }
}
class Prepend extends Normalizer {
  /**
   * Prepends the input string.
   * @param {string} text The text to normalize.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return n = this.config.prepend + n, n;
  }
}
class NormalizerSequence extends Normalizer {
  /**
  * Create a new instance of NormalizerSequence.
  * @param {Object} config The configuration object.
  * @param {Object[]} config.normalizers An array of Normalizer configuration objects.
  */
  constructor(n) {
    super(n), this.normalizers = n.normalizers.map((o) => Normalizer.fromConfig(o));
  }
  /**
  * Apply a sequence of Normalizers to the input text.
  * @param {string} text The text to normalize.
  * @returns {string} The normalized text.
  */
  normalize(n) {
    return this.normalizers.reduce((o, u) => u.normalize(o), n);
  }
}
class BertNormalizer extends Normalizer {
  /**
   * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
   *
   * @param {string} text The input text to tokenize.
   * @returns {string} The tokenized text with whitespace added around CJK characters.
   */
  _tokenize_chinese_chars(n) {
    const o = [];
    for (let u = 0; u < n.length; ++u) {
      const l = n[u], h = l.charCodeAt(0);
      this._is_chinese_char(h) ? (o.push(" "), o.push(l), o.push(" ")) : o.push(l);
    }
    return o.join("");
  }
  /**
   * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.
   *
   * A "chinese character" is defined as anything in the CJK Unicode block:
   * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
   *
   * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.
   * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.
   * Those alphabets are used to write space-separated words, so they are not treated specially
   * and are handled like all other languages.
   *
   * @param {number} cp The Unicode codepoint to check.
   * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.
   */
  _is_chinese_char(n) {
    return n >= 19968 && n <= 40959 || n >= 13312 && n <= 19903 || n >= 131072 && n <= 173791 || n >= 173824 && n <= 177983 || n >= 177984 && n <= 178207 || n >= 178208 && n <= 183983 || n >= 63744 && n <= 64255 || n >= 194560 && n <= 195103;
  }
  /**
   * Strips accents from the given text.
   * @param {string} text The text to strip accents from.
   * @returns {string} The text with accents removed.
   */
  stripAccents(n) {
    return n.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  }
  /**
   * Checks whether `char` is a control character.
   * @param {string} char The character to check.
   * @returns {boolean} Whether `char` is a control character.
   * @private
   */
  _is_control(n) {
    switch (n) {
      case "	":
      case `
`:
      case "\r":
        return !1;
      default:
        return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$", "u").test(n);
    }
  }
  /**
   * Performs invalid character removal and whitespace cleanup on text.
   * @param {string} text The text to clean.
   * @returns {string} The cleaned text.
   * @private
   */
  _clean_text(n) {
    const o = [];
    for (const u of n) {
      const l = u.charCodeAt(0);
      l === 0 || l === 65533 || this._is_control(u) || (/^\s$/.test(u) ? o.push(" ") : o.push(u));
    }
    return o.join("");
  }
  /**
   * Normalizes the given text based on the configuration.
   * @param {string} text The text to normalize.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return this.config.clean_text && (n = this._clean_text(n)), this.config.handle_chinese_chars && (n = this._tokenize_chinese_chars(n)), this.config.lowercase ? (n = n.toLowerCase(), this.config.strip_accents !== !1 && (n = this.stripAccents(n))) : this.config.strip_accents && (n = this.stripAccents(n)), n;
  }
}
class PreTokenizer extends Callable {
  /**
  * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.
  *
  * @static
  * @param {Object} config A configuration object for the pre-tokenizer.
  * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.
  * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.
  */
  static fromConfig(n) {
    if (n === null) return null;
    switch (n.type) {
      case "BertPreTokenizer":
        return new BertPreTokenizer(n);
      case "Sequence":
        return new PreTokenizerSequence(n);
      case "Whitespace":
        return new WhitespacePreTokenizer(n);
      case "WhitespaceSplit":
        return new WhitespaceSplit(n);
      case "Metaspace":
        return new MetaspacePreTokenizer(n);
      case "ByteLevel":
        return new ByteLevelPreTokenizer(n);
      case "Split":
        return new SplitPreTokenizer(n);
      case "Punctuation":
        return new PunctuationPreTokenizer(n);
      case "Digits":
        return new DigitsPreTokenizer(n);
      case "Replace":
        return new ReplacePreTokenizer(n);
      default:
        throw new Error(`Unknown PreTokenizer type: ${n.type}`);
    }
  }
  /**
   * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
   *
   * @abstract
   * @param {string} text The text to pre-tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} The pre-tokenized text.
   * @throws {Error} If the method is not implemented in the subclass.
   */
  pre_tokenize_text(n, o) {
    throw Error("pre_tokenize_text should be implemented in subclass.");
  }
  /**
   * Tokenizes the given text into pre-tokens.
   * @param {string|string[]} text The text or array of texts to pre-tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of pre-tokens.
   */
  pre_tokenize(n, o) {
    return (Array.isArray(n) ? n.map((u) => this.pre_tokenize_text(u, o)) : this.pre_tokenize_text(n, o)).flat();
  }
  /**
   * Alias for {@link PreTokenizer#pre_tokenize}.
   * @param {string|string[]} text The text or array of texts to pre-tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of pre-tokens.
   */
  _call(n, o) {
    return this.pre_tokenize(n, o);
  }
}
class BertPreTokenizer extends PreTokenizer {
  /**
   * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
   * similar to that used in the original implementation of BERT.
   * 
   * @param {Object} config The configuration object.
   */
  constructor(n) {
    super(), this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, "gu");
  }
  /**
   * Tokenizes a single text using the BERT pre-tokenization scheme.
   * 
   * @param {string} text The text to tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens.
   */
  pre_tokenize_text(n, o) {
    return n.trim().match(this.pattern) || [];
  }
}
class ByteLevelPreTokenizer extends PreTokenizer {
  /**
   * Creates a new instance of the `ByteLevelPreTokenizer` class.
   * @param {Object} config The configuration object.
   */
  constructor(n) {
    super(), this.config = n, this.add_prefix_space = this.config.add_prefix_space, this.trim_offsets = this.config.trim_offsets, this.use_regex = this.config.use_regex ?? !0, this.pattern = new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+", "gu"), this.byte_encoder = BYTES_TO_UNICODE, this.text_encoder = new TextEncoder();
  }
  /**
   * Tokenizes a single piece of text using byte-level tokenization.
   * @param {string} text The text to tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens.
   */
  pre_tokenize_text(n, o) {
    return this.add_prefix_space && !n.startsWith(" ") && (n = " " + n), (this.use_regex ? n.match(this.pattern) || [] : [n]).map(
      (l) => Array.from(this.text_encoder.encode(l), (h) => this.byte_encoder[h]).join("")
    );
  }
}
class SplitPreTokenizer extends PreTokenizer {
  /**
   * @param {Object} config The configuration options for the pre-tokenizer.
   * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
   * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.
   * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.
   * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
   * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.
   */
  constructor(n) {
    super(), this.config = n, this.pattern = createPattern(this.config.pattern, this.config.invert);
  }
  /**
   * Tokenizes text by splitting it using the given pattern.
   * @param {string} text The text to tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens.
   */
  pre_tokenize_text(n, o) {
    return this.pattern === null ? [] : this.config.invert ? n.match(this.pattern) || [] : regexSplit(n, this.pattern);
  }
}
class PunctuationPreTokenizer extends PreTokenizer {
  /**
   * @param {Object} config The configuration options for the pre-tokenizer.
   * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
   */
  constructor(n) {
    super(), this.config = n, this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, "gu");
  }
  /**
   * Tokenizes text by splitting it using the given pattern.
   * @param {string} text The text to tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens.
   */
  pre_tokenize_text(n, o) {
    return n.match(this.pattern) || [];
  }
}
class DigitsPreTokenizer extends PreTokenizer {
  /**
   * @param {Object} config The configuration options for the pre-tokenizer.
   * @param {boolean} config.individual_digits Whether to split on individual digits.
   */
  constructor(n) {
    super(), this.config = n;
    const o = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`;
    this.pattern = new RegExp(o, "gu");
  }
  /**
   * Tokenizes text by splitting it using the given pattern.
   * @param {string} text The text to tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens.
   */
  pre_tokenize_text(n, o) {
    return n.match(this.pattern) || [];
  }
}
class PostProcessor extends Callable {
  /**
   * @param {Object} config The configuration for the post-processor.
   */
  constructor(n) {
    super(), this.config = n;
  }
  /**
   * Factory method to create a PostProcessor object from a configuration object.
   *
   * @param {Object} config Configuration object representing a PostProcessor.
   * @returns {PostProcessor} A PostProcessor object created from the given configuration.
   * @throws {Error} If an unknown PostProcessor type is encountered.
   */
  static fromConfig(n) {
    if (n === null) return null;
    switch (n.type) {
      case "TemplateProcessing":
        return new TemplateProcessing(n);
      case "ByteLevel":
        return new ByteLevelPostProcessor(n);
      case "RobertaProcessing":
        return new RobertaProcessing(n);
      case "BertProcessing":
        return new BertProcessing(n);
      case "Sequence":
        return new PostProcessorSequence(n);
      default:
        throw new Error(`Unknown PostProcessor type: ${n.type}`);
    }
  }
  /**
   * Method to be implemented in subclass to apply post-processing on the given tokens.
   *
   * @param {Array} tokens The input tokens to be post-processed.
   * @param {...*} args Additional arguments required by the post-processing logic.
   * @returns {PostProcessedOutput} The post-processed tokens.
   * @throws {Error} If the method is not implemented in subclass.
   */
  post_process(n, ...o) {
    throw Error("post_process should be implemented in subclass.");
  }
  /**
   * Alias for {@link PostProcessor#post_process}.
   * @param {Array} tokens The text or array of texts to post-process.
   * @param {...*} args Additional arguments required by the post-processing logic.
   * @returns {PostProcessedOutput} The post-processed tokens.
   */
  _call(n, ...o) {
    return this.post_process(n, ...o);
  }
}
class BertProcessing extends PostProcessor {
  /**
   * @param {Object} config The configuration for the post-processor.
   * @param {string[]} config.cls The special tokens to add to the beginning of the input.
   * @param {string[]} config.sep The special tokens to add to the end of the input.
   */
  constructor(n) {
    super(n), this.cls = n.cls[0], this.sep = n.sep[0];
  }
  /**
   * Adds the special tokens to the beginning and end of the input.
   * @param {string[]} tokens The input tokens.
   * @param {string[]} [tokens_pair=null] An optional second set of input tokens.
   * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.
   */
  post_process(n, o = null, {
    add_special_tokens: u = !0
  } = {}) {
    u && (n = mergeArrays([this.cls], n, [this.sep]));
    let l = new Array(n.length).fill(0);
    if (o !== null) {
      const h = u && this instanceof RobertaProcessing ? [this.sep] : [], a = u ? [this.sep] : [];
      n = mergeArrays(n, h, o, a), l = mergeArrays(l, new Array(o.length + h.length + a.length).fill(1));
    }
    return { tokens: n, token_type_ids: l };
  }
}
class RobertaProcessing extends BertProcessing {
}
class TemplateProcessing extends PostProcessor {
  /**
   * Creates a new instance of `TemplateProcessing`.
   * @param {Object} config The configuration options for the post processor.
   * @param {Array} config.single The template for a single sequence of tokens.
   * @param {Array} config.pair The template for a pair of sequences of tokens.
   */
  constructor(n) {
    super(n), this.single = n.single, this.pair = n.pair;
  }
  /**
   * Replaces special tokens in the template with actual tokens.
   * @param {string[]} tokens The list of tokens for the first sequence.
   * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
   * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.
   */
  post_process(n, o = null, {
    add_special_tokens: u = !0
  } = {}) {
    const l = o === null ? this.single : this.pair;
    let h = [], a = [];
    for (const f of l)
      "SpecialToken" in f ? u && (h.push(f.SpecialToken.id), a.push(f.SpecialToken.type_id)) : "Sequence" in f && (f.Sequence.id === "A" ? (h = mergeArrays(h, n), a = mergeArrays(a, new Array(n.length).fill(f.Sequence.type_id))) : f.Sequence.id === "B" && (h = mergeArrays(h, o), a = mergeArrays(a, new Array(o.length).fill(f.Sequence.type_id))));
    return { tokens: h, token_type_ids: a };
  }
}
class ByteLevelPostProcessor extends PostProcessor {
  /**
   * Post process the given tokens.
   * @param {string[]} tokens The list of tokens for the first sequence.
   * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
   * @returns {PostProcessedOutput} An object containing the post-processed tokens.
   */
  post_process(n, o = null) {
    return o && (n = mergeArrays(n, o)), { tokens: n };
  }
}
class PostProcessorSequence extends PostProcessor {
  /**
   * Creates a new instance of PostProcessorSequence.
   * @param {Object} config The configuration object.
   * @param {Object[]} config.processors The list of post-processors to apply.
   */
  constructor(n) {
    super(n), this.processors = n.processors.map((o) => PostProcessor.fromConfig(o));
  }
  /**
   * Post process the given tokens.
   * @param {string[]} tokens The list of tokens for the first sequence.
   * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
   * @returns {PostProcessedOutput} An object containing the post-processed tokens.
   */
  post_process(n, o = null, u = {}) {
    let l;
    for (const h of this.processors)
      if (h instanceof ByteLevelPostProcessor)
        n = h.post_process(n).tokens, o && (o = h.post_process(o).tokens);
      else {
        const a = h.post_process(n, o, u);
        n = a.tokens, l = a.token_type_ids;
      }
    return { tokens: n, token_type_ids: l };
  }
}
class Decoder extends Callable {
  /**
  * Creates an instance of `Decoder`.
  *
  * @param {Object} config The configuration object.
  */
  constructor(n) {
    super(), this.config = n, this.added_tokens = [], this.end_of_word_suffix = null, this.trim_offsets = n.trim_offsets;
  }
  /**
  * Creates a decoder instance based on the provided configuration.
  *
  * @param {Object} config The configuration object.
  * @returns {Decoder} A decoder instance.
  * @throws {Error} If an unknown decoder type is provided.
  */
  static fromConfig(n) {
    if (n === null) return null;
    switch (n.type) {
      case "WordPiece":
        return new WordPieceDecoder(n);
      case "Metaspace":
        return new MetaspaceDecoder(n);
      case "ByteLevel":
        return new ByteLevelDecoder(n);
      case "Replace":
        return new ReplaceDecoder(n);
      case "ByteFallback":
        return new ByteFallback(n);
      case "Fuse":
        return new FuseDecoder(n);
      case "Strip":
        return new StripDecoder(n);
      case "Sequence":
        return new DecoderSequence(n);
      case "CTC":
        return new CTCDecoder(n);
      case "BPEDecoder":
        return new BPEDecoder(n);
      default:
        throw new Error(`Unknown Decoder type: ${n.type}`);
    }
  }
  /**
  * Calls the `decode` method.
  *
  * @param {string[]} tokens The list of tokens.
  * @returns {string} The decoded string.
  */
  _call(n) {
    return this.decode(n);
  }
  /**
  * Decodes a list of tokens.
  * @param {string[]} tokens The list of tokens.
  * @returns {string} The decoded string.
  */
  decode(n) {
    return this.decode_chain(n).join("");
  }
  /**
   * Apply the decoder to a list of tokens.
   * 
   * @param {string[]} tokens The list of tokens.
   * @returns {string[]} The decoded list of tokens.
   * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
   */
  decode_chain(n) {
    throw Error("`decode_chain` should be implemented in subclass.");
  }
}
class ReplaceDecoder extends Decoder {
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    const o = createPattern(this.config.pattern);
    return o === null ? n : n.map((u) => u.replaceAll(o, this.config.content));
  }
}
class ByteFallback extends Decoder {
  constructor(n) {
    super(n), this.text_decoder = new TextDecoder();
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    const o = [];
    let u = [];
    for (const l of n) {
      let h = null;
      if (l.length === 6 && l.startsWith("<0x") && l.endsWith(">")) {
        const a = parseInt(l.slice(3, 5), 16);
        isNaN(a) || (h = a);
      }
      if (h !== null)
        u.push(h);
      else {
        if (u.length > 0) {
          const a = this.text_decoder.decode(Uint8Array.from(u));
          o.push(a), u = [];
        }
        o.push(l);
      }
    }
    if (u.length > 0) {
      const l = this.text_decoder.decode(Uint8Array.from(u));
      o.push(l), u = [];
    }
    return o;
  }
}
class FuseDecoder extends Decoder {
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    return [n.join("")];
  }
}
class StripDecoder extends Decoder {
  constructor(n) {
    super(n), this.content = this.config.content, this.start = this.config.start, this.stop = this.config.stop;
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    return n.map((o) => {
      let u = 0;
      for (let h = 0; h < this.start && o[h] === this.content; ++h) {
        u = h + 1;
        continue;
      }
      let l = o.length;
      for (let h = 0; h < this.stop; ++h) {
        const a = o.length - h - 1;
        if (o[a] === this.content) {
          l = a;
          continue;
        } else
          break;
      }
      return o.slice(u, l);
    });
  }
}
class WordPieceDecoder extends Decoder {
  /**
   * Creates a new instance of WordPieceDecoder.
   * @param {Object} config The configuration object.
   * @param {string} config.prefix The prefix used for WordPiece encoding.
   * @param {boolean} config.cleanup Whether to cleanup the decoded string.
   */
  constructor(n) {
    super(n), this.cleanup = n.cleanup;
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    return n.map((o, u) => (u !== 0 && (o.startsWith(this.config.prefix) ? o = o.replace(this.config.prefix, "") : o = " " + o), this.cleanup && (o = clean_up_tokenization(o)), o));
  }
}
class ByteLevelDecoder extends Decoder {
  /**
   * Create a `ByteLevelDecoder` object.
   * @param {Object} config Configuration object.
   */
  constructor(n) {
    super(n), this.byte_decoder = UNICODE_TO_BYTES, this.text_decoder = new TextDecoder("utf-8", {
      fatal: !1,
      ignoreBOM: !0
    }), this.end_of_word_suffix = null;
  }
  /**
   * Convert an array of tokens to string by decoding each byte.
   * @param {string[]} tokens Array of tokens to be decoded.
   * @returns {string} The decoded string.
   */
  convert_tokens_to_string(n) {
    const o = n.join(""), u = new Uint8Array([...o].map((h) => this.byte_decoder[h]));
    return this.text_decoder.decode(u);
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    const o = [];
    let u = [];
    for (const l of n)
      this.added_tokens.find((h) => h.content === l) !== void 0 ? (u.length > 0 && (o.push(this.convert_tokens_to_string(u)), u = []), o.push(l)) : u.push(l);
    return u.length > 0 && o.push(this.convert_tokens_to_string(u)), o;
  }
}
class CTCDecoder extends Decoder {
  constructor(n) {
    super(n), this.pad_token = this.config.pad_token, this.word_delimiter_token = this.config.word_delimiter_token, this.cleanup = this.config.cleanup;
  }
  /**
   * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
   * @param {string[]} tokens Array of tokens to be decoded.
   * @returns {string} The decoded string.
   */
  convert_tokens_to_string(n) {
    if (n.length === 0) return "";
    const o = [n[0]];
    for (let h = 1; h < n.length; ++h)
      n[h] !== o.at(-1) && o.push(n[h]);
    let l = o.filter((h) => h !== this.pad_token).join("");
    return this.cleanup && (l = clean_up_tokenization(l).replaceAll(this.word_delimiter_token, " ").trim()), l;
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    return [this.convert_tokens_to_string(n)];
  }
}
class DecoderSequence extends Decoder {
  /**
   * Creates a new instance of DecoderSequence.
   * @param {Object} config The configuration object.
   * @param {Object[]} config.decoders The list of decoders to apply.
   */
  constructor(n) {
    super(n), this.decoders = n.decoders.map((o) => Decoder.fromConfig(o));
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    return this.decoders.reduce((o, u) => u.decode_chain(o), n);
  }
}
class BPEDecoder extends Decoder {
  constructor(n) {
    super(n), this.suffix = this.config.suffix;
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    return n.map((o, u) => o.replaceAll(this.suffix, u === n.length - 1 ? "" : " "));
  }
}
class VitsDecoder extends Decoder {
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    let o = "";
    for (let u = 1; u < n.length; u += 2)
      o += n[u];
    return [o];
  }
}
class MetaspacePreTokenizer extends PreTokenizer {
  /**
   * @param {Object} config The configuration object for the MetaspacePreTokenizer.
   * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.
   * @param {string} config.replacement The character to replace spaces with.
   * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.
   * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.
   */
  constructor(n) {
    super(), this.addPrefixSpace = n.add_prefix_space, this.replacement = n.replacement, this.strRep = n.str_rep || this.replacement, this.prepend_scheme = n.prepend_scheme ?? "always";
  }
  /**
   * This method takes a string, replaces spaces with the replacement character,
   * adds a prefix space if requested, and returns a new list of tokens.
   * @param {string} text The text to pre-tokenize.
   * @param {Object} [options] The options for the pre-tokenization.
   * @param {number} [options.section_index] The index of the section to pre-tokenize.
   * @returns {string[]} A new list of pre-tokenized tokens.
   */
  pre_tokenize_text(n, {
    section_index: o = void 0
  } = {}) {
    let u = n.replaceAll(" ", this.strRep);
    return (
      // We add a prefix space if:
      //  (1) The addPrefixSpace option is enabled and the normalized
      //      token does not already start with the replacement character.
      this.addPrefixSpace && !u.startsWith(this.replacement) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && o === 0) && (u = this.strRep + u), [u]
    );
  }
}
class MetaspaceDecoder extends Decoder {
  /**
   * Constructs a new MetaspaceDecoder object.
   * @param {Object} config The configuration object for the MetaspaceDecoder.
   * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.
   * @param {string} config.replacement The string to replace spaces with.
   */
  constructor(n) {
    super(n), this.addPrefixSpace = n.add_prefix_space, this.replacement = n.replacement;
  }
  /** @type {Decoder['decode_chain']} */
  decode_chain(n) {
    const o = [];
    for (let u = 0; u < n.length; ++u) {
      let l = n[u].replaceAll(this.replacement, " ");
      this.addPrefixSpace && u == 0 && l.startsWith(" ") && (l = l.substring(1)), o.push(l);
    }
    return o;
  }
}
class Precompiled extends Normalizer {
  /**
   * Create a new instance of Precompiled normalizer.
   * @param {Object} config The configuration object.
   * @param {any} config.precompiled_charsmap Precompiled chars mapping.
   */
  constructor(n) {
    super(n), this.charsmap = n.precompiled_charsmap;
  }
  /**
   * Normalizes the given text by applying the precompiled charsmap.
   * @param {string} text The text to normalize.
   * @returns {string} The normalized text.
   */
  normalize(n) {
    return n = n.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ""), n = n.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, " "), n.includes("～") ? n = n.split("～").map((u) => u.normalize("NFKC")).join("～") : n = n.normalize("NFKC"), n;
  }
}
class PreTokenizerSequence extends PreTokenizer {
  /**
   * Creates an instance of PreTokenizerSequence.
   * @param {Object} config The configuration object for the pre-tokenizer sequence.
   * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.
   */
  constructor(n) {
    super(), this.tokenizers = n.pretokenizers.map((o) => PreTokenizer.fromConfig(o));
  }
  /**
   * Applies each pre-tokenizer in the sequence to the input text in turn.
   * @param {string} text The text to pre-tokenize.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} The pre-tokenized text.
   */
  pre_tokenize_text(n, o) {
    return this.tokenizers.reduce((u, l) => l.pre_tokenize(u, o), [n]);
  }
}
class WhitespacePreTokenizer extends PreTokenizer {
  /**
   * Creates an instance of WhitespacePreTokenizer.
   * @param {Object} config The configuration object for the pre-tokenizer.
   */
  constructor(n) {
    super();
  }
  /**
   * Pre-tokenizes the input text by splitting it on word boundaries.
   * @param {string} text The text to be pre-tokenized.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
   */
  pre_tokenize_text(n, o) {
    return n.match(/\w+|[^\w\s]+/g) || [];
  }
}
class WhitespaceSplit extends PreTokenizer {
  /**
   * Creates an instance of WhitespaceSplit.
   * @param {Object} config The configuration object for the pre-tokenizer.
   */
  constructor(n) {
    super();
  }
  /**
   * Pre-tokenizes the input text by splitting it on whitespace characters.
   * @param {string} text The text to be pre-tokenized.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
   */
  pre_tokenize_text(n, o) {
    return whitespace_split(n);
  }
}
class ReplacePreTokenizer extends PreTokenizer {
  /**
   * @param {Object} config The configuration options for the pre-tokenizer.
   * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
   * @param {string} config.content What to replace the pattern with.
   */
  constructor(n) {
    super(), this.config = n, this.pattern = createPattern(this.config.pattern), this.content = this.config.content;
  }
  /**
   * Pre-tokenizes the input text by replacing certain characters.
   * @param {string} text The text to be pre-tokenized.
   * @param {Object} [options] Additional options for the pre-tokenization logic.
   * @returns {string[]} An array of tokens produced by replacing certain characters.
   */
  pre_tokenize_text(n, o) {
    return this.pattern === null ? [n] : [n.replaceAll(this.pattern, this.config.content)];
  }
}
const SPECIAL_TOKEN_ATTRIBUTES = [
  "bos_token",
  "eos_token",
  "unk_token",
  "sep_token",
  "pad_token",
  "cls_token",
  "mask_token"
  // additional_special_tokens (TODO)
];
function padHelper(d, n, o, u) {
  for (const l of Object.keys(d)) {
    const h = n - d[l].length, a = o(l), f = new Array(h).fill(a);
    d[l] = u === "right" ? mergeArrays(d[l], f) : mergeArrays(f, d[l]);
  }
}
function truncateHelper(d, n) {
  for (const o of Object.keys(d))
    d[o].length = n;
}
class PreTrainedTokenizer extends Callable {
  return_token_type_ids = !1;
  _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + '
' + message['content'] + '<|im_end|>' + '
'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
' }}{% endif %}`;
  /**
   * Create a new PreTrainedTokenizer instance.
   * @param {Object} tokenizerJSON The JSON of the tokenizer.
   * @param {Object} tokenizerConfig The config of the tokenizer.
   */
  constructor(n, o) {
    super(), this._tokenizer_config = o, this.normalizer = Normalizer.fromConfig(n.normalizer), this.pre_tokenizer = PreTokenizer.fromConfig(n.pre_tokenizer), this.model = TokenizerModel.fromConfig(n.model, o), this.post_processor = PostProcessor.fromConfig(n.post_processor), this.decoder = Decoder.fromConfig(n.decoder), this.special_tokens = [], this.all_special_ids = [], this.added_tokens = [];
    for (const u of n.added_tokens) {
      const l = new AddedToken(u);
      this.added_tokens.push(l), this.model.tokens_to_ids.set(l.content, l.id), this.model.vocab[l.id] = l.content, l.special && (this.special_tokens.push(l.content), this.all_special_ids.push(l.id));
    }
    if (this.additional_special_tokens = o.additional_special_tokens ?? [], this.special_tokens.push(...this.additional_special_tokens), this.special_tokens = [...new Set(this.special_tokens)], this.decoder && (this.decoder.added_tokens = this.added_tokens, this.decoder.end_of_word_suffix = this.model.end_of_word_suffix), this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(
      this.added_tokens.map((u) => `${u.lstrip ? "\\s*" : ""}(${escapeRegExp(u.content)})${u.rstrip ? "\\s*" : ""}`).join("|")
    ) : null, this.mask_token = this.getToken("mask_token"), this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token), this.pad_token = this.getToken("pad_token", "eos_token"), this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token), this.sep_token = this.getToken("sep_token"), this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token), this.unk_token = this.getToken("unk_token"), this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token), this.model_max_length = o.model_max_length, this.remove_space = o.remove_space, this.clean_up_tokenization_spaces = o.clean_up_tokenization_spaces ?? !0, this.do_lowercase_and_remove_accent = o.do_lowercase_and_remove_accent ?? !1, this.padding_side = "right", this.legacy = !1, this.chat_template = o.chat_template ?? null, Array.isArray(this.chat_template)) {
      const u = /* @__PURE__ */ Object.create(null);
      for (const { name: l, template: h } of this.chat_template) {
        if (typeof l != "string" || typeof h != "string")
          throw new Error('Chat template must be a list of objects with "name" and "template" properties');
        u[l] = h;
      }
      this.chat_template = u;
    }
    this._compiled_template_cache = /* @__PURE__ */ new Map();
  }
  /**
   * Returns the value of the first matching key in the tokenizer config object.
   * @param {...string} keys One or more keys to search for in the tokenizer config object.
   * @returns {string|null} The value associated with the first matching key, or null if no match is found.
   * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
   */
  getToken(...n) {
    for (const o of n) {
      const u = this._tokenizer_config[o];
      if (u)
        if (typeof u == "object") {
          if (u.__type === "AddedToken")
            return u.content;
          throw Error(`Unknown token: ${u}`);
        } else
          return u;
    }
    return null;
  }
  /**
   * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. 
   * 
   * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
   * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
   * 
   * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
   * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
   */
  static async from_pretrained(n, {
    progress_callback: o = null,
    config: u = null,
    cache_dir: l = null,
    local_files_only: h = !1,
    revision: a = "main",
    legacy: f = null
  } = {}) {
    const g = await loadTokenizer(n, {
      progress_callback: o,
      cache_dir: l,
      local_files_only: h,
      revision: a,
      legacy: f
    });
    return new this(...g);
  }
  /**
   * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
   * 
   * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
   * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
   * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
   * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
   */
  /**
   * Encode/tokenize the given text(s).
   * @param {string|string[]} text The text to tokenize.
   * @param {Object} options An optional object containing the following properties:
   * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
   * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
   * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
   * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
   * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
   * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
   * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.
   * @returns {BatchEncoding} Object to be passed to the model.
   */
  _call(n, {
    text_pair: o = null,
    add_special_tokens: u = !0,
    padding: l = !1,
    truncation: h = null,
    max_length: a = null,
    return_tensor: f = !0,
    // Different to HF
    return_token_type_ids: g = null
  } = {}) {
    const c = Array.isArray(n);
    let s;
    if (c) {
      if (n.length === 0)
        throw Error("text array must be non-empty");
      if (o !== null) {
        if (Array.isArray(o)) {
          if (n.length !== o.length)
            throw Error("text and text_pair must have the same length");
        } else throw Error("text_pair must also be an array");
        s = n.map(
          (e, r) => this._encode_plus(e, o[r], { add_special_tokens: u, return_token_type_ids: g })
        );
      } else
        s = n.map((e) => this._encode_plus(e, null, { add_special_tokens: u, return_token_type_ids: g }));
    } else {
      if (n == null)
        throw Error("text may not be null or undefined");
      if (Array.isArray(o))
        throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");
      s = [this._encode_plus(n, o, { add_special_tokens: u, return_token_type_ids: g })];
    }
    if (a === null ? l === "max_length" ? a = this.model_max_length : a = max(s.map((e) => e.input_ids.length))[0] : h || console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."), a = Math.min(a, this.model_max_length), l || h)
      for (let e = 0; e < s.length; ++e)
        s[e].input_ids.length !== a && (s[e].input_ids.length > a ? h && truncateHelper(s[e], a) : l && padHelper(
          s[e],
          a,
          (r) => r === "input_ids" ? this.pad_token_id : 0,
          this.padding_side
        ));
    const t = {};
    if (f) {
      if (!(l && h) && s.some((r) => {
        for (const i of Object.keys(r))
          if (r[i].length !== s[0][i]?.length)
            return !0;
        return !1;
      }))
        throw Error(
          "Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length."
        );
      const e = [s.length, s[0].input_ids.length];
      for (const r of Object.keys(s[0]))
        t[r] = new Tensor(
          "int64",
          BigInt64Array.from(s.flatMap((i) => i[r]).map(BigInt)),
          e
        );
    } else {
      for (const e of Object.keys(s[0]))
        t[e] = s.map((r) => r[e]);
      if (!c)
        for (const e of Object.keys(t))
          t[e] = t[e][0];
    }
    return (
      /** @type {BatchEncoding} */
      t
    );
  }
  /**
   * Encodes a single text using the preprocessor pipeline of the tokenizer.
   *
   * @param {string|null} text The text to encode.
   * @returns {string[]|null} The encoded tokens.
   */
  _encode_text(n) {
    return n === null ? null : (this.added_tokens_regex ? n.split(this.added_tokens_regex).filter((l) => l) : [n]).map((l, h) => {
      if (this.added_tokens.find((f) => f.content === l) !== void 0)
        return l;
      {
        if (this.remove_space === !0 && (l = l.trim().split(/\s+/).join(" ")), this.do_lowercase_and_remove_accent && (l = lowercase_and_remove_accent(l)), this.normalizer !== null && (l = this.normalizer(l)), l.length === 0)
          return [];
        const f = this.pre_tokenizer !== null ? this.pre_tokenizer(l, {
          section_index: h
        }) : [l];
        return this.model(f);
      }
    }).flat();
  }
  /**
   * Encodes a single text or a pair of texts using the model's tokenizer.
   *
   * @param {string} text The text to encode.
   * @param {string|null} text_pair The optional second text to encode.
   * @param {Object} options An optional object containing the following properties:
   * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
   * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
   * @returns {EncodingSingle} An object containing the encoded text.
   * @private
   */
  _encode_plus(n, o = null, {
    add_special_tokens: u = !0,
    return_token_type_ids: l = null
  } = {}) {
    const h = this._encode_text(n), a = this._encode_text(o), f = this.post_processor ? this.post_processor(h, a, { add_special_tokens: u }) : { tokens: mergeArrays(h ?? [], a ?? []) }, g = this.model.convert_tokens_to_ids(f.tokens), c = {
      input_ids: g,
      attention_mask: new Array(g.length).fill(1)
    };
    return (l ?? this.return_token_type_ids) && f.token_type_ids && (c.token_type_ids = f.token_type_ids), c;
  }
  /**
   * Encodes a single text or a pair of texts using the model's tokenizer.
   *
   * @param {string} text The text to encode.
   * @param {string|null} text_pair The optional second text to encode.
   * @param {Object} options An optional object containing the following properties:
   * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
   * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
   * @returns {number[]} An array of token IDs representing the encoded text(s).
   */
  encode(n, o = null, {
    add_special_tokens: u = !0,
    return_token_type_ids: l = null
  } = {}) {
    const { input_ids: h } = this._encode_plus(n, o, {
      add_special_tokens: u,
      return_token_type_ids: l
    });
    return h;
  }
  /**
   * Decode a batch of tokenized sequences.
   * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
   * @param {Object} decode_args (Optional) Object with decoding arguments.
   * @returns {string[]} List of decoded sequences.
   */
  batch_decode(n, o = {}) {
    return n instanceof Tensor && (n = n.tolist()), n.map((u) => this.decode(u, o));
  }
  /**
   * Decodes a sequence of token IDs back to a string.
   *
   * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode.
   * @param {Object} [decode_args={}]
   * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
   * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
   *
   * @returns {string} The decoded string.
   * @throws {Error} If `token_ids` is not a non-empty array of integers.
   */
  decode(n, o = {}) {
    if (n instanceof Tensor && (n = prepareTensorForDecode(n)), !Array.isArray(n) || n.length === 0 || !isIntegralNumber(n[0]))
      throw Error("token_ids must be a non-empty array of integers.");
    return this.decode_single(n, o);
  }
  /**
   * Decode a single list of token ids to a string.
   * @param {number[]} token_ids List of token ids to decode
   * @param {Object} decode_args Optional arguments for decoding
   * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding
   * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.
   * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.
   * @returns {string} The decoded string
   */
  decode_single(n, {
    skip_special_tokens: o = !1,
    clean_up_tokenization_spaces: u = null
  }) {
    let l = this.model.convert_ids_to_tokens(n);
    o && (l = l.filter((a) => !this.special_tokens.includes(a)));
    let h = this.decoder ? this.decoder(l) : l.join(" ");
    return this.decoder && this.decoder.end_of_word_suffix && (h = h.replaceAll(this.decoder.end_of_word_suffix, " "), o && (h = h.trim())), (u ?? this.clean_up_tokenization_spaces) && (h = clean_up_tokenization(h)), h;
  }
  get default_chat_template() {
    return this._warned_about_chat_template || (console.warn(
      "No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."
    ), this._warned_about_chat_template = !0), this._default_chat_template;
  }
  /**
   * Converts a list of message objects with `"role"` and `"content"` keys to a list of token
   * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
   * determine the format and control tokens to use when converting. When chat_template is None, it will fall back
   * to the default_chat_template specified at the class level.
   * 
   * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.
   * 
   * **Example:** Applying a chat template to a conversation.
   * 
   * ```javascript
   * import { AutoTokenizer } from "@xenova/transformers";
   * 
   * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1");
   * 
   * const chat = [
   *   { "role": "user", "content": "Hello, how are you?" },
   *   { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
   *   { "role": "user", "content": "I'd like to show off how chat templating works!" },
   * ]
   * 
   * const text = tokenizer.apply_chat_template(chat, { tokenize: false });
   * // "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
   * 
   * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
   * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]
   * ```
   * 
   * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys.
   * @param {Object} options An optional object containing the following properties:
   * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If
   * this is not passed, the model's default chat template will be used instead.
   * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate
   * the start of an assistant message. This is useful when you want to generate a response from the model.
   * Note that this argument will be passed to the chat template, and so it must be supported in the
   * template for this argument to have any effect.
   * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.
   * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
   * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
   * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.
   * If not specified, the tokenizer's `max_length` attribute will be used as a default.
   * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
   * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.
   * @returns {string | Tensor | number[]| number[][]} The tokenized output.
   */
  apply_chat_template(n, {
    chat_template: o = null,
    add_generation_prompt: u = !1,
    tokenize: l = !0,
    padding: h = !1,
    truncation: a = !1,
    max_length: f = null,
    return_tensor: g = !0,
    tokenizer_kwargs: c = {},
    ...s
  } = {}) {
    if (this.chat_template && typeof this.chat_template == "object" || this.chat_template === null && this.default_chat_template && typeof this.default_chat_template == "object") {
      const i = this.chat_template ?? this.default_chat_template;
      if (o !== null && Object.hasOwn(i, o))
        o = i[o];
      else if (o === null && "default" in i)
        o = i.default;
      else if (o === null)
        throw Error(
          `This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(i).sort()}.`
        );
    } else
      o ??= this.chat_template ?? this.default_chat_template;
    if (typeof o != "string")
      throw Error(`chat_template must be a string, but got ${typeof o}`);
    let t = this._compiled_template_cache.get(o);
    t === void 0 && (t = new Template(o), this._compiled_template_cache.set(o, t));
    const e = /* @__PURE__ */ Object.create(null);
    for (const i of SPECIAL_TOKEN_ATTRIBUTES) {
      const p = this.getToken(i);
      p && (e[i] = p);
    }
    const r = t.render({
      messages: n,
      add_generation_prompt: u,
      ...e,
      ...s
    });
    return l ? this._call(r, {
      add_special_tokens: !1,
      padding: h,
      truncation: a,
      max_length: f,
      return_tensor: g,
      ...c
    }).input_ids : r;
  }
}
class BertTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class AlbertTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class MobileBertTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class SqueezeBertTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class DebertaTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class DebertaV2Tokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class HerbertTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class ConvBertTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class RoFormerTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class DistilBertTokenizer extends PreTrainedTokenizer {
}
class CamembertTokenizer extends PreTrainedTokenizer {
}
class XLMTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
  constructor(n, o) {
    super(n, o), console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.');
  }
}
class ElectraTokenizer extends PreTrainedTokenizer {
  return_token_type_ids = !0;
}
class T5Tokenizer extends PreTrainedTokenizer {
}
class GPT2Tokenizer extends PreTrainedTokenizer {
  _default_chat_template = '{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';
}
class BartTokenizer extends PreTrainedTokenizer {
}
class MBartTokenizer extends PreTrainedTokenizer {
  constructor(n, o) {
    super(n, o), this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/, this.language_codes = this.special_tokens.filter((u) => this.languageRegex.test(u)), this.lang_to_token = (u) => u;
  }
  /**
   * Helper function to build translation inputs for an `MBartTokenizer`.
   * @param {string|string[]} raw_inputs The text to tokenize.
   * @param {Object} tokenizer_options Options to be sent to the tokenizer
   * @param {Object} generate_kwargs Generation options.
   * @returns {Object} Object to be passed to the model.
   */
  _build_translation_inputs(n, o, u) {
    return _build_translation_inputs(this, n, o, u);
  }
}
class MBart50Tokenizer extends MBartTokenizer {
}
class RobertaTokenizer extends PreTrainedTokenizer {
}
class BloomTokenizer extends GPT2Tokenizer {
  // NOTE: `GPT2Tokenizer` to get the correct chat template
  constructor(n, o) {
    const u = ".,!?…。，、।۔،", l = n.pre_tokenizer?.pretokenizers[0]?.pattern;
    l && l.Regex === ` ?[^(\\s|[${u}])]+` && (l.Regex = ` ?[^\\s${u}]+`), super(n, o);
  }
}
const SPIECE_UNDERLINE = "▁";
class LlamaTokenizer extends PreTrainedTokenizer {
  _default_chat_template = `{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<<SYS>>
' + system_message + '
<</SYS>>

' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<<SYS>>
' + content.strip() + '
<</SYS>>

' }}{% elif message['role'] == 'assistant' %}{{ ' '  + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`;
  DEFAULT_SYSTEM_PROMPT = `You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`;
  constructor(n, o) {
    super(n, o), this.use_default_system_prompt = o.use_default_system_prompt ?? !1, this.legacy = o.legacy ?? !0, this.legacy || (this.normalizer = null, this.pre_tokenizer = new MetaspacePreTokenizer({
      replacement: SPIECE_UNDERLINE,
      add_prefix_space: !0,
      prepend_scheme: "first"
    }));
  }
  /**
   * Helper function to handle legacy encoding of SPM tokenizers.
   * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387
   * @param {string} text The text to encode.
   * @returns {string[]} The encoded tokens.
   */
  _encode_text(n) {
    if (n === null) return null;
    if (this.legacy || n.length === 0)
      return super._encode_text(n);
    let o = super._encode_text(SPIECE_UNDERLINE + n.replaceAll(SPIECE_UNDERLINE, " "));
    return o.length > 1 && o[0] === SPIECE_UNDERLINE && this.special_tokens.includes(o[1]) && (o = o.slice(1)), o;
  }
  get default_chat_template() {
    return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT", this.use_default_system_prompt ? "true" : "false").replaceAll("DEFAULT_SYSTEM_MESSAGE", this.DEFAULT_SYSTEM_PROMPT.replaceAll(`
`, "\\n").replaceAll("'", "\\'"));
  }
}
class CodeLlamaTokenizer extends LlamaTokenizer {
}
class XLMRobertaTokenizer extends PreTrainedTokenizer {
}
class MPNetTokenizer extends PreTrainedTokenizer {
}
class FalconTokenizer extends PreTrainedTokenizer {
}
class GPTNeoXTokenizer extends PreTrainedTokenizer {
}
class EsmTokenizer extends PreTrainedTokenizer {
}
class Qwen2Tokenizer extends PreTrainedTokenizer {
}
class GemmaTokenizer extends PreTrainedTokenizer {
  _default_chat_template = `{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '
' + message['content'] | trim + '<end_of_turn>
' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model
'}}{% endif %}`;
}
class Grok1Tokenizer extends PreTrainedTokenizer {
}
function _build_translation_inputs(d, n, o, u) {
  if (!("language_codes" in d) || !Array.isArray(d.language_codes))
    throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");
  if (!("languageRegex" in d) || !(d.languageRegex instanceof RegExp))
    throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");
  if (!("lang_to_token" in d) || typeof d.lang_to_token != "function")
    throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");
  const l = u.src_lang, h = u.tgt_lang;
  if (!d.language_codes.includes(h))
    throw new Error(`Target language code "${h}" is not valid. Must be one of: {${d.language_codes.join(", ")}}`);
  if (l !== void 0) {
    if (!d.language_codes.includes(l))
      throw new Error(`Source language code "${l}" is not valid. Must be one of: {${d.language_codes.join(", ")}}`);
    for (const a of d.post_processor.config.single)
      if ("SpecialToken" in a && d.languageRegex.test(a.SpecialToken.id)) {
        a.SpecialToken.id = d.lang_to_token(l);
        break;
      }
  }
  return u.forced_bos_token_id = d.model.convert_tokens_to_ids([d.lang_to_token(h)])[0], d._call(n, o);
}
class NllbTokenizer extends PreTrainedTokenizer {
  constructor(n, o) {
    super(n, o), this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/, this.language_codes = this.special_tokens.filter((u) => this.languageRegex.test(u)), this.lang_to_token = (u) => u;
  }
  /**
   * Helper function to build translation inputs for an `NllbTokenizer`.
   * @param {string|string[]} raw_inputs The text to tokenize.
   * @param {Object} tokenizer_options Options to be sent to the tokenizer
   * @param {Object} generate_kwargs Generation options.
   * @returns {Object} Object to be passed to the model.
   */
  _build_translation_inputs(n, o, u) {
    return _build_translation_inputs(this, n, o, u);
  }
}
class M2M100Tokenizer extends PreTrainedTokenizer {
  constructor(n, o) {
    super(n, o), this.languageRegex = /^__[a-z]{2,3}__$/, this.language_codes = this.special_tokens.filter((u) => this.languageRegex.test(u)).map((u) => u.slice(2, -2)), this.lang_to_token = (u) => `__${u}__`;
  }
  /**
   * Helper function to build translation inputs for an `M2M100Tokenizer`.
   * @param {string|string[]} raw_inputs The text to tokenize.
   * @param {Object} tokenizer_options Options to be sent to the tokenizer
   * @param {Object} generate_kwargs Generation options.
   * @returns {Object} Object to be passed to the model.
   */
  _build_translation_inputs(n, o, u) {
    return _build_translation_inputs(this, n, o, u);
  }
}
const WHISPER_LANGUAGES = [
  ["en", "english"],
  ["zh", "chinese"],
  ["de", "german"],
  ["es", "spanish"],
  ["ru", "russian"],
  ["ko", "korean"],
  ["fr", "french"],
  ["ja", "japanese"],
  ["pt", "portuguese"],
  ["tr", "turkish"],
  ["pl", "polish"],
  ["ca", "catalan"],
  ["nl", "dutch"],
  ["ar", "arabic"],
  ["sv", "swedish"],
  ["it", "italian"],
  ["id", "indonesian"],
  ["hi", "hindi"],
  ["fi", "finnish"],
  ["vi", "vietnamese"],
  ["he", "hebrew"],
  ["uk", "ukrainian"],
  ["el", "greek"],
  ["ms", "malay"],
  ["cs", "czech"],
  ["ro", "romanian"],
  ["da", "danish"],
  ["hu", "hungarian"],
  ["ta", "tamil"],
  ["no", "norwegian"],
  ["th", "thai"],
  ["ur", "urdu"],
  ["hr", "croatian"],
  ["bg", "bulgarian"],
  ["lt", "lithuanian"],
  ["la", "latin"],
  ["mi", "maori"],
  ["ml", "malayalam"],
  ["cy", "welsh"],
  ["sk", "slovak"],
  ["te", "telugu"],
  ["fa", "persian"],
  ["lv", "latvian"],
  ["bn", "bengali"],
  ["sr", "serbian"],
  ["az", "azerbaijani"],
  ["sl", "slovenian"],
  ["kn", "kannada"],
  ["et", "estonian"],
  ["mk", "macedonian"],
  ["br", "breton"],
  ["eu", "basque"],
  ["is", "icelandic"],
  ["hy", "armenian"],
  ["ne", "nepali"],
  ["mn", "mongolian"],
  ["bs", "bosnian"],
  ["kk", "kazakh"],
  ["sq", "albanian"],
  ["sw", "swahili"],
  ["gl", "galician"],
  ["mr", "marathi"],
  ["pa", "punjabi"],
  ["si", "sinhala"],
  ["km", "khmer"],
  ["sn", "shona"],
  ["yo", "yoruba"],
  ["so", "somali"],
  ["af", "afrikaans"],
  ["oc", "occitan"],
  ["ka", "georgian"],
  ["be", "belarusian"],
  ["tg", "tajik"],
  ["sd", "sindhi"],
  ["gu", "gujarati"],
  ["am", "amharic"],
  ["yi", "yiddish"],
  ["lo", "lao"],
  ["uz", "uzbek"],
  ["fo", "faroese"],
  ["ht", "haitian creole"],
  ["ps", "pashto"],
  ["tk", "turkmen"],
  ["nn", "nynorsk"],
  ["mt", "maltese"],
  ["sa", "sanskrit"],
  ["lb", "luxembourgish"],
  ["my", "myanmar"],
  ["bo", "tibetan"],
  ["tl", "tagalog"],
  ["mg", "malagasy"],
  ["as", "assamese"],
  ["tt", "tatar"],
  ["haw", "hawaiian"],
  ["ln", "lingala"],
  ["ha", "hausa"],
  ["ba", "bashkir"],
  ["jw", "javanese"],
  ["su", "sundanese"]
], WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES), WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([
  ...WHISPER_LANGUAGES.map(([d, n]) => [n, d]),
  ["burmese", "my"],
  ["valencian", "ca"],
  ["flemish", "nl"],
  ["haitian", "ht"],
  ["letzeburgesch", "lb"],
  ["pushto", "ps"],
  ["panjabi", "pa"],
  ["moldavian", "ro"],
  ["moldovan", "ro"],
  ["sinhalese", "si"],
  ["castilian", "es"]
]);
class WhisperTokenizer extends PreTrainedTokenizer {
  _default_chat_template = '{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';
  /**
   * Decodes automatic speech recognition (ASR) sequences.
   * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.
   * @param {Object} options The options to use for decoding.
   * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.
   */
  _decode_asr(n, {
    return_timestamps: o = !1,
    return_language: u = !1,
    time_precision: l = null,
    force_full_sequences: h = !0
  } = {}) {
    if (l === null)
      throw Error("Must specify time_precision");
    let a = null;
    const f = o === "word";
    function g() {
      return { language: a, timestamp: [null, null], text: "" };
    }
    const c = [];
    let s = g(), t = 0;
    const e = this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1;
    let r = [], i = [], p = !1, m = null;
    const _ = new Set(this.all_special_ids);
    for (const w of n) {
      const T = w.tokens, S = f ? w.token_timestamps : null;
      let E = null, O = e;
      if ("stride" in w) {
        const [L, j, B] = w.stride;
        if (t -= j, m = L - B, j && (O = j / l + e), B)
          for (let F = T.length - 1; F >= 0; --F) {
            const D = T[F];
            if (D >= e) {
              if (E !== null && (D - e) * l < m)
                break;
              E = D;
            }
          }
      }
      let v = [], A = [];
      for (let L = 0; L < T.length; ++L) {
        const j = T[L];
        if (_.has(j)) {
          const B = this.decode([j]), F = WHISPER_LANGUAGE_MAPPING.get(B.slice(2, -2));
          if (F !== void 0) {
            if (a !== null && F !== a && !o) {
              r.push(v);
              const D = this.findLongestCommonSequence(r)[0], I = this.decode(D);
              s.text = I, c.push(s), r = [], v = [], s = g();
            }
            a = s.language = F;
          }
        } else if (j >= e) {
          const B = (j - e) * l + t, F = round(B, 2);
          if (E !== null && j >= E)
            p = !0;
          else if (p || r.length > 0 && j < O)
            p = !1;
          else if (s.timestamp[0] === null)
            s.timestamp[0] = F;
          else if (F !== s.timestamp[0]) {
            s.timestamp[1] = F, r.push(v), f && i.push(A);
            const [D, I] = this.findLongestCommonSequence(
              r,
              i
            ), $ = this.decode(D);
            s.text = $, f && (s.words = this.collateWordTimestamps(
              D,
              I,
              a
            )), c.push(s), r = [], v = [], i = [], A = [], s = g();
          }
        } else if (v.push(j), f) {
          let B = round(S[L] + t, 2), F;
          L + 1 < S.length ? F = round(S[L + 1] + t, 2) : F = null, A.push([B, F]);
        }
      }
      if ("stride" in w) {
        const [L, j, B] = w.stride;
        t += L - B;
      }
      v.length > 0 ? (r.push(v), f && i.push(A)) : r.every((L) => L.length === 0) && (s = g(), r = [], v = [], i = [], A = []);
    }
    if (r.length > 0) {
      if (h && o)
        throw new Error(
          "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation."
        );
      const [w, T] = this.findLongestCommonSequence(r, i), S = this.decode(w);
      s.text = S, f && (s.words = this.collateWordTimestamps(
        w,
        T,
        a
      )), c.push(s);
    }
    let b = /* @__PURE__ */ Object.create(null);
    const y = c.map((w) => w.text).join("");
    if (o || u) {
      for (let w = 0; w < c.length; ++w) {
        const T = c[w];
        o || delete T.timestamp, u || delete T.language;
      }
      if (f) {
        const w = [];
        for (const T of c)
          for (const S of T.words)
            w.push(S);
        b = { chunks: w };
      } else
        b = { chunks: c };
    }
    return [y, b];
  }
  /**
   * Finds the longest common sequence among the provided sequences.
   * @param {number[][]} sequences An array of sequences of token ids to compare.
   * @returns {number[][]} The longest common sequence found.
   * @throws {Error} If there is a bug within the function.
   * @private
   */
  findLongestCommonSequence(n, o = null) {
    let u = n[0], l = u.length, h = [];
    const a = Array.isArray(o) && o.length > 0;
    let f = a ? [] : null, g = a ? o[0] : null;
    for (let c = 1; c < n.length; ++c) {
      const s = n[c];
      let t = 0, e = [l, l, 0, 0];
      const r = s.length;
      for (let w = 1; w < l + r; ++w) {
        const T = w / 1e4, S = Math.max(0, l - w), E = Math.min(l, l + r - w), O = u.slice(S, E), v = Math.max(0, w - l), A = Math.min(r, w), L = s.slice(v, A);
        if (O.length !== L.length)
          throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");
        const j = O.filter((F, D) => F === L[D]).length, B = j / w + T;
        j > 1 && B > t && (t = B, e = [S, E, v, A]);
      }
      const [i, p, m, _] = e, b = Math.floor((p + i) / 2), y = Math.floor((_ + m) / 2);
      h.push(...u.slice(0, b)), u = s.slice(y), l = u.length, a && (f.push(...g.slice(0, b)), g = o[c].slice(y));
    }
    return h.push(...u), a ? (f.push(...g), [h, f]) : [h, []];
  }
  /** @private */
  collateWordTimestamps(n, o, u) {
    const [l, h, a] = this.combineTokensIntoWords(n, u), f = [];
    for (let g = 0; g < l.length; ++g) {
      const c = a[g];
      f.push({
        text: l[g],
        timestamp: [
          o[c.at(0)][0],
          o[c.at(-1)][1]
        ]
      });
    }
    return f;
  }
  /**
   * Groups tokens by word. Returns a tuple containing a list of strings with the words,
   * and a list of `token_id` sequences with the tokens making up each word.
   * @param {number[]} tokens 
   * @param {string} [language] 
   * @param {string} prepend_punctionations 
   * @param {string} append_punctuations 
   * 
   * @private
   */
  combineTokensIntoWords(n, o, u = `"'“¡¿([{-`, l = `"'.。,，!！?？:：”)]}、`) {
    o = o ?? "english";
    let h, a, f;
    return ["chinese", "japanese", "thai", "lao", "myanmar"].includes(o) ? [h, a, f] = this.splitTokensOnUnicode(n) : [h, a, f] = this.splitTokensOnSpaces(n), this.mergePunctuations(h, a, f, u, l);
  }
  /** @type {PreTrainedTokenizer['decode']} */
  decode(n, o) {
    let u;
    return o && o.decode_with_timestamps ? (n instanceof Tensor && (n = prepareTensorForDecode(n)), u = this.decodeWithTimestamps(n, o)) : u = super.decode(n, o), u;
  }
  /**
   * @param {number[]} token_ids List of token IDs to decode.
   * @param {Object} decode_args Optional arguments for decoding
   * @private
   */
  decodeWithTimestamps(n, o) {
    const u = o?.time_precision ?? 0.02, l = Array.from(this.all_special_ids).at(-1) + 1;
    let h = [[]];
    for (const a of n)
      if (a >= l) {
        const f = round((a - l) * u, 2);
        h.push(`<|${f}|>`), h.push([]);
      } else
        h[h.length - 1].push(a);
    return h = h.map(
      (a) => typeof a == "string" ? a : super.decode(a, o)
    ), h.join("");
  }
  /**
   * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.
   * @param {number[]} tokens 
   * @returns {*}
   * @private
   */
  splitTokensOnUnicode(n) {
    const o = this.decode(n, {
      // @ts-ignore
      decode_with_timestamps: !0
    }), u = "�", l = [], h = [], a = [];
    let f = [], g = [], c = 0;
    for (let s = 0; s < n.length; ++s) {
      const t = n[s];
      f.push(t), g.push(s);
      const e = this.decode(f, {
        // @ts-ignore
        decode_with_timestamps: !0
      });
      (!e.includes(u) || o[c + e.indexOf(u)] === u) && (l.push(e), h.push(f), a.push(g), f = [], g = [], c += e.length);
    }
    return [l, h, a];
  }
  /**
   * Combine tokens into words by splitting at whitespace and punctuation tokens.
   * @param {number[]} tokens 
   * @private
   */
  splitTokensOnSpaces(n) {
    const [o, u, l] = this.splitTokensOnUnicode(n), h = [], a = [], f = [], g = new RegExp(`^[${PUNCTUATION_REGEX}]$`, "gu");
    for (let c = 0; c < o.length; ++c) {
      const s = o[c], t = u[c], e = l[c], r = t[0] >= this.model.tokens_to_ids.get("<|endoftext|>"), i = s.startsWith(" "), p = s.trim(), m = g.test(p);
      if (r || i || m || h.length === 0)
        h.push(s), a.push(t), f.push(e);
      else {
        const _ = h.length - 1;
        h[_] += s, a[_].push(...t), f[_].push(...e);
      }
    }
    return [h, a, f];
  }
  /**
   * Merges punctuation tokens with neighboring words.
   * @param {string[]} words 
   * @param {number[][]} tokens 
   * @param {number[][]} indices 
   * @param {string} prepended 
   * @param {string} appended 
   * @private
   */
  mergePunctuations(n, o, u, l, h) {
    const a = structuredClone(n), f = structuredClone(o), g = structuredClone(u);
    let c = a.length - 2, s = a.length - 1;
    for (; c >= 0; )
      a[c].startsWith(" ") && l.includes(a[c].trim()) ? (a[s] = a[c] + a[s], f[s] = mergeArrays(f[c], f[s]), g[s] = mergeArrays(g[c], g[s]), a[c] = "", f[c] = [], g[c] = []) : s = c, --c;
    for (c = 0, s = 1; s < a.length; )
      !a[c].endsWith(" ") && h.includes(a[s]) ? (a[c] += a[s], f[c] = mergeArrays(f[c], f[s]), g[c] = mergeArrays(g[c], g[s]), a[s] = "", f[s] = [], g[s] = []) : c = s, ++s;
    return [
      a.filter((t) => t),
      f.filter((t) => t.length > 0),
      g.filter((t) => t.length > 0)
    ];
  }
  /**
   * Helper function to build translation inputs for a `WhisperTokenizer`,
   * depending on the language, task, and whether to predict timestamp tokens.
   * 
   * Used to override the prefix tokens appended to the start of the label sequence.
   * 
   * **Example: Get ids for a language**
   * ```javascript
   * // instantiate the tokenizer and set the prefix token to Spanish
   * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny');
   * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' });
   * // [(1, 50262), (2, 50363)]
   * ```
   * 
   * @param {Object} options Options to generate the decoder prompt.
   * @param {string} [options.language] The language of the transcription text.
   * The corresponding language id token is appended to the start of the sequence for multilingual
   * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended
   * to the start of sequence.
   * @param {string} [options.task] Task identifier to append at the start of sequence (if any).
   * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and
   * "translate" for speech translation.
   * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence.
   * @returns {number[][]} The decoder prompt ids.
   */
  get_decoder_prompt_ids({
    language: n = null,
    task: o = null,
    no_timestamps: u = !0
  } = {}) {
    const l = [];
    if (n) {
      n = n.toLowerCase();
      let h = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(n);
      if (h === void 0)
        if (WHISPER_LANGUAGE_MAPPING.has(n))
          h = n;
        else {
          const g = n.length === 2 ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();
          throw new Error(`Language "${n}" is not supported. Must be one of: ${JSON.stringify(g)}`);
        }
      const a = this.model.tokens_to_ids.get(`<|${h}|>`);
      if (a === void 0)
        throw new Error(`Unable to find language "${h}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);
      l.push(a);
    } else
      l.push(null);
    if (o) {
      if (o = o.toLowerCase(), o !== "transcribe" && o !== "translate")
        throw new Error(`Task "${o}" is not supported. Must be one of: ["transcribe", "translate"]`);
      const h = this.model.tokens_to_ids.get(`<|${o}|>`);
      if (h === void 0)
        throw new Error(`Unable to find task "${o}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);
      l.push(h);
    } else
      l.push(null);
    if (u) {
      const h = this.model.tokens_to_ids.get("<|notimestamps|>");
      if (h === void 0)
        throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');
      l.push(h);
    }
    return l.map((h, a) => [a + 1, h]).filter((h) => h[1] !== null);
  }
}
class CodeGenTokenizer extends PreTrainedTokenizer {
}
class CLIPTokenizer extends PreTrainedTokenizer {
}
class SiglipTokenizer extends PreTrainedTokenizer {
}
class MarianTokenizer extends PreTrainedTokenizer {
  /**
   * Create a new MarianTokenizer instance.
   * @param {Object} tokenizerJSON The JSON of the tokenizer.
   * @param {Object} tokenizerConfig The config of the tokenizer.
   */
  constructor(n, o) {
    super(n, o), this.languageRegex = /^(>>\w+<<)\s*/g, this.supported_language_codes = this.model.vocab.filter(
      (u) => this.languageRegex.test(u)
    ), console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.');
  }
  /**
   * Encodes a single text. Overriding this method is necessary since the language codes
   * must be removed before encoding with sentencepiece model.
   * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
   *
   * @param {string|null} text The text to encode.
   * @returns {Array} The encoded tokens.
   */
  _encode_text(n) {
    if (n === null) return null;
    const [o, ...u] = n.trim().split(this.languageRegex);
    if (u.length === 0)
      return super._encode_text(o);
    if (u.length === 2) {
      const [l, h] = u;
      return this.supported_language_codes.includes(l) || console.warn(`Unsupported language code "${l}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`), mergeArrays([l], super._encode_text(h));
    }
  }
}
class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer {
}
class BlenderbotTokenizer extends PreTrainedTokenizer {
  _default_chat_template = "{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ '  ' }}{% endif %}{% endfor %}{{ eos_token }}";
}
class BlenderbotSmallTokenizer extends BlenderbotTokenizer {
}
class SpeechT5Tokenizer extends PreTrainedTokenizer {
}
class NougatTokenizer extends PreTrainedTokenizer {
}
class VitsTokenizer extends PreTrainedTokenizer {
  constructor(n, o) {
    super(n, o), this.decoder = new VitsDecoder({});
  }
}
class CohereTokenizer extends PreTrainedTokenizer {
}
class AutoTokenizer {
  static TOKENIZER_CLASS_MAPPING = {
    T5Tokenizer,
    DistilBertTokenizer,
    CamembertTokenizer,
    DebertaTokenizer,
    DebertaV2Tokenizer,
    BertTokenizer,
    HerbertTokenizer,
    ConvBertTokenizer,
    RoFormerTokenizer,
    XLMTokenizer,
    ElectraTokenizer,
    MobileBertTokenizer,
    SqueezeBertTokenizer,
    AlbertTokenizer,
    GPT2Tokenizer,
    BartTokenizer,
    MBartTokenizer,
    MBart50Tokenizer,
    RobertaTokenizer,
    WhisperTokenizer,
    CodeGenTokenizer,
    CLIPTokenizer,
    SiglipTokenizer,
    MarianTokenizer,
    BloomTokenizer,
    NllbTokenizer,
    M2M100Tokenizer,
    LlamaTokenizer,
    CodeLlamaTokenizer,
    XLMRobertaTokenizer,
    MPNetTokenizer,
    FalconTokenizer,
    GPTNeoXTokenizer,
    EsmTokenizer,
    Wav2Vec2CTCTokenizer,
    BlenderbotTokenizer,
    BlenderbotSmallTokenizer,
    SpeechT5Tokenizer,
    NougatTokenizer,
    VitsTokenizer,
    Qwen2Tokenizer,
    GemmaTokenizer,
    Grok1Tokenizer,
    CohereTokenizer,
    // Base case:
    PreTrainedTokenizer
  };
  /**
   * Instantiate one of the tokenizer classes of the library from a pretrained model.
   * 
   * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object
   * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
   * 
   * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
   * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.
   *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
   *   user or organization name, like `dbmdz/bert-base-german-cased`.
   * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.
   * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
   * 
   * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.
   */
  static async from_pretrained(n, {
    quantized: o = !0,
    progress_callback: u = null,
    config: l = null,
    cache_dir: h = null,
    local_files_only: a = !1,
    revision: f = "main",
    legacy: g = null
  } = {}) {
    const [c, s] = await loadTokenizer(n, {
      progress_callback: u,
      cache_dir: h,
      local_files_only: a,
      revision: f,
      legacy: g
    }), t = s.tokenizer_class?.replace(/Fast$/, "") ?? "PreTrainedTokenizer";
    let e = this.TOKENIZER_CLASS_MAPPING[t];
    return e || (console.warn(`Unknown tokenizer class "${t}", attempting to construct from base class.`), e = PreTrainedTokenizer), new e(c, s);
  }
}
async function loadConfig(d, n) {
  return await getModelJSON(d, "config.json", !0, n);
}
class PretrainedConfig {
  // NOTE: Typo in original
  /**
   * Create a new PreTrainedTokenizer instance.
   * @param {Object} configJSON The JSON of the config.
   */
  constructor(n) {
    this.model_type = null, this.is_encoder_decoder = !1, Object.assign(this, n);
  }
  /**
   * Loads a pre-trained config from the given `pretrained_model_name_or_path`. 
   * 
   * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
   * @param {PretrainedOptions} options Additional options for loading the config.
   * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
   * 
   * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
   */
  static async from_pretrained(n, {
    progress_callback: o = null,
    config: u = null,
    cache_dir: l = null,
    local_files_only: h = !1,
    revision: a = "main"
  } = {}) {
    let f = u ?? await loadConfig(n, {
      progress_callback: o,
      cache_dir: l,
      local_files_only: h,
      revision: a
    });
    return new this(f);
  }
}
class AutoConfig {
  /** @type {PretrainedConfig.from_pretrained} */
  static async from_pretrained(...n) {
    return PretrainedConfig.from_pretrained(...n);
  }
}
class LogitsProcessorList extends Callable {
  /**
   * Constructs a new instance of `LogitsProcessorList`.
   */
  constructor() {
    super(), this.processors = [];
  }
  /**
   * Adds a new logits processor to the list.
   *
   * @param {LogitsProcessor} item The logits processor function to add.
   */
  push(n) {
    this.processors.push(n);
  }
  /**
   * Adds multiple logits processors to the list.
   *
   * @param {LogitsProcessor[]} items The logits processor functions to add.
   */
  extend(n) {
    this.processors.push(...n);
  }
  /**
   * Applies all logits processors in the list to a batch of logits, modifying them in-place.
   *
   * @param {number[]} input_ids The input IDs for the language model.
   * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
   *                                                input sequence in the batch.
   */
  _call(n, o) {
    for (let u of o)
      this.processors.forEach(
        (l) => l(n, u)
      );
  }
  [Symbol.iterator]() {
    return this.processors.values();
  }
}
class LogitsProcessor extends Callable {
  /**
   * Apply the processor to the input logits.
   *
   * @abstract
   * @param {Array} input_ids The input ids.
   * @param {Tensor} logits The logits to process.
   * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
   */
  _call(n, o) {
    throw Error("`_call` should be implemented in a subclass");
  }
}
class ForceTokensLogitsProcessor extends LogitsProcessor {
  /**
   * Constructs a new instance of `ForceTokensLogitsProcessor`.
   * 
   * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
   */
  constructor(n) {
    super(), this.force_token_map = Object.fromEntries(n ?? []);
  }
  /**
   * Apply the processor to the input logits.
   *
   * @param {Array} input_ids The input ids.
   * @param {Tensor} logits The logits to process.
   * @returns {Tensor} The processed logits.
   */
  _call(n, o) {
    let u = this.force_token_map[n.length];
    return exists(u) && (o.data.fill(-1 / 0), o.data[u] = 0), o;
  }
}
class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
  /**
   * Create a ForcedBOSTokenLogitsProcessor.
   * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
   */
  constructor(n) {
    super(), this.bos_token_id = n;
  }
  /**
   * Apply the BOS token forcing to the logits.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The logits with BOS token forcing.
   */
  _call(n, o) {
    return n.length === 1 && (o.data.fill(-1 / 0), o.data[this.bos_token_id] = 0), o;
  }
}
class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
  /**
   * Create a ForcedEOSTokenLogitsProcessor.
   * @param {number} max_length Max length of the sequence.
   * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
   */
  constructor(n, o) {
    super(), this.max_length = n, this.forced_eos_token_id = o;
  }
  /**
   * Apply the processor to input_ids and logits.
   * 
   * @param {number[]} input_ids The input ids.
   * @param {Tensor} logits The logits tensor.
   */
  _call(n, o) {
  }
}
class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
  /**
   * Create a SuppressTokensAtBeginLogitsProcessor.
   * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
   * @param {number} begin_index The number of tokens to generate before suppressing tokens.
   */
  constructor(n, o) {
    super(), this.begin_suppress_tokens = n, this.begin_index = o;
  }
  /**
   * Apply the BOS token forcing to the logits.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The logits with BOS token forcing.
   */
  _call(n, o) {
    if (n.length === this.begin_index)
      for (let u of this.begin_suppress_tokens)
        o.data[u] = -1 / 0;
    return o;
  }
}
class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
  /**
   * Constructs a new WhisperTimeStampLogitsProcessor.
   * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
   * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
   * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
   * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
   * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
   */
  constructor(n) {
    super(), this.eos_token_id = n.eos_token_id, this.no_timestamps_token_id = n.no_timestamps_token_id, this.timestamp_begin = this.no_timestamps_token_id + 1, this.begin_index = (n.forced_decoder_ids || []).length + 2, n.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id && (this.begin_index -= 1), this.max_initial_timestamp_index = n.max_initial_timestamp_index;
  }
  /**
   * Modify the logits to handle timestamp tokens.
   * @param {Array} input_ids The input sequence of tokens.
   * @param {Tensor} logits The logits output by the model.
   * @returns {Tensor} The modified logits.
   */
  _call(n, o) {
    const u = (
      /** @type {Float32Array} */
      o.data
    );
    if (u[this.no_timestamps_token_id] = -1 / 0, n.length === this.begin_index - 1)
      return u.fill(-1 / 0), u[this.timestamp_begin] = 0, o;
    const l = n.slice(this.begin_index), h = l.length >= 1 && l[l.length - 1] >= this.timestamp_begin, a = l.length < 2 || l[l.length - 2] >= this.timestamp_begin;
    if (h && (a ? u.subarray(this.timestamp_begin).fill(-1 / 0) : u.subarray(0, this.eos_token_id).fill(-1 / 0)), n.length === this.begin_index && this.max_initial_timestamp_index !== null) {
      const s = this.timestamp_begin + this.max_initial_timestamp_index;
      u.subarray(s + 1).fill(-1 / 0);
    }
    const f = log_softmax(u), g = Math.log(f.subarray(this.timestamp_begin).map(Math.exp).reduce((s, t) => s + t)), c = max(f.subarray(0, this.timestamp_begin))[0];
    return g > c && u.subarray(0, this.timestamp_begin).fill(-1 / 0), o;
  }
}
class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
  /**
   * Create a NoRepeatNGramLogitsProcessor.
   * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
   */
  constructor(n) {
    super(), this.no_repeat_ngram_size = n;
  }
  /**
   * Generate n-grams from a sequence of token ids.
   * @param {number[]} prevInputIds List of previous input ids
   * @returns {Map<string, number[]>} Map of generated n-grams
   */
  getNgrams(n) {
    const o = n.length, u = [];
    for (let h = 0; h < o + 1 - this.no_repeat_ngram_size; ++h) {
      const a = [];
      for (let f = 0; f < this.no_repeat_ngram_size; ++f)
        a.push(n[h + f]);
      u.push(a);
    }
    const l = /* @__PURE__ */ new Map();
    for (const h of u) {
      const a = h.slice(0, h.length - 1), f = JSON.stringify(a), g = l.get(f) ?? [];
      g.push(h[h.length - 1]), l.set(f, g);
    }
    return l;
  }
  /**
   * Generate n-grams from a sequence of token ids.
   * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
   * @param {number[]} prevInputIds List of previous input ids
   * @returns {number[]} Map of generated n-grams
   */
  getGeneratedNgrams(n, o) {
    const u = o.slice(o.length + 1 - this.no_repeat_ngram_size, o.length);
    return n.get(JSON.stringify(u)) ?? [];
  }
  /**
   * Calculate banned n-gram tokens
   * @param {number[]} prevInputIds List of previous input ids
   * @returns {number[]} Map of generated n-grams
   */
  calcBannedNgramTokens(n) {
    const o = [];
    if (n.length + 1 < this.no_repeat_ngram_size)
      return o;
    {
      const u = this.getNgrams(n);
      return this.getGeneratedNgrams(u, n);
    }
  }
  /**
   * Apply the no-repeat-ngram processor to the logits.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The logits with no-repeat-ngram processing.
   */
  _call(n, o) {
    const u = this.calcBannedNgramTokens(n);
    for (const l of u)
      o.data[l] = -1 / 0;
    return o;
  }
}
class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
  /**
   * Create a RepetitionPenaltyLogitsProcessor.
   * @param {number} penalty The penalty to apply for repeated tokens.
   */
  constructor(n) {
    super(), this.penalty = n;
  }
  /**
   * Apply the repetition penalty to the logits.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The logits with repetition penalty processing.
   */
  _call(n, o) {
    for (const u of n)
      o.data[u] < 0 ? o.data[u] *= this.penalty : o.data[u] /= this.penalty;
    return o;
  }
}
class MinLengthLogitsProcessor extends LogitsProcessor {
  /**
   * Create a MinLengthLogitsProcessor.
   * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
   * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
   */
  constructor(n, o) {
    super(), this.min_length = n, this.eos_token_id = Array.isArray(o) ? o : [o];
  }
  /**
   * Apply logit processor.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The processed logits.
   */
  _call(n, o) {
    if (n.length < this.min_length)
      for (const u of this.eos_token_id)
        o.data[u] = -1 / 0;
    return o;
  }
}
class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
  /**
   * Create a MinNewTokensLengthLogitsProcessor.
   * @param {number} prompt_length_to_skip The input tokens length.
   * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
   * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
   */
  constructor(n, o, u) {
    super(), this.prompt_length_to_skip = n, this.min_new_tokens = o, this.eos_token_id = Array.isArray(u) ? u : [u];
  }
  /**
   * Apply logit processor.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The processed logits.
   */
  _call(n, o) {
    if (n.length - this.prompt_length_to_skip < this.min_new_tokens)
      for (const l of this.eos_token_id)
        o.data[l] = -1 / 0;
    return o;
  }
}
class NoBadWordsLogitsProcessor extends LogitsProcessor {
  /**
   * Create a `NoBadWordsLogitsProcessor`.
   * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
   * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
   */
  constructor(n, o) {
    super(), this.bad_words_ids = n, this.eos_token_id = Array.isArray(o) ? o : [o];
  }
  /**
   * Apply logit processor.
   * @param {Array} input_ids The input IDs.
   * @param {Object} logits The logits.
   * @returns {Object} The processed logits.
   */
  _call(n, o) {
    for (const u of this.bad_words_ids) {
      let l = !0;
      for (let h = 1; h <= u.length - 1 && u.length < n.length; ++h)
        if (u.at(-h - 1) !== n.at(-h)) {
          l = !1;
          break;
        }
      l && (o.data[u.at(-1)] = -1 / 0);
    }
    return o;
  }
}
const GenerationConfig = (
  /** @type {any} */
  class {
    /**
     * Create a new GenerationConfig object.
     * @param {GenerationConfigType} kwargs 
     */
    constructor(d = {}) {
      this.max_length = d.max_length ?? 20, this.max_new_tokens = d.max_new_tokens ?? null, this.min_length = d.min_length ?? 0, this.min_new_tokens = d.min_new_tokens ?? null, this.early_stopping = d.early_stopping ?? !1, this.max_time = d.max_time ?? null, this.do_sample = d.do_sample ?? !1, this.num_beams = d.num_beams ?? 1, this.num_beam_groups = d.num_beam_groups ?? 1, this.penalty_alpha = d.penalty_alpha ?? null, this.use_cache = d.use_cache ?? !0, this.temperature = d.temperature ?? 1, this.top_k = d.top_k ?? 50, this.top_p = d.top_p ?? 1, this.typical_p = d.typical_p ?? 1, this.epsilon_cutoff = d.epsilon_cutoff ?? 0, this.eta_cutoff = d.eta_cutoff ?? 0, this.diversity_penalty = d.diversity_penalty ?? 0, this.repetition_penalty = d.repetition_penalty ?? 1, this.encoder_repetition_penalty = d.encoder_repetition_penalty ?? 1, this.length_penalty = d.length_penalty ?? 1, this.no_repeat_ngram_size = d.no_repeat_ngram_size ?? 0, this.bad_words_ids = d.bad_words_ids ?? null, this.force_words_ids = d.force_words_ids ?? null, this.renormalize_logits = d.renormalize_logits ?? !1, this.constraints = d.constraints ?? null, this.forced_bos_token_id = d.forced_bos_token_id ?? null, this.forced_eos_token_id = d.forced_eos_token_id ?? null, this.remove_invalid_values = d.remove_invalid_values ?? !1, this.exponential_decay_length_penalty = d.exponential_decay_length_penalty ?? null, this.suppress_tokens = d.suppress_tokens ?? null, this.begin_suppress_tokens = d.begin_suppress_tokens ?? null, this.forced_decoder_ids = d.forced_decoder_ids ?? null, this.num_return_sequences = d.num_return_sequences ?? 1, this.output_attentions = d.output_attentions ?? !1, this.output_hidden_states = d.output_hidden_states ?? !1, this.output_scores = d.output_scores ?? !1, this.return_dict_in_generate = d.return_dict_in_generate ?? !1, this.pad_token_id = d.pad_token_id ?? null, this.bos_token_id = d.bos_token_id ?? null, this.eos_token_id = d.eos_token_id ?? null, this.encoder_no_repeat_ngram_size = d.encoder_no_repeat_ngram_size ?? 0, this.decoder_start_token_id = d.decoder_start_token_id ?? null, this.generation_kwargs = d.generation_kwargs ?? {};
    }
  }
);
class Sampler extends Callable {
  /**
   * Creates a new Sampler object with the specified generation config.
   * @param {GenerationConfigType} generation_config The generation config.
   */
  constructor(n) {
    super(), this.generation_config = n;
  }
  /**
   * Executes the sampler, using the specified logits.
   * @param {Tensor} logits
   * @param {number} index
   * @returns {void}
   */
  _call(n, o = -1) {
    return this.sample(n, o);
  }
  /**
   * Abstract method for sampling the logits.
   * @param {Tensor} logits
   * @param {number} index
   * @throws {Error}
   */
  sample(n, o) {
    throw Error("sample should be implemented in subclasses.");
  }
  /**
   * Returns the specified logits as an array, with temperature applied.
   * @param {Tensor} logits
   * @param {number} index
   * @returns {Float32Array}
   */
  getLogits(n, o) {
    let u = n.dims.at(-1), l = (
      /** @type {Float32Array} */
      n.data
    );
    if (o === -1)
      l = l.slice(-u);
    else {
      let h = o * u;
      l = l.slice(h, h + u);
    }
    return this.generation_config.temperature > 0 && (l = l.map((h) => h / this.generation_config.temperature)), l;
  }
  /**
   * Selects an item randomly based on the specified probabilities.
   * @param {Array} probabilities An array of probabilities to use for selection.
   * @returns {number} The index of the selected item.
   */
  randomSelect(n) {
    let o = n.reduce((l, h) => l + h, 0), u = Math.random() * o;
    for (let l = 0; l < n.length; ++l)
      if (u -= n[l], u <= 0)
        return l;
    return 0;
  }
  /**
   * Returns a Sampler object based on the specified options.
   * @param {GenerationConfigType} generation_config An object containing options for the sampler.
   * @returns {Sampler} A Sampler object.
   */
  static getSampler(n) {
    if (n.do_sample)
      return new MultinomialSampler(n);
    if (n.num_beams > 1)
      return new BeamSearchSampler(n);
    if (n.num_return_sequences > 1)
      throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${n.num_return_sequences}.`);
    return new GreedySampler(n);
  }
}
class GreedySampler extends Sampler {
  /**
   * Sample the maximum probability of a given logits tensor.
   * @param {Tensor} logits
   * @param {number} [index=-1]
   * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).
   */
  sample(n, o = -1) {
    let u = this.getLogits(n, o);
    return [
      [max(u)[1], 0]
    ];
  }
}
class MultinomialSampler extends Sampler {
  /**
   * Sample from the logits.
   * @param {Tensor} logits
   * @param {number} index
   * @returns {Array}
   */
  sample(n, o = -1) {
    let u = n.dims.at(-1);
    this.generation_config.top_k > 0 && (u = Math.min(this.generation_config.top_k, u));
    const l = this.getLogits(n, o), h = getTopItems(l, u), a = softmax(h.map((f) => f[1]));
    return Array.from({ length: this.generation_config.num_beams }, () => {
      const f = this.randomSelect(a);
      return [
        h[f][0],
        // token id
        Math.log(a[f])
        // score
      ];
    });
  }
}
class BeamSearchSampler extends Sampler {
  /**
   * Sample from the logits.
   * @param {Tensor} logits
   * @param {number} index
   * @returns {Array}
   */
  sample(n, o = -1) {
    let u = n.dims.at(-1);
    this.generation_config.top_k > 0 && (u = Math.min(this.generation_config.top_k, u));
    const l = this.getLogits(n, o), h = getTopItems(l, u), a = softmax(h.map((f) => f[1]));
    return Array.from({ length: this.generation_config.num_beams }, (f, g) => [
      h[g][0],
      // token id
      Math.log(a[g])
      // score
    ]);
  }
}
const { InferenceSession, Tensor: ONNXTensor, env } = ONNX, MODEL_TYPES = {
  EncoderOnly: 0,
  EncoderDecoder: 1,
  Seq2Seq: 2,
  Vision2Seq: 3,
  DecoderOnly: 4,
  MaskGeneration: 5
}, MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map(), MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map(), MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map();
async function constructSession(d, n, o) {
  let u = `onnx/${n}${o.quantized ? "_quantized" : ""}.onnx`, l = await getModelFile(d, u, !0, o);
  try {
    return await InferenceSession.create(l, {
      executionProviders
    });
  } catch (h) {
    if (executionProviders.length === 1 && executionProviders[0] === "wasm")
      throw h;
    return console.warn(h), console.warn(
      "Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "
    ), await InferenceSession.create(l, {
      executionProviders: ["wasm"]
    });
  }
}
function validateInputs(d, n) {
  const o = /* @__PURE__ */ Object.create(null), u = [];
  for (const a of d.inputNames) {
    const f = n[a];
    if (!(f instanceof Tensor)) {
      u.push(a);
      continue;
    }
    o[a] = env.wasm.proxy ? f.clone() : f;
  }
  if (u.length > 0)
    throw new Error(
      `An error occurred during model execution: "Missing the following inputs: ${u.join(", ")}.`
    );
  const l = Object.keys(n).length, h = d.inputNames.length;
  if (l > h) {
    let a = Object.keys(n).filter((f) => !d.inputNames.includes(f));
    console.warn(`WARNING: Too many inputs were provided (${l} > ${h}). The following inputs will be ignored: "${a.join(", ")}".`);
  }
  return o;
}
async function sessionRun(d, n) {
  const o = validateInputs(d, n);
  try {
    let u = await d.run(o);
    return u = replaceTensors(u), u;
  } catch (u) {
    throw console.error(`An error occurred during model execution: "${u}".`), console.error("Inputs given to model:", o), u;
  }
}
function replaceTensors(d) {
  for (let n in d)
    d[n] instanceof ONNXTensor ? d[n] = new Tensor(d[n]) : typeof d[n] == "object" && replaceTensors(d[n]);
  return d;
}
function toI64Tensor(d) {
  if (d instanceof Tensor)
    return d;
  if (d.length === 0)
    throw Error("items must be non-empty");
  if (Array.isArray(d[0])) {
    if (d.some((n) => n.length !== d[0].length))
      throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");
    return new Tensor(
      "int64",
      BigInt64Array.from(d.flat().map((n) => BigInt(n))),
      [d.length, d[0].length]
    );
  } else
    return new Tensor(
      "int64",
      BigInt64Array.from(d.map((n) => BigInt(n))),
      [1, d.length]
    );
}
function prepareAttentionMask(d, n) {
  let o = d.config.pad_token_id ?? null, u = d.config.eos_token_id ?? null;
  isIntegralNumber(u) && (u = [u]);
  let l = n.indexOf(o) !== -1, h = u === null || !u.includes(o);
  if (l && h) {
    let a = BigInt64Array.from(
      // Note: != so that int matches bigint
      // @ts-ignore
      n.data.map((f) => f != o)
    );
    return new Tensor("int64", a, n.dims);
  } else
    return ones_like(n);
}
function preparePositionIds(d, n, o) {
  if (!d.inputNames.includes("position_ids")) return;
  const u = new BigInt64Array(n.attention_mask.data.length);
  for (let l = 0; l < n.attention_mask.dims[0]; ++l) {
    let h = l * n.attention_mask.dims[1], a = BigInt(0);
    for (let f = 0; f < n.attention_mask.dims[1]; ++f) {
      const g = h + f;
      n.attention_mask.data[g] === 0n ? u[g] = BigInt(1) : (u[g] = a, a += n.attention_mask.data[g]);
    }
  }
  n.position_ids = new Tensor("int64", u, n.attention_mask.dims), o && (n.position_ids = n.position_ids.slice(null, -1).unsqueeze_(-1));
}
function boolTensor(d) {
  return new Tensor("bool", [d], [1]);
}
async function seq2seqForward(d, n) {
  let { encoder_outputs: o, past_key_values: u } = n;
  o || (o = (await encoderForward(d, n)).last_hidden_state);
  let l = {
    input_ids: n.decoder_input_ids,
    encoder_hidden_states: o
  };
  const h = !!u;
  d.decoder_merged_session.inputNames.includes("use_cache_branch") && (l.use_cache_branch = boolTensor(h)), d.decoder_merged_session.inputNames.includes("encoder_attention_mask") && (l.encoder_attention_mask = n.attention_mask), preparePositionIds(d.decoder_merged_session, l, h), d.addPastKeyValues(l, u);
  const a = await sessionRun(d.decoder_merged_session, l);
  let f = a.logits;
  u = d.getPastKeyValues(a, u);
  const g = d.getAttentions(a);
  return new Seq2SeqLMOutput({ logits: f, past_key_values: u, encoder_outputs: o, ...g });
}
function seq2seqStartBeams(d, n, o, u) {
  let l = [], h = 0;
  const a = d.requires_attention_mask ?? !0;
  let f = o.decoder_input_ids ?? o.decoder_start_token_id ?? o.bos_token_id ?? o.eos_token_id;
  f instanceof Tensor ? f = f.tolist().flat() : Array.isArray(f) || (f = [f]);
  for (let g of n) {
    g.dims = [1, ...g.dims];
    let c = {
      inputs: g,
      encoder_outputs: null,
      prev_model_outputs: null,
      output_token_ids: f,
      done: !1,
      score: 0,
      id: h++
      // assign unique id to beams
    };
    a && (c.attention_mask = prepareAttentionMask(d, g)), l.push(c);
  }
  return l;
}
async function seq2seqRunBeam(d, n) {
  const o = d.main_input_name;
  let u = n.output_token_ids;
  n.prev_model_outputs && (u = u.slice(-1));
  let l = {
    [o]: n.inputs,
    decoder_input_ids: toI64Tensor(u),
    encoder_outputs: n.encoder_outputs,
    past_key_values: n.prev_model_outputs?.past_key_values
  };
  n.attention_mask && (l.attention_mask = n.attention_mask);
  let h = await d.forward(l);
  return n.prev_model_outputs = h, n.encoder_outputs = h.encoder_outputs, h;
}
function seq2seqUpdatebeam(d, n) {
  d.output_token_ids = [...d.output_token_ids, n];
}
async function encoderForward(d, n) {
  const o = /* @__PURE__ */ Object.create(null);
  for (const u of d.session.inputNames)
    o[u] = n[u];
  return d.session.inputNames.includes("token_type_ids") && !o.token_type_ids && (o.token_type_ids = new Tensor(
    "int64",
    new BigInt64Array(o.input_ids.data.length),
    o.input_ids.dims
  )), await sessionRun(d.session, o);
}
async function decoderForward(d, n) {
  let { input_ids: o, past_key_values: u, attention_mask: l } = n, h = {
    input_ids: o,
    attention_mask: l ?? prepareAttentionMask(d, o)
  };
  const a = !!u;
  d.session.inputNames.includes("use_cache_branch") && (h.use_cache_branch = boolTensor(a)), preparePositionIds(d.session, h, a), d.addPastKeyValues(h, u);
  let f = await sessionRun(d.session, h), g = f.logits;
  return u = d.getPastKeyValues(f, u), { logits: g, past_key_values: u };
}
function decoderStartBeams(d, n, o, u, l) {
  let h = [], a = 0;
  for (let f of n) {
    let g = f.tolist().map(Number);
    f.dims = [1, ...f.dims];
    let c;
    l ? (c = l[a], c.dims = [1, ...c.dims]) : c = prepareAttentionMask(d, f);
    let s = {
      input: f,
      model_input_ids: f,
      attention_mask: c,
      prev_model_outputs: null,
      output_token_ids: g,
      num_output_tokens: u,
      done: !1,
      score: 0,
      id: a++
      // assign unique id to beams
    };
    h.push(s);
  }
  return h;
}
async function decoderRunBeam(d, n) {
  let o = new BigInt64Array(n.output_token_ids.length).fill(1n), u = {
    input_ids: n.model_input_ids,
    attention_mask: new Tensor(
      "int64",
      o,
      [1, o.length]
    ),
    past_key_values: n.prev_model_outputs?.past_key_values
  }, l = await d.forward(u);
  return n.prev_model_outputs = l, l;
}
function decoderUpdatebeam(d, n) {
  d.output_token_ids = [...d.output_token_ids, n], d.model_input_ids = new Tensor("int64", [BigInt(n)], [1, 1]);
}
class PreTrainedModel extends Callable {
  main_input_name = "input_ids";
  /**
   * Creates a new instance of the `PreTrainedModel` class.
   * @param {Object} config The model configuration.
   * @param {any} session session for the model.
   */
  constructor(n, o) {
    super(), this.config = n, this.session = o;
    const u = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor), l = MODEL_TYPE_MAPPING.get(u);
    this.can_generate = !1, this._runBeam = null, this._getStartBeams = null, this._updateBeam = null, this._forward = null, l === MODEL_TYPES.DecoderOnly ? (this.can_generate = !0, this._runBeam = decoderRunBeam, this._getStartBeams = decoderStartBeams, this._updateBeam = decoderUpdatebeam, this._forward = decoderForward) : l === MODEL_TYPES.Seq2Seq || l === MODEL_TYPES.Vision2Seq ? (this.can_generate = !0, this._runBeam = seq2seqRunBeam, this._getStartBeams = seq2seqStartBeams, this._updateBeam = seq2seqUpdatebeam, this._forward = seq2seqForward) : l === MODEL_TYPES.EncoderDecoder ? this._forward = encoderForward : this._forward = encoderForward;
  }
  /**
  * Disposes of all the ONNX sessions that were created during inference.
  * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
  * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
  */
  async dispose() {
    const n = [];
    for (let o of Object.keys(this)) {
      const u = this[o];
      u instanceof InferenceSession && n.push(u.handler.dispose());
    }
    return await Promise.all(n);
  }
  /**
   * Instantiate one of the model classes of the library from a pretrained model.
   * 
   * The model class to instantiate is selected based on the `model_type` property of the config object
   * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
   * 
   * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
   * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
   *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
   *   user or organization name, like `dbmdz/bert-base-german-cased`.
   * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
   * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
   * 
   * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
   */
  static async from_pretrained(n, {
    quantized: o = !0,
    progress_callback: u = null,
    config: l = null,
    cache_dir: h = null,
    local_files_only: a = !1,
    revision: f = "main",
    model_file_name: g = null
  } = {}) {
    let c = {
      quantized: o,
      progress_callback: u,
      config: l,
      cache_dir: h,
      local_files_only: a,
      revision: f,
      model_file_name: g
    };
    const s = MODEL_CLASS_TO_NAME_MAPPING.get(this), t = MODEL_TYPE_MAPPING.get(s);
    let e;
    return t === MODEL_TYPES.DecoderOnly ? e = await Promise.all([
      AutoConfig.from_pretrained(n, c),
      constructSession(n, c.model_file_name ?? "decoder_model_merged", c),
      getModelJSON(n, "generation_config.json", !1, c)
    ]) : t === MODEL_TYPES.Seq2Seq || t === MODEL_TYPES.Vision2Seq ? e = await Promise.all([
      AutoConfig.from_pretrained(n, c),
      constructSession(n, "encoder_model", c),
      constructSession(n, "decoder_model_merged", c),
      getModelJSON(n, "generation_config.json", !1, c)
    ]) : t === MODEL_TYPES.MaskGeneration ? e = await Promise.all([
      AutoConfig.from_pretrained(n, c),
      constructSession(n, "vision_encoder", c),
      constructSession(n, "prompt_encoder_mask_decoder", c)
    ]) : t === MODEL_TYPES.EncoderDecoder ? e = await Promise.all([
      AutoConfig.from_pretrained(n, c),
      constructSession(n, "encoder_model", c),
      constructSession(n, "decoder_model_merged", c)
    ]) : (t !== MODEL_TYPES.EncoderOnly && console.warn(`Model type for '${s ?? l?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`), e = await Promise.all([
      AutoConfig.from_pretrained(n, c),
      constructSession(n, c.model_file_name ?? "model", c)
    ])), new this(...e);
  }
  /**
   * Runs the model with the provided inputs
   * @param {Object} model_inputs Object containing input tensors
   * @returns {Promise<Object>} Object containing output tensors
   */
  async _call(n) {
    return await this.forward(n);
  }
  /**
   * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
   * will be chosen based on the model type.
   * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
   * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
   * @throws {Error} This method must be implemented in subclasses.
   */
  async forward(n) {
    return await this._forward(this, n);
  }
  /**
   * @param {import('./utils/generation.js').GenerationConfigType} generation_config 
   * @param {number} input_ids_seq_length The starting sequence length for the input ids.
   * @returns {LogitsProcessorList}
   * @private
   */
  _get_logits_processor(n, o, u = null) {
    const l = new LogitsProcessorList();
    if (n.repetition_penalty !== null && n.repetition_penalty !== 1 && l.push(new RepetitionPenaltyLogitsProcessor(n.repetition_penalty)), n.no_repeat_ngram_size !== null && n.no_repeat_ngram_size > 0 && l.push(new NoRepeatNGramLogitsProcessor(n.no_repeat_ngram_size)), n.bad_words_ids !== null && l.push(new NoBadWordsLogitsProcessor(n.bad_words_ids, n.eos_token_id)), n.min_length !== null && n.eos_token_id !== null && n.min_length > 0 && l.push(new MinLengthLogitsProcessor(n.min_length, n.eos_token_id)), n.min_new_tokens !== null && n.eos_token_id !== null && n.min_new_tokens > 0 && l.push(new MinNewTokensLengthLogitsProcessor(
      o,
      n.min_new_tokens,
      n.eos_token_id
    )), n.forced_bos_token_id !== null && l.push(new ForcedBOSTokenLogitsProcessor(n.forced_bos_token_id)), n.forced_eos_token_id !== null && l.push(new ForcedEOSTokenLogitsProcessor(
      n.max_length,
      n.forced_eos_token_id
    )), n.begin_suppress_tokens !== null) {
      let h = o > 1 || n.forced_bos_token_id === null ? o : o + 1;
      n.forced_decoder_ids !== null && (h += n.forced_decoder_ids[n.forced_decoder_ids.length - 1][0]), l.push(new SuppressTokensAtBeginLogitsProcessor(n.begin_suppress_tokens, h));
    }
    return n.forced_decoder_ids !== null && l.push(new ForceTokensLogitsProcessor(n.forced_decoder_ids)), u !== null && l.extend(u), l;
  }
  /**
   * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
   * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
   * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
   * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
   */
  _get_generation_config(n) {
    let o = new GenerationConfig(this.config);
    return "generation_config" in this && Object.assign(o, this.generation_config), n !== null && Object.assign(o, n), o;
  }
  /**
   * @typedef {import('./utils/maths.js').TypedArray} TypedArray
   */
  /**
   * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
   * @typedef {Object} DecoderOutput
   * 
   * Generates text based on the given inputs and generation configuration using the model.
   * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
   * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
   * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
   * @param {Object} options options
   * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
   * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
   * @throws {Error} Throws an error if the inputs array is empty.
   */
  async generate(n, o = null, u = null, {
    inputs_attention_mask: l = null
  } = {}) {
    if (!this.can_generate) {
      let m = `The current model class (${MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor)}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;
      const _ = this.config.model_type, b = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(_) ?? MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(_) ?? MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(_) ?? MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(_);
      throw b && (m += ` Please use the following class instead: '${b[0]}'`), Error(m);
    }
    if (!(n instanceof Tensor) && !isTypedArray(n) && !Array.isArray(n))
      throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${n.constructor.name}".`);
    let h;
    if (this.config.is_encoder_decoder)
      h = 0;
    else if (h = n instanceof Tensor ? n.dims.at(-1) : n.length, h === 0)
      throw Error("Must supply a non-empty array of input token ids.");
    o = this._get_generation_config(o), u = u ?? new LogitsProcessorList(), u = this._get_logits_processor(
      o,
      h,
      u
    );
    let a = o.eos_token_id;
    a !== null && !Array.isArray(a) && (a = [a]);
    let f = 1;
    const g = f + (o.max_new_tokens ?? 1 / 0), c = Number.isInteger(o.max_length) && (o.max_new_tokens ?? null) === null;
    let s = Sampler.getSampler(o), t = this.getStartBeams(n, o, f, l);
    for (; t.some((p) => !p.done) && f < g; ) {
      let p = [];
      for (let m of t) {
        if (m.done) {
          p.push(m);
          continue;
        }
        if (c && m.output_token_ids.length >= o.max_length) {
          m.done = !0, p.push(m);
          continue;
        }
        let _ = await this.runBeam(m);
        o.output_attentions && this.addAttentionsToBeam(m, _), o.output_scores;
        let b = _.logits.slice(null, -1, null);
        u(m.output_token_ids, b);
        let y = s(b);
        for (let [w, T] of y) {
          let S = { ...m };
          this.updateBeam(S, w), S.score += T, a && a.includes(w) && (S.done = !0), p.push(S);
        }
      }
      ++f, p = this.groupBeams(p).map(
        (m) => m.sort((_, b) => b.score - _.score).slice(0, o.num_beams)
        // remove outside beam width
      ), t = p.flat(), o.callback_function && o.callback_function(t);
    }
    const e = this.groupBeams(t), r = (p) => e.map(
      (m) => o.num_return_sequences > 1 ? m.slice(0, o.num_return_sequences).map((_) => _[p]) : [m[0][p]]
    ).flat(), i = r("output_token_ids");
    if (o.return_dict_in_generate) {
      const p = r("decoder_attentions"), m = r("cross_attentions");
      return {
        sequences: i,
        decoder_attentions: p,
        cross_attentions: m
      };
    } else
      return i;
  }
  /**
   * Helper function to add attentions to beam
   * @param {Object} beam 
   * @param {Object} output
   * @private 
   */
  addAttentionsToBeam(n, o) {
    if (this.config.is_encoder_decoder) {
      if (!o.cross_attentions || o.cross_attentions.length === 0)
        throw Error(
          "`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`."
        );
      n.cross_attentions || (n.cross_attentions = []), n.cross_attentions.push(o.cross_attentions);
    }
    if (!o.decoder_attentions || o.decoder_attentions.length === 0)
      throw Error(
        "`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`."
      );
    n.decoder_attentions || (n.decoder_attentions = []), n.decoder_attentions.push(o.decoder_attentions);
  }
  /**
   * Groups an array of beam objects by their ids.
   *
   * @param {Array} beams The array of beam objects to group.
   * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
   */
  groupBeams(n) {
    const o = /* @__PURE__ */ Object.create(null);
    for (const u of n)
      o[u.id] === void 0 ? o[u.id] = [u] : o[u.id].push(u);
    return Object.values(o);
  }
  /**
   * Returns an object containing past key values from the given decoder results object.
   *
   * @param {Object} decoderResults The decoder results object.
   * @param {Object} pastKeyValues The previous past key values.
   * @returns {Object} An object containing past key values.
   */
  getPastKeyValues(n, o) {
    const u = /* @__PURE__ */ Object.create(null);
    for (const l in n)
      if (l.startsWith("present")) {
        let h = l.replace("present", "past_key_values");
        o && l.includes("encoder") ? u[h] = o[h] : u[h] = n[l];
      }
    return u;
  }
  /**
   * Returns an object containing attentions from the given decoder results object.
   *
   * @param {Object} decoderResults The decoder results object.
   * @returns {Object} An object containing attentions.
   */
  getAttentions(n) {
    const o = /* @__PURE__ */ Object.create(null);
    for (const u of ["cross_attentions", "decoder_attentions"]) {
      const l = [];
      for (const h in n)
        if (h.startsWith(u)) {
          const a = h.split(".").pop();
          l[a] = n[h];
        }
      o[u] = l;
    }
    return o;
  }
  /**
   * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
   *
   * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
   * @param {Object} pastKeyValues An object containing past key values.
   */
  addPastKeyValues(n, o) {
    if (o)
      Object.assign(n, o);
    else if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? !0)) {
      let l = [1, this.num_encoder_heads, 0, this.encoder_dim_kv], h = [1, this.num_decoder_heads, 0, this.decoder_dim_kv];
      for (let a = 0; a < this.num_decoder_layers; ++a)
        n[`past_key_values.${a}.encoder.key`] = new Tensor("float32", [], l), n[`past_key_values.${a}.encoder.value`] = new Tensor("float32", [], l), n[`past_key_values.${a}.decoder.key`] = new Tensor("float32", [], h), n[`past_key_values.${a}.decoder.value`] = new Tensor("float32", [], h);
    } else if (this.config.model_type === "falcon") {
      let l = [1 * this.num_heads, 0, this.dim_kv];
      for (let h = 0; h < this.num_layers; ++h)
        n[`past_key_values.${h}.key`] = new Tensor("float32", [], l), n[`past_key_values.${h}.value`] = new Tensor("float32", [], l);
    } else if (this.config.multi_query) {
      let l = [1 * this.num_heads, 0, 2 * this.dim_kv];
      for (let h = 0; h < this.num_layers; ++h)
        n[`past_key_values.${h}.key_value`] = new Tensor("float32", [], l);
    } else if (this.config.model_type === "bloom") {
      let l = [1 * this.num_heads, this.dim_kv, 0], h = [1 * this.num_heads, 0, this.dim_kv];
      for (let a = 0; a < this.num_layers; ++a)
        n[`past_key_values.${a}.key`] = new Tensor("float32", [], l), n[`past_key_values.${a}.value`] = new Tensor("float32", [], h);
    } else {
      let l = [1, this.num_heads, 0, this.dim_kv];
      for (let h = 0; h < this.num_layers; ++h)
        n[`past_key_values.${h}.key`] = new Tensor("float32", [], l), n[`past_key_values.${h}.value`] = new Tensor("float32", [], l);
    }
  }
  /**
   * Initializes and returns the beam for text generation task
   * @param {Tensor} inputTokenIds The input token ids.
   * @param {Object} generation_config The generation config.
   * @param {number} numOutputTokens The number of tokens to be generated.
   * @param {Tensor} inputs_attention_mask Optional input attention mask.
   * @returns {any} A Beam object representing the initialized beam.
   * @private
   */
  getStartBeams(n, o, u, l) {
    return this._getStartBeams(this, n, o, u, l);
  }
  /**
   * Runs a single step of the beam search generation algorithm.
   * @param {any} beam The current beam being generated.
   * @returns {Promise<any>} The updated beam after a single generation step.
   * @private
   */
  async runBeam(n) {
    return await this._runBeam(this, n);
  }
  /**
   * Update a beam with a new token ID.
   * @param {Object} beam The beam to update.
   * @param {number} newTokenId The new token ID to add to the beam's output.
   * @private
   */
  updateBeam(n, o) {
    return this._updateBeam(n, o);
  }
}
class ModelOutput {
}
class BertPreTrainedModel extends PreTrainedModel {
}
class BertModel extends BertPreTrainedModel {
}
class BertForMaskedLM extends BertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class BertForSequenceClassification extends BertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class BertForTokenClassification extends BertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class BertForQuestionAnswering extends BertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class NomicBertPreTrainedModel extends PreTrainedModel {
}
class NomicBertModel extends NomicBertPreTrainedModel {
}
class RoFormerPreTrainedModel extends PreTrainedModel {
}
class RoFormerModel extends RoFormerPreTrainedModel {
}
class RoFormerForMaskedLM extends RoFormerPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class RoFormerForTokenClassification extends RoFormerPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class ConvBertPreTrainedModel extends PreTrainedModel {
}
class ConvBertModel extends ConvBertPreTrainedModel {
}
class ConvBertForMaskedLM extends ConvBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class ConvBertForTokenClassification extends ConvBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class ElectraPreTrainedModel extends PreTrainedModel {
}
class ElectraModel extends ElectraPreTrainedModel {
}
class ElectraForMaskedLM extends ElectraPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class ElectraForSequenceClassification extends ElectraPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class ElectraForTokenClassification extends ElectraPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class ElectraForQuestionAnswering extends ElectraPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class CamembertPreTrainedModel extends PreTrainedModel {
}
class CamembertModel extends CamembertPreTrainedModel {
}
class CamembertForMaskedLM extends CamembertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class CamembertForSequenceClassification extends CamembertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class CamembertForTokenClassification extends CamembertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class CamembertForQuestionAnswering extends CamembertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class DebertaPreTrainedModel extends PreTrainedModel {
}
class DebertaModel extends DebertaPreTrainedModel {
}
class DebertaForMaskedLM extends DebertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class DebertaForSequenceClassification extends DebertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class DebertaForTokenClassification extends DebertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class DebertaForQuestionAnswering extends DebertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class DebertaV2PreTrainedModel extends PreTrainedModel {
}
class DebertaV2Model extends DebertaV2PreTrainedModel {
}
class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class DistilBertPreTrainedModel extends PreTrainedModel {
}
class DistilBertModel extends DistilBertPreTrainedModel {
}
class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class DistilBertForTokenClassification extends DistilBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class DistilBertForMaskedLM extends DistilBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class EsmPreTrainedModel extends PreTrainedModel {
}
class EsmModel extends EsmPreTrainedModel {
}
class EsmForMaskedLM extends EsmPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class EsmForSequenceClassification extends EsmPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class EsmForTokenClassification extends EsmPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class MobileBertPreTrainedModel extends PreTrainedModel {
}
class MobileBertModel extends MobileBertPreTrainedModel {
}
class MobileBertForMaskedLM extends MobileBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} returned object
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} returned object
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class MPNetPreTrainedModel extends PreTrainedModel {
}
class MPNetModel extends MPNetPreTrainedModel {
}
class MPNetForMaskedLM extends MPNetPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class MPNetForSequenceClassification extends MPNetPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class MPNetForTokenClassification extends MPNetPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class MPNetForQuestionAnswering extends MPNetPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class SqueezeBertPreTrainedModel extends PreTrainedModel {
}
class SqueezeBertModel extends SqueezeBertPreTrainedModel {
}
class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} returned object
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} returned object
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class AlbertPreTrainedModel extends PreTrainedModel {
}
class AlbertModel extends AlbertPreTrainedModel {
}
class AlbertForSequenceClassification extends AlbertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} returned object
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class AlbertForQuestionAnswering extends AlbertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} returned object
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class AlbertForMaskedLM extends AlbertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class T5PreTrainedModel extends PreTrainedModel {
}
class T5Model extends T5PreTrainedModel {
}
class T5ForConditionalGeneration extends T5PreTrainedModel {
  /**
   * Creates a new instance of the `T5ForConditionalGeneration` class.
   * @param {Object} config The model configuration.
   * @param {any} session session for the model.
   * @param {any} decoder_merged_session session for the decoder.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.num_decoder_layers, this.num_decoder_heads = this.config.num_heads, this.decoder_dim_kv = this.config.d_kv, this.num_encoder_layers = this.config.num_layers, this.num_encoder_heads = this.config.num_heads, this.encoder_dim_kv = this.config.d_kv;
  }
}
class LongT5PreTrainedModel extends PreTrainedModel {
}
class LongT5Model extends LongT5PreTrainedModel {
}
class LongT5ForConditionalGeneration extends LongT5PreTrainedModel {
  /**
   * Creates a new instance of the `LongT5ForConditionalGeneration` class.
   * @param {Object} config The model configuration.
   * @param {any} session session for the model.
   * @param {any} decoder_merged_session session for the decoder.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.num_decoder_layers, this.num_decoder_heads = this.config.num_heads, this.decoder_dim_kv = this.config.d_kv, this.num_encoder_layers = this.config.num_layers, this.num_encoder_heads = this.config.num_heads, this.encoder_dim_kv = this.config.d_kv;
  }
}
class MT5PreTrainedModel extends PreTrainedModel {
}
class MT5Model extends MT5PreTrainedModel {
}
class MT5ForConditionalGeneration extends MT5PreTrainedModel {
  /**
   * Creates a new instance of the `MT5ForConditionalGeneration` class.
   * @param {any} config The model configuration.
   * @param {any} session The ONNX session containing the encoder weights.
   * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.num_decoder_layers, this.num_decoder_heads = this.config.num_heads, this.decoder_dim_kv = this.config.d_kv, this.num_encoder_layers = this.config.num_layers, this.num_encoder_heads = this.config.num_heads, this.encoder_dim_kv = this.config.d_kv;
  }
}
class BartPretrainedModel extends PreTrainedModel {
}
class BartModel extends BartPretrainedModel {
}
class BartForConditionalGeneration extends BartPretrainedModel {
  /**
   * Creates a new instance of the `BartForConditionalGeneration` class.
   * @param {Object} config The configuration object for the Bart model.
   * @param {Object} session The ONNX session used to execute the model.
   * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
   * @param {Object} generation_config The generation configuration object.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class BartForSequenceClassification extends BartPretrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class MBartPreTrainedModel extends PreTrainedModel {
}
class MBartModel extends MBartPreTrainedModel {
}
class MBartForConditionalGeneration extends MBartPreTrainedModel {
  /**
   * Creates a new instance of the `MBartForConditionalGeneration` class.
   * @param {Object} config The configuration object for the Bart model.
   * @param {Object} session The ONNX session used to execute the model.
   * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
   * @param {Object} generation_config The generation configuration object.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class MBartForSequenceClassification extends MBartPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class MBartForCausalLM extends MBartPreTrainedModel {
  /**
   * Creates a new instance of the `MBartForCausalLM` class.
   * @param {Object} config Configuration object for the model.
   * @param {Object} decoder_merged_session ONNX Session object for the decoder.
   * @param {Object} generation_config Configuration object for the generation process.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class BlenderbotPreTrainedModel extends PreTrainedModel {
}
class BlenderbotModel extends BlenderbotPreTrainedModel {
}
class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel {
  /**
   * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
   * @param {any} config The model configuration.
   * @param {any} session The ONNX session containing the encoder weights.
   * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class BlenderbotSmallPreTrainedModel extends PreTrainedModel {
}
class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel {
}
class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel {
  /**
   * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
   * @param {any} config The model configuration.
   * @param {any} session The ONNX session containing the encoder weights.
   * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class RobertaPreTrainedModel extends PreTrainedModel {
}
class RobertaModel extends RobertaPreTrainedModel {
}
class RobertaForMaskedLM extends RobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class RobertaForSequenceClassification extends RobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} returned object
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class RobertaForTokenClassification extends RobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class RobertaForQuestionAnswering extends RobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} returned object
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class XLMPreTrainedModel extends PreTrainedModel {
}
class XLMModel extends XLMPreTrainedModel {
}
class XLMWithLMHeadModel extends XLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class XLMForSequenceClassification extends XLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} returned object
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class XLMForTokenClassification extends XLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class XLMForQuestionAnswering extends XLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} returned object
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class XLMRobertaPreTrainedModel extends PreTrainedModel {
}
class XLMRobertaModel extends XLMRobertaPreTrainedModel {
}
class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<MaskedLMOutput>} returned object
   */
  async _call(n) {
    return new MaskedLMOutput(await super._call(n));
  }
}
class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} returned object
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {
  /**
   * Calls the model on new inputs.
   *
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<QuestionAnsweringModelOutput>} returned object
   */
  async _call(n) {
    return new QuestionAnsweringModelOutput(await super._call(n));
  }
}
class ASTPreTrainedModel extends PreTrainedModel {
}
class ASTModel extends ASTPreTrainedModel {
}
class ASTForAudioClassification extends ASTPreTrainedModel {
}
class WhisperPreTrainedModel extends PreTrainedModel {
}
class WhisperModel extends WhisperPreTrainedModel {
}
class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
  requires_attention_mask = !1;
  main_input_name = "input_features";
  /**
   * Creates a new instance of the `WhisperForConditionalGeneration` class.
   * @param {Object} config Configuration object for the model.
   * @param {Object} session ONNX Session object for the model.
   * @param {Object} decoder_merged_session ONNX Session object for the decoder.
   * @param {Object} generation_config Configuration object for the generation process.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
  /**
   * @typedef {Object} WhisperGenerationConfig
   * @extends GenerationConfig
   * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
   * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
   * with the text. This can be used with or without the `return_timestamps` option. To get word-level
   * timestamps, use the tokenizer to group the tokens into words.
   * @property {number} [num_frames=null]  The number of audio frames available in this chunk. This is only used generating word-level timestamps.
   */
  /**
   * Generates outputs based on input and generation configuration.
   * @param {Object} inputs Input data for the model.
   * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
   * @param {Object} logits_processor Optional logits processor object.
   * @returns {Promise<Object>} Promise object represents the generated outputs.
   */
  async generate(n, o = null, u = null) {
    if (o = this._get_generation_config(o), o.return_timestamps ??= !1, o.return_timestamps && (u = [new WhisperTimeStampLogitsProcessor(o)]), o.return_token_timestamps && (o.output_attentions = !0, o.return_dict_in_generate = !0, o.task === "translate" && console.warn("Token-level timestamps may not be reliable for task 'translate'."), !o.alignment_heads))
      throw new Error(
        "Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config."
      );
    const l = await super.generate(n, o, u);
    return o.return_token_timestamps && o.alignment_heads && (l.token_timestamps = this._extract_token_timestamps(
      l,
      o.alignment_heads,
      o.num_frames
    )), l;
  }
  /**
   * Calculates token-level timestamps using the encoder-decoder cross-attentions and
   * dynamic time-warping (DTW) to map each output token to a position in the input audio.
   * @param {Object} generate_outputs Outputs generated by the model
   * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model
   * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model
   * @param {number[][]} generate_outputs.sequences The sequences output by the model
   * @param {number[][]} alignment_heads Alignment heads of the model
   * @param {number} [num_frames=null] Number of frames in the input audio.
   * @param {number} [time_precision=0.02] Precision of the timestamps in seconds
   * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token
   */
  _extract_token_timestamps(n, o, u = null, l = 0.02) {
    if (!n.cross_attentions)
      throw new Error(
        "Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`."
      );
    let h = this.config.median_filter_width;
    h === void 0 && (console.warn("Model config has no `median_filter_width`, using default value of 7."), h = 7);
    const a = n.cross_attentions.map((c) => {
      let s = Array.from(
        { length: this.config.decoder_layers },
        (m, _) => cat(c.map((b) => b[_]), 2)
      ), t = stack(o.map(([m, _]) => u ? s[m].slice(null, _, null, [0, u]) : s[m].slice(null, _)));
      t = t.transpose(1, 0, 2, 3);
      let [e, r] = std_mean(t, -2, 0, !0), i = t.clone();
      for (let m = 0; m < i.dims[0]; ++m) {
        let _ = i[m];
        for (let b = 0; b < _.dims[0]; ++b) {
          let y = _[b];
          const w = e[m][b][0], T = r[m][b][0];
          for (let S = 0; S < y.dims[0]; ++S) {
            let E = y[S];
            for (let O = 0; O < E.data.length; ++O)
              E.data[O] = (E.data[O] - T.data[O]) / w.data[O];
            E.data.set(medianFilter(E.data, h));
          }
        }
      }
      return mean(i, 1);
    }), f = [n.sequences.length, n.sequences[0].length], g = new Tensor(
      "float32",
      new Float32Array(f[0] * f[1]),
      f
    );
    for (let c = 0; c < f[0]; ++c) {
      const s = a[c].neg().squeeze_(0);
      let [t, e] = dynamicTimeWarping(s), r = Array.from({ length: t.length - 1 }, (m, _) => t[_ + 1] - t[_]), i = mergeArrays([1], r).map((m) => !!m), p = [];
      for (let m = 0; m < i.length; ++m)
        i[m] && p.push(e[m] * l);
      g[c].data.set(p, 1);
    }
    return g;
  }
}
class VisionEncoderDecoderModel extends PreTrainedModel {
  main_input_name = "pixel_values";
  /**
   * Creates a new instance of the `VisionEncoderDecoderModel` class.
   * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
   * @param {Object} session The ONNX session containing the encoder model.
   * @param {any} decoder_merged_session The ONNX session containing the merged decoder model.
   * @param {Object} generation_config Configuration object for the generation process.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l;
    const h = this.config.encoder, a = this.config.decoder, f = h.model_type;
    (MODEL_MAPPING_NAMES_ENCODER_ONLY.get(f) ?? MODEL_MAPPING_NAMES_ENCODER_DECODER.get(f)) || console.warn(`Model type for encoder '${f}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`);
    const c = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(a.model_type);
    if (!c)
      throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`);
    const s = c[1], t = new s(a, u, l);
    this.add_encoder_pkv = "num_decoder_layers" in t, this.add_encoder_pkv ? (this.num_decoder_layers = t.num_decoder_layers, this.num_decoder_heads = t.num_decoder_heads, this.decoder_dim_kv = t.decoder_dim_kv, this.num_encoder_layers = t.num_encoder_layers, this.num_encoder_heads = t.num_encoder_heads, this.encoder_dim_kv = t.encoder_dim_kv) : (this.num_layers = t.num_layers, this.num_heads = t.num_heads, this.dim_kv = t.dim_kv);
  }
}
class CLIPPreTrainedModel extends PreTrainedModel {
}
class CLIPModel extends CLIPPreTrainedModel {
}
class CLIPTextModelWithProjection extends CLIPPreTrainedModel {
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, o = {}) {
    return o.model_file_name ??= "text_model", super.from_pretrained(n, o);
  }
}
class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, o = {}) {
    return o.model_file_name ??= "vision_model", super.from_pretrained(n, o);
  }
}
class SiglipPreTrainedModel extends PreTrainedModel {
}
class SiglipModel extends SiglipPreTrainedModel {
}
class SiglipTextModel extends SiglipPreTrainedModel {
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, o = {}) {
    return o.model_file_name ??= "text_model", super.from_pretrained(n, o);
  }
}
class SiglipVisionModel extends CLIPPreTrainedModel {
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, o = {}) {
    return o.model_file_name ??= "vision_model", super.from_pretrained(n, o);
  }
}
class ChineseCLIPPreTrainedModel extends PreTrainedModel {
}
class ChineseCLIPModel extends ChineseCLIPPreTrainedModel {
}
class CLIPSegPreTrainedModel extends PreTrainedModel {
}
class CLIPSegModel extends CLIPSegPreTrainedModel {
}
class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel {
}
class GPT2PreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `GPT2PreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.n_head, this.num_layers = this.config.n_layer, this.dim_kv = this.config.n_embd / this.num_heads;
  }
}
class GPT2Model extends GPT2PreTrainedModel {
}
class GPT2LMHeadModel extends GPT2PreTrainedModel {
}
class GPTNeoPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `GPTNeoPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_heads, this.num_layers = this.config.num_layers, this.dim_kv = this.config.hidden_size / this.num_heads;
  }
}
class GPTNeoModel extends GPTNeoPreTrainedModel {
}
class GPTNeoForCausalLM extends GPTNeoPreTrainedModel {
}
class GPTNeoXPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `GPTNeoXPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.num_heads;
  }
}
class GPTNeoXModel extends GPTNeoXPreTrainedModel {
}
class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel {
}
class GPTJPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `GPTJPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.n_head, this.num_layers = this.config.n_layer, this.dim_kv = this.config.n_embd / this.num_heads;
  }
}
class GPTJModel extends GPTJPreTrainedModel {
}
class GPTJForCausalLM extends GPTJPreTrainedModel {
}
class GPTBigCodePreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `GPTBigCodePreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.n_head, this.num_layers = this.config.n_layer, this.dim_kv = this.config.n_embd / this.num_heads;
  }
}
class GPTBigCodeModel extends GPTBigCodePreTrainedModel {
}
class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel {
}
class CodeGenPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `CodeGenPreTrainedModel` class.
   * @param {Object} config The model configuration object.
   * @param {Object} session The ONNX session object.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.n_head, this.num_layers = this.config.n_layer, this.dim_kv = this.config.n_embd / this.num_heads;
  }
}
class CodeGenModel extends CodeGenPreTrainedModel {
}
class CodeGenForCausalLM extends CodeGenPreTrainedModel {
}
class LlamaPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `LlamaPreTrainedModel` class.
   * @param {Object} config The model configuration object.
   * @param {Object} session The ONNX session object.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
  }
}
class LlamaModel extends LlamaPreTrainedModel {
}
class LlamaForCausalLM extends LlamaPreTrainedModel {
}
class Qwen2PreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `Qwen2PreTrainedModel` class.
   * @param {Object} config The model configuration object.
   * @param {Object} session The ONNX session object.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
  }
}
class Qwen2Model extends Qwen2PreTrainedModel {
}
class Qwen2ForCausalLM extends Qwen2PreTrainedModel {
}
class PhiPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `PhiPreTrainedModel` class.
   * @param {Object} config The model configuration object.
   * @param {Object} session The ONNX session object.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.num_heads;
  }
}
class PhiModel extends PhiPreTrainedModel {
}
class PhiForCausalLM extends PhiPreTrainedModel {
}
class BloomPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `BloomPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.n_head, this.num_layers = this.config.n_layer, this.dim_kv = this.config.hidden_size / this.num_heads;
  }
}
class BloomModel extends BloomPreTrainedModel {
}
class BloomForCausalLM extends BloomPreTrainedModel {
}
class MptPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `MptPreTrainedModel` class.
   * @param {Object} config The model configuration object.
   * @param {Object} session The ONNX session object.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.n_heads, this.num_layers = this.config.n_layers, this.dim_kv = this.config.d_model / this.num_heads;
  }
}
class MptModel extends MptPreTrainedModel {
}
class MptForCausalLM extends MptPreTrainedModel {
}
class OPTPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `OPTPreTrainedModel` class.
   * @param {Object} config The model configuration object.
   * @param {Object} session The ONNX session object.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.num_heads;
  }
}
class OPTModel extends OPTPreTrainedModel {
}
class OPTForCausalLM extends OPTPreTrainedModel {
}
class ViTPreTrainedModel extends PreTrainedModel {
}
class ViTModel extends ViTPreTrainedModel {
}
class ViTForImageClassification extends ViTPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class FastViTPreTrainedModel extends PreTrainedModel {
}
class FastViTModel extends FastViTPreTrainedModel {
}
class FastViTForImageClassification extends FastViTPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class VitMattePreTrainedModel extends PreTrainedModel {
}
class VitMatteForImageMatting extends VitMattePreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new ImageMattingOutput(await super._call(n));
  }
}
class MobileViTPreTrainedModel extends PreTrainedModel {
}
class MobileViTModel extends MobileViTPreTrainedModel {
}
class MobileViTForImageClassification extends MobileViTPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class MobileViTV2PreTrainedModel extends PreTrainedModel {
}
class MobileViTV2Model extends MobileViTV2PreTrainedModel {
}
class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class OwlViTPreTrainedModel extends PreTrainedModel {
}
class OwlViTModel extends OwlViTPreTrainedModel {
}
class OwlViTForObjectDetection extends OwlViTPreTrainedModel {
}
class Owlv2PreTrainedModel extends PreTrainedModel {
}
class Owlv2Model extends Owlv2PreTrainedModel {
}
class Owlv2ForObjectDetection extends Owlv2PreTrainedModel {
}
class BeitPreTrainedModel extends PreTrainedModel {
}
class BeitModel extends BeitPreTrainedModel {
}
class BeitForImageClassification extends BeitPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class DetrPreTrainedModel extends PreTrainedModel {
}
class DetrModel extends DetrPreTrainedModel {
}
class DetrForObjectDetection extends DetrPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new DetrObjectDetectionOutput(await super._call(n));
  }
}
class DetrForSegmentation extends DetrPreTrainedModel {
  /**
   * Runs the model with the provided inputs
   * @param {Object} model_inputs Model inputs
   * @returns {Promise<DetrSegmentationOutput>} Object containing segmentation outputs
   */
  async _call(n) {
    return new DetrSegmentationOutput(await super._call(n));
  }
}
class DetrObjectDetectionOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
   * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
   * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
   */
  constructor({ logits: n, pred_boxes: o }) {
    super(), this.logits = n, this.pred_boxes = o;
  }
}
class DetrSegmentationOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits The output logits of the model.
   * @param {Tensor} output.pred_boxes Predicted boxes.
   * @param {Tensor} output.pred_masks Predicted masks.
   */
  constructor({ logits: n, pred_boxes: o, pred_masks: u }) {
    super(), this.logits = n, this.pred_boxes = o, this.pred_masks = u;
  }
}
class TableTransformerPreTrainedModel extends PreTrainedModel {
}
class TableTransformerModel extends TableTransformerPreTrainedModel {
}
class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new TableTransformerObjectDetectionOutput(await super._call(n));
  }
}
class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput {
}
class DeiTPreTrainedModel extends PreTrainedModel {
}
class DeiTModel extends DeiTPreTrainedModel {
}
class DeiTForImageClassification extends DeiTPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class ResNetPreTrainedModel extends PreTrainedModel {
}
class ResNetModel extends ResNetPreTrainedModel {
}
class ResNetForImageClassification extends ResNetPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class SwinPreTrainedModel extends PreTrainedModel {
}
class SwinModel extends SwinPreTrainedModel {
}
class SwinForImageClassification extends SwinPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class Swin2SRPreTrainedModel extends PreTrainedModel {
}
class Swin2SRModel extends Swin2SRPreTrainedModel {
}
class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel {
}
class DPTPreTrainedModel extends PreTrainedModel {
}
class DPTModel extends DPTPreTrainedModel {
}
class DPTForDepthEstimation extends DPTPreTrainedModel {
}
class DepthAnythingPreTrainedModel extends PreTrainedModel {
}
class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel {
}
class GLPNPreTrainedModel extends PreTrainedModel {
}
class GLPNModel extends GLPNPreTrainedModel {
}
class GLPNForDepthEstimation extends GLPNPreTrainedModel {
}
class DonutSwinPreTrainedModel extends PreTrainedModel {
}
class DonutSwinModel extends DonutSwinPreTrainedModel {
}
class ConvNextPreTrainedModel extends PreTrainedModel {
}
class ConvNextModel extends ConvNextPreTrainedModel {
}
class ConvNextForImageClassification extends ConvNextPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class ConvNextV2PreTrainedModel extends PreTrainedModel {
}
class ConvNextV2Model extends ConvNextV2PreTrainedModel {
}
class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class Dinov2PreTrainedModel extends PreTrainedModel {
}
class Dinov2Model extends Dinov2PreTrainedModel {
}
class Dinov2ForImageClassification extends Dinov2PreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class YolosPreTrainedModel extends PreTrainedModel {
}
class YolosModel extends YolosPreTrainedModel {
}
class YolosForObjectDetection extends YolosPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new YolosObjectDetectionOutput(await super._call(n));
  }
}
class YolosObjectDetectionOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
   * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
   * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
   */
  constructor({ logits: n, pred_boxes: o }) {
    super(), this.logits = n, this.pred_boxes = o;
  }
}
class SamPreTrainedModel extends PreTrainedModel {
}
class SamModel extends SamPreTrainedModel {
  /**
   * Creates a new instance of the `SamModel` class.
   * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
   * @param {Object} vision_encoder The ONNX session containing the vision encoder model.
   * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model.
   */
  constructor(n, o, u) {
    super(n, o), this.prompt_encoder_mask_decoder = u;
  }
  /**
   * Compute image embeddings and positional image embeddings, given the pixel values of an image.
   * @param {Object} model_inputs Object containing the model inputs.
   * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.
   * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.
   */
  async get_image_embeddings({ pixel_values: n }) {
    return await encoderForward(this, { pixel_values: n });
  }
  /**
   * @typedef {Object} SamModelInputs Object containing the model inputs.
   * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
   * These can be obtained using a `SamProcessor`.
   * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`.
   * This is used by the prompt encoder to encode the prompt.
   * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
   * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:
   *  - `1`: the point is a point that contains the object of interest
   *  - `0`: the point is a point that does not contain the object of interest
   *  - `-1`: the point corresponds to the background
   *  - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
   * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.
   * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.
   */
  /**
   * @param {SamModelInputs} model_inputs Object containing the model inputs.
   * @returns {Promise<Object>} The output of the model.
   */
  async forward(n) {
    if ((!n.image_embeddings || !n.image_positional_embeddings) && (n = {
      ...n,
      ...await this.get_image_embeddings(n)
    }), !n.input_labels) {
      const o = n.input_points.dims.slice(0, -1), u = o.reduce((l, h) => l * h, 1);
      n.input_labels = new Tensor(
        "int64",
        new BigInt64Array(u).fill(1n),
        o
      );
    }
    return await sessionRun(this.prompt_encoder_mask_decoder, {
      input_points: n.input_points,
      input_labels: n.input_labels,
      image_embeddings: n.image_embeddings,
      image_positional_embeddings: n.image_positional_embeddings
    });
  }
  /**
   * Runs the model with the provided inputs
   * @param {Object} model_inputs Model inputs
   * @returns {Promise<SamImageSegmentationOutput>} Object containing segmentation outputs
   */
  async _call(n) {
    return new SamImageSegmentationOutput(await super._call(n));
  }
}
class SamImageSegmentationOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.iou_scores The output logits of the model.
   * @param {Tensor} output.pred_masks Predicted boxes.
   */
  constructor({ iou_scores: n, pred_masks: o }) {
    super(), this.iou_scores = n, this.pred_masks = o;
  }
}
class MarianPreTrainedModel extends PreTrainedModel {
}
class MarianModel extends MarianPreTrainedModel {
}
class MarianMTModel extends MarianPreTrainedModel {
  /**
   * Creates a new instance of the `MarianMTModel` class.
  * @param {Object} config The model configuration object.
  * @param {Object} session The ONNX session object.
  * @param {any} decoder_merged_session 
  * @param {any} generation_config 
  */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class M2M100PreTrainedModel extends PreTrainedModel {
}
class M2M100Model extends M2M100PreTrainedModel {
}
class M2M100ForConditionalGeneration extends M2M100PreTrainedModel {
  /**
   * Creates a new instance of the `M2M100ForConditionalGeneration` class.
  * @param {Object} config The model configuration object.
  * @param {Object} session The ONNX session object.
  * @param {any} decoder_merged_session 
  * @param {any} generation_config 
  */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
  }
}
class Wav2Vec2PreTrainedModel extends PreTrainedModel {
}
class Wav2Vec2Model extends Wav2Vec2PreTrainedModel {
}
class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {
  /**
   * @param {Object} model_inputs
   * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
   * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
   */
  async _call(n) {
    return new CausalLMOutput(await super._call(n));
  }
}
class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class UniSpeechPreTrainedModel extends PreTrainedModel {
}
class UniSpeechModel extends UniSpeechPreTrainedModel {
}
class UniSpeechForCTC extends UniSpeechPreTrainedModel {
  /**
   * @param {Object} model_inputs
   * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
   * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
   */
  async _call(n) {
    return new CausalLMOutput(await super._call(n));
  }
}
class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class UniSpeechSatPreTrainedModel extends PreTrainedModel {
}
class UniSpeechSatModel extends UniSpeechSatPreTrainedModel {
}
class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {
  /**
   * @param {Object} model_inputs
   * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
   * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
   */
  async _call(n) {
    return new CausalLMOutput(await super._call(n));
  }
}
class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class Wav2Vec2BertPreTrainedModel extends PreTrainedModel {
}
class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel {
}
class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {
  /**
   * @param {Object} model_inputs
   * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.
   * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
   */
  async _call(n) {
    return new CausalLMOutput(await super._call(n));
  }
}
class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class HubertModel extends Wav2Vec2PreTrainedModel {
}
class HubertForCTC extends Wav2Vec2PreTrainedModel {
  /**
   * @param {Object} model_inputs
   * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
   * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
   */
  async _call(n) {
    return new CausalLMOutput(await super._call(n));
  }
}
class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class WavLMPreTrainedModel extends PreTrainedModel {
}
class WavLMModel extends WavLMPreTrainedModel {
}
class WavLMForCTC extends WavLMPreTrainedModel {
  /**
   * @param {Object} model_inputs
   * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
   * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
   */
  async _call(n) {
    return new CausalLMOutput(await super._call(n));
  }
}
class WavLMForSequenceClassification extends WavLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class WavLMForXVector extends WavLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<XVectorOutput>} An object containing the model's output logits and speaker embeddings.
   */
  async _call(n) {
    return new XVectorOutput(await super._call(n));
  }
}
class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
   */
  async _call(n) {
    return new TokenClassifierOutput(await super._call(n));
  }
}
class SpeechT5PreTrainedModel extends PreTrainedModel {
}
class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel {
}
class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {
  /**
   * Creates a new instance of the `SpeechT5ForTextToSpeech` class.
   * @param {Object} config The model configuration.
   * @param {any} session session for the model.
   * @param {any} decoder_merged_session session for the decoder.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u, l) {
    super(n, o), this.decoder_merged_session = u, this.generation_config = l, this.num_decoder_layers = this.config.decoder_layers, this.num_decoder_heads = this.config.decoder_attention_heads, this.decoder_dim_kv = this.config.hidden_size / this.num_decoder_heads, this.num_encoder_layers = this.config.encoder_layers, this.num_encoder_heads = this.config.encoder_attention_heads, this.encoder_dim_kv = this.config.hidden_size / this.num_encoder_heads;
  }
  /**
   * @typedef {Object} SpeechOutput
   * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape
   * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
   * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
   * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape
   * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
   */
  /**
   * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.
   * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.
   * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.
   * @param {Object} options Optional parameters for generating speech.
   * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.
   * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.
   * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.
   * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.
   * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.
   * @returns {Promise<SpeechOutput>} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.
   */
  async generate_speech(n, o, {
    threshold: u = 0.5,
    minlenratio: l = 0,
    maxlenratio: h = 20,
    vocoder: a = null
    // output_cross_attentions = false, // TODO add
  } = {}) {
    const f = {
      input_ids: n
    }, { encoder_outputs: g, encoder_attention_mask: c } = await encoderForward(this, f), s = g.dims[1] / this.config.reduction_factor, t = Math.floor(s * h), e = Math.floor(s * l), r = this.config.num_mel_bins;
    let i = [], p = null, m = null, _ = 0;
    for (; ; ) {
      ++_;
      const w = boolTensor(!!m);
      let T;
      m ? T = m.output_sequence_out : T = new Tensor(
        "float32",
        new Float32Array(r),
        [1, 1, r]
      );
      let S = {
        use_cache_branch: w,
        output_sequence: T,
        encoder_attention_mask: c,
        speaker_embeddings: o,
        encoder_hidden_states: g
      };
      this.addPastKeyValues(S, p), m = await sessionRun(this.decoder_merged_session, S), p = this.getPastKeyValues(m, p);
      const { prob: E, spectrum: O } = m;
      if (i.push(O), _ >= e && // Finished when stop token or maximum length is reached.
      (Array.from(E.data).filter((v) => v >= u).length > 0 || _ >= t))
        break;
    }
    const b = cat(i), { waveform: y } = await sessionRun(a.session, { spectrogram: b });
    return {
      spectrogram: b,
      waveform: y
      // cross_attentions: null, // TODO add
    };
  }
}
class SpeechT5HifiGan extends PreTrainedModel {
  main_input_name = "spectrogram";
}
class TrOCRPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `TrOCRPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_encoder_layers = this.num_decoder_layers = this.config.decoder_layers, this.num_encoder_heads = this.num_decoder_heads = this.config.decoder_attention_heads, this.encoder_dim_kv = this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
  }
}
class TrOCRForCausalLM extends TrOCRPreTrainedModel {
}
class MistralPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `MistralPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_key_value_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
  }
}
class MistralModel extends MistralPreTrainedModel {
}
class MistralForCausalLM extends MistralPreTrainedModel {
}
class Starcoder2PreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `Starcoder2PreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_key_value_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
  }
}
class Starcoder2Model extends Starcoder2PreTrainedModel {
}
class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel {
}
class FalconPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `FalconPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
  }
}
class FalconModel extends FalconPreTrainedModel {
}
class FalconForCausalLM extends FalconPreTrainedModel {
}
class ClapPreTrainedModel extends PreTrainedModel {
}
class ClapModel extends ClapPreTrainedModel {
}
class ClapTextModelWithProjection extends ClapPreTrainedModel {
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, o = {}) {
    return o.model_file_name ??= "text_model", super.from_pretrained(n, o);
  }
}
class ClapAudioModelWithProjection extends ClapPreTrainedModel {
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, o = {}) {
    return o.model_file_name ??= "audio_model", super.from_pretrained(n, o);
  }
}
class VitsPreTrainedModel extends PreTrainedModel {
}
class VitsModel extends VitsPreTrainedModel {
  /**
   * Calls the model on new inputs.
   * @param {Object} model_inputs The inputs to the model.
   * @returns {Promise<VitsModelOutput>} The outputs for the VITS model.
   */
  async _call(n) {
    return new VitsModelOutput(await super._call(n));
  }
}
class SegformerPreTrainedModel extends PreTrainedModel {
}
class SegformerForImageClassification extends SegformerPreTrainedModel {
}
class SegformerForSemanticSegmentation extends SegformerPreTrainedModel {
}
class StableLmPreTrainedModel extends PreTrainedModel {
  /**
   * Creates a new instance of the `StableLmPreTrainedModel` class.
   * @param {Object} config The configuration of the model.
   * @param {any} session The ONNX session containing the model weights.
   * @param {GenerationConfig} generation_config The generation configuration.
   */
  constructor(n, o, u) {
    super(n, o), this.generation_config = u, this.config.pad_token_id = this.config.eos_token_id, this.num_heads = this.config.num_attention_heads, this.num_layers = this.config.num_hidden_layers, this.dim_kv = this.config.hidden_size / this.num_heads;
  }
}
class StableLmForCausalLM extends StableLmPreTrainedModel {
}
class EfficientNetPreTrainedModel extends PreTrainedModel {
}
class EfficientNetModel extends EfficientNetPreTrainedModel {
}
class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {
  /**
   * @param {any} model_inputs
   */
  async _call(n) {
    return new SequenceClassifierOutput(await super._call(n));
  }
}
class PretrainedMixin {
  /**
   * Mapping from model type to model class.
   * @type {Map<string, Object>[]}
   */
  static MODEL_CLASS_MAPPINGS = null;
  /**
   * Whether to attempt to instantiate the base class (`PretrainedModel`) if 
   * the model type is not found in the mapping.
   */
  static BASE_IF_FAIL = !1;
  /** @type {PreTrainedModel.from_pretrained} */
  static async from_pretrained(n, {
    quantized: o = !0,
    progress_callback: u = null,
    config: l = null,
    cache_dir: h = null,
    local_files_only: a = !1,
    revision: f = "main",
    model_file_name: g = null
  } = {}) {
    let c = {
      quantized: o,
      progress_callback: u,
      config: l,
      cache_dir: h,
      local_files_only: a,
      revision: f,
      model_file_name: g
    };
    if (l = await AutoConfig.from_pretrained(n, c), c.config || (c.config = l), !this.MODEL_CLASS_MAPPINGS)
      throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name);
    for (let s of this.MODEL_CLASS_MAPPINGS) {
      const t = s.get(l.model_type);
      if (t)
        return await t[1].from_pretrained(n, c);
    }
    if (this.BASE_IF_FAIL)
      return console.warn(`Unknown model class "${l.model_type}", attempting to construct from base class.`), await PreTrainedModel.from_pretrained(n, c);
    throw Error(`Unsupported model type: ${l.model_type}`);
  }
}
const MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ new Map([
  ["bert", ["BertModel", BertModel]],
  ["nomic_bert", ["NomicBertModel", NomicBertModel]],
  ["roformer", ["RoFormerModel", RoFormerModel]],
  ["electra", ["ElectraModel", ElectraModel]],
  ["esm", ["EsmModel", EsmModel]],
  ["convbert", ["ConvBertModel", ConvBertModel]],
  ["camembert", ["CamembertModel", CamembertModel]],
  ["deberta", ["DebertaModel", DebertaModel]],
  ["deberta-v2", ["DebertaV2Model", DebertaV2Model]],
  ["mpnet", ["MPNetModel", MPNetModel]],
  ["albert", ["AlbertModel", AlbertModel]],
  ["distilbert", ["DistilBertModel", DistilBertModel]],
  ["roberta", ["RobertaModel", RobertaModel]],
  ["xlm", ["XLMModel", XLMModel]],
  ["xlm-roberta", ["XLMRobertaModel", XLMRobertaModel]],
  ["clap", ["ClapModel", ClapModel]],
  ["clip", ["CLIPModel", CLIPModel]],
  ["clipseg", ["CLIPSegModel", CLIPSegModel]],
  ["chinese_clip", ["ChineseCLIPModel", ChineseCLIPModel]],
  ["siglip", ["SiglipModel", SiglipModel]],
  ["mobilebert", ["MobileBertModel", MobileBertModel]],
  ["squeezebert", ["SqueezeBertModel", SqueezeBertModel]],
  ["wav2vec2", ["Wav2Vec2Model", Wav2Vec2Model]],
  ["wav2vec2-bert", ["Wav2Vec2BertModel", Wav2Vec2BertModel]],
  ["unispeech", ["UniSpeechModel", UniSpeechModel]],
  ["unispeech-sat", ["UniSpeechSatModel", UniSpeechSatModel]],
  ["hubert", ["HubertModel", HubertModel]],
  ["wavlm", ["WavLMModel", WavLMModel]],
  ["audio-spectrogram-transformer", ["ASTModel", ASTModel]],
  ["vits", ["VitsModel", VitsModel]],
  ["detr", ["DetrModel", DetrModel]],
  ["table-transformer", ["TableTransformerModel", TableTransformerModel]],
  ["vit", ["ViTModel", ViTModel]],
  ["fastvit", ["FastViTModel", FastViTModel]],
  ["mobilevit", ["MobileViTModel", MobileViTModel]],
  ["mobilevitv2", ["MobileViTV2Model", MobileViTV2Model]],
  ["owlvit", ["OwlViTModel", OwlViTModel]],
  ["owlv2", ["Owlv2Model", Owlv2Model]],
  ["beit", ["BeitModel", BeitModel]],
  ["deit", ["DeiTModel", DeiTModel]],
  ["convnext", ["ConvNextModel", ConvNextModel]],
  ["convnextv2", ["ConvNextV2Model", ConvNextV2Model]],
  ["dinov2", ["Dinov2Model", Dinov2Model]],
  ["resnet", ["ResNetModel", ResNetModel]],
  ["swin", ["SwinModel", SwinModel]],
  ["swin2sr", ["Swin2SRModel", Swin2SRModel]],
  ["donut-swin", ["DonutSwinModel", DonutSwinModel]],
  ["yolos", ["YolosModel", YolosModel]],
  ["dpt", ["DPTModel", DPTModel]],
  ["glpn", ["GLPNModel", GLPNModel]],
  ["hifigan", ["SpeechT5HifiGan", SpeechT5HifiGan]],
  ["efficientnet", ["EfficientNetModel", EfficientNetModel]]
]), MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ new Map([
  ["t5", ["T5Model", T5Model]],
  ["longt5", ["LongT5Model", LongT5Model]],
  ["mt5", ["MT5Model", MT5Model]],
  ["bart", ["BartModel", BartModel]],
  ["mbart", ["MBartModel", MBartModel]],
  ["marian", ["MarianModel", MarianModel]],
  ["whisper", ["WhisperModel", WhisperModel]],
  ["m2m_100", ["M2M100Model", M2M100Model]],
  ["blenderbot", ["BlenderbotModel", BlenderbotModel]],
  ["blenderbot-small", ["BlenderbotSmallModel", BlenderbotSmallModel]]
]), MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ new Map([
  ["bloom", ["BloomModel", BloomModel]],
  ["gpt2", ["GPT2Model", GPT2Model]],
  ["gptj", ["GPTJModel", GPTJModel]],
  ["gpt_bigcode", ["GPTBigCodeModel", GPTBigCodeModel]],
  ["gpt_neo", ["GPTNeoModel", GPTNeoModel]],
  ["gpt_neox", ["GPTNeoXModel", GPTNeoXModel]],
  ["codegen", ["CodeGenModel", CodeGenModel]],
  ["llama", ["LlamaModel", LlamaModel]],
  ["qwen2", ["Qwen2Model", Qwen2Model]],
  ["phi", ["PhiModel", PhiModel]],
  ["mpt", ["MptModel", MptModel]],
  ["opt", ["OPTModel", OPTModel]],
  ["mistral", ["MistralModel", MistralModel]],
  ["starcoder2", ["Starcoder2Model", Starcoder2Model]],
  ["falcon", ["FalconModel", FalconModel]]
]), MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["speecht5", ["SpeechT5ForSpeechToText", SpeechT5ForSpeechToText]],
  ["whisper", ["WhisperForConditionalGeneration", WhisperForConditionalGeneration]]
]), MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["speecht5", ["SpeechT5ForTextToSpeech", SpeechT5ForTextToSpeech]]
]), MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["vits", ["VitsModel", VitsModel]]
]), MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["bert", ["BertForSequenceClassification", BertForSequenceClassification]],
  ["roformer", ["RoFormerForSequenceClassification", RoFormerForSequenceClassification]],
  ["electra", ["ElectraForSequenceClassification", ElectraForSequenceClassification]],
  ["esm", ["EsmForSequenceClassification", EsmForSequenceClassification]],
  ["convbert", ["ConvBertForSequenceClassification", ConvBertForSequenceClassification]],
  ["camembert", ["CamembertForSequenceClassification", CamembertForSequenceClassification]],
  ["deberta", ["DebertaForSequenceClassification", DebertaForSequenceClassification]],
  ["deberta-v2", ["DebertaV2ForSequenceClassification", DebertaV2ForSequenceClassification]],
  ["mpnet", ["MPNetForSequenceClassification", MPNetForSequenceClassification]],
  ["albert", ["AlbertForSequenceClassification", AlbertForSequenceClassification]],
  ["distilbert", ["DistilBertForSequenceClassification", DistilBertForSequenceClassification]],
  ["roberta", ["RobertaForSequenceClassification", RobertaForSequenceClassification]],
  ["xlm", ["XLMForSequenceClassification", XLMForSequenceClassification]],
  ["xlm-roberta", ["XLMRobertaForSequenceClassification", XLMRobertaForSequenceClassification]],
  ["bart", ["BartForSequenceClassification", BartForSequenceClassification]],
  ["mbart", ["MBartForSequenceClassification", MBartForSequenceClassification]],
  ["mobilebert", ["MobileBertForSequenceClassification", MobileBertForSequenceClassification]],
  ["squeezebert", ["SqueezeBertForSequenceClassification", SqueezeBertForSequenceClassification]]
]), MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["bert", ["BertForTokenClassification", BertForTokenClassification]],
  ["roformer", ["RoFormerForTokenClassification", RoFormerForTokenClassification]],
  ["electra", ["ElectraForTokenClassification", ElectraForTokenClassification]],
  ["esm", ["EsmForTokenClassification", EsmForTokenClassification]],
  ["convbert", ["ConvBertForTokenClassification", ConvBertForTokenClassification]],
  ["camembert", ["CamembertForTokenClassification", CamembertForTokenClassification]],
  ["deberta", ["DebertaForTokenClassification", DebertaForTokenClassification]],
  ["deberta-v2", ["DebertaV2ForTokenClassification", DebertaV2ForTokenClassification]],
  ["mpnet", ["MPNetForTokenClassification", MPNetForTokenClassification]],
  ["distilbert", ["DistilBertForTokenClassification", DistilBertForTokenClassification]],
  ["roberta", ["RobertaForTokenClassification", RobertaForTokenClassification]],
  ["xlm", ["XLMForTokenClassification", XLMForTokenClassification]],
  ["xlm-roberta", ["XLMRobertaForTokenClassification", XLMRobertaForTokenClassification]]
]), MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["t5", ["T5ForConditionalGeneration", T5ForConditionalGeneration]],
  ["longt5", ["LongT5ForConditionalGeneration", LongT5ForConditionalGeneration]],
  ["mt5", ["MT5ForConditionalGeneration", MT5ForConditionalGeneration]],
  ["bart", ["BartForConditionalGeneration", BartForConditionalGeneration]],
  ["mbart", ["MBartForConditionalGeneration", MBartForConditionalGeneration]],
  ["marian", ["MarianMTModel", MarianMTModel]],
  ["m2m_100", ["M2M100ForConditionalGeneration", M2M100ForConditionalGeneration]],
  ["blenderbot", ["BlenderbotForConditionalGeneration", BlenderbotForConditionalGeneration]],
  ["blenderbot-small", ["BlenderbotSmallForConditionalGeneration", BlenderbotSmallForConditionalGeneration]]
]), MODEL_WITH_LM_HEAD_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["bloom", ["BloomForCausalLM", BloomForCausalLM]],
  ["gpt2", ["GPT2LMHeadModel", GPT2LMHeadModel]],
  ["gptj", ["GPTJForCausalLM", GPTJForCausalLM]],
  ["gpt_bigcode", ["GPTBigCodeForCausalLM", GPTBigCodeForCausalLM]],
  ["gpt_neo", ["GPTNeoForCausalLM", GPTNeoForCausalLM]],
  ["gpt_neox", ["GPTNeoXForCausalLM", GPTNeoXForCausalLM]],
  ["codegen", ["CodeGenForCausalLM", CodeGenForCausalLM]],
  ["llama", ["LlamaForCausalLM", LlamaForCausalLM]],
  ["qwen2", ["Qwen2ForCausalLM", Qwen2ForCausalLM]],
  ["phi", ["PhiForCausalLM", PhiForCausalLM]],
  ["mpt", ["MptForCausalLM", MptForCausalLM]],
  ["opt", ["OPTForCausalLM", OPTForCausalLM]],
  ["mbart", ["MBartForCausalLM", MBartForCausalLM]],
  ["mistral", ["MistralForCausalLM", MistralForCausalLM]],
  ["starcoder2", ["Starcoder2ForCausalLM", Starcoder2ForCausalLM]],
  ["falcon", ["FalconForCausalLM", FalconForCausalLM]],
  ["trocr", ["TrOCRForCausalLM", TrOCRForCausalLM]],
  ["stablelm", ["StableLmForCausalLM", StableLmForCausalLM]]
]), MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["bert", ["BertForMaskedLM", BertForMaskedLM]],
  ["roformer", ["RoFormerForMaskedLM", RoFormerForMaskedLM]],
  ["electra", ["ElectraForMaskedLM", ElectraForMaskedLM]],
  ["esm", ["EsmForMaskedLM", EsmForMaskedLM]],
  ["convbert", ["ConvBertForMaskedLM", ConvBertForMaskedLM]],
  ["camembert", ["CamembertForMaskedLM", CamembertForMaskedLM]],
  ["deberta", ["DebertaForMaskedLM", DebertaForMaskedLM]],
  ["deberta-v2", ["DebertaV2ForMaskedLM", DebertaV2ForMaskedLM]],
  ["mpnet", ["MPNetForMaskedLM", MPNetForMaskedLM]],
  ["albert", ["AlbertForMaskedLM", AlbertForMaskedLM]],
  ["distilbert", ["DistilBertForMaskedLM", DistilBertForMaskedLM]],
  ["roberta", ["RobertaForMaskedLM", RobertaForMaskedLM]],
  ["xlm", ["XLMWithLMHeadModel", XLMWithLMHeadModel]],
  ["xlm-roberta", ["XLMRobertaForMaskedLM", XLMRobertaForMaskedLM]],
  ["mobilebert", ["MobileBertForMaskedLM", MobileBertForMaskedLM]],
  ["squeezebert", ["SqueezeBertForMaskedLM", SqueezeBertForMaskedLM]]
]), MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["bert", ["BertForQuestionAnswering", BertForQuestionAnswering]],
  ["roformer", ["RoFormerForQuestionAnswering", RoFormerForQuestionAnswering]],
  ["electra", ["ElectraForQuestionAnswering", ElectraForQuestionAnswering]],
  ["convbert", ["ConvBertForQuestionAnswering", ConvBertForQuestionAnswering]],
  ["camembert", ["CamembertForQuestionAnswering", CamembertForQuestionAnswering]],
  ["deberta", ["DebertaForQuestionAnswering", DebertaForQuestionAnswering]],
  ["deberta-v2", ["DebertaV2ForQuestionAnswering", DebertaV2ForQuestionAnswering]],
  ["mpnet", ["MPNetForQuestionAnswering", MPNetForQuestionAnswering]],
  ["albert", ["AlbertForQuestionAnswering", AlbertForQuestionAnswering]],
  ["distilbert", ["DistilBertForQuestionAnswering", DistilBertForQuestionAnswering]],
  ["roberta", ["RobertaForQuestionAnswering", RobertaForQuestionAnswering]],
  ["xlm", ["XLMForQuestionAnswering", XLMForQuestionAnswering]],
  ["xlm-roberta", ["XLMRobertaForQuestionAnswering", XLMRobertaForQuestionAnswering]],
  ["mobilebert", ["MobileBertForQuestionAnswering", MobileBertForQuestionAnswering]],
  ["squeezebert", ["SqueezeBertForQuestionAnswering", SqueezeBertForQuestionAnswering]]
]), MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]]
]), MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["vit", ["ViTForImageClassification", ViTForImageClassification]],
  ["fastvit", ["FastViTForImageClassification", FastViTForImageClassification]],
  ["mobilevit", ["MobileViTForImageClassification", MobileViTForImageClassification]],
  ["mobilevitv2", ["MobileViTV2ForImageClassification", MobileViTV2ForImageClassification]],
  ["beit", ["BeitForImageClassification", BeitForImageClassification]],
  ["deit", ["DeiTForImageClassification", DeiTForImageClassification]],
  ["convnext", ["ConvNextForImageClassification", ConvNextForImageClassification]],
  ["convnextv2", ["ConvNextV2ForImageClassification", ConvNextV2ForImageClassification]],
  ["dinov2", ["Dinov2ForImageClassification", Dinov2ForImageClassification]],
  ["resnet", ["ResNetForImageClassification", ResNetForImageClassification]],
  ["swin", ["SwinForImageClassification", SwinForImageClassification]],
  ["segformer", ["SegformerForImageClassification", SegformerForImageClassification]],
  ["efficientnet", ["EfficientNetForImageClassification", EfficientNetForImageClassification]]
]), MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["detr", ["DetrForObjectDetection", DetrForObjectDetection]],
  ["table-transformer", ["TableTransformerForObjectDetection", TableTransformerForObjectDetection]],
  ["yolos", ["YolosForObjectDetection", YolosForObjectDetection]]
]), MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["owlvit", ["OwlViTForObjectDetection", OwlViTForObjectDetection]],
  ["owlv2", ["Owlv2ForObjectDetection", Owlv2ForObjectDetection]]
]), MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["detr", ["DetrForSegmentation", DetrForSegmentation]],
  ["clipseg", ["CLIPSegForImageSegmentation", CLIPSegForImageSegmentation]]
]), MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["segformer", ["SegformerForSemanticSegmentation", SegformerForSemanticSegmentation]]
]), MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["sam", ["SamModel", SamModel]]
]), MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["wav2vec2", ["Wav2Vec2ForCTC", Wav2Vec2ForCTC]],
  ["wav2vec2-bert", ["Wav2Vec2BertForCTC", Wav2Vec2BertForCTC]],
  ["unispeech", ["UniSpeechForCTC", UniSpeechForCTC]],
  ["unispeech-sat", ["UniSpeechSatForCTC", UniSpeechSatForCTC]],
  ["wavlm", ["WavLMForCTC", WavLMForCTC]],
  ["hubert", ["HubertForCTC", HubertForCTC]]
]), MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["wav2vec2", ["Wav2Vec2ForSequenceClassification", Wav2Vec2ForSequenceClassification]],
  ["wav2vec2-bert", ["Wav2Vec2BertForSequenceClassification", Wav2Vec2BertForSequenceClassification]],
  ["unispeech", ["UniSpeechForSequenceClassification", UniSpeechForSequenceClassification]],
  ["unispeech-sat", ["UniSpeechSatForSequenceClassification", UniSpeechSatForSequenceClassification]],
  ["wavlm", ["WavLMForSequenceClassification", WavLMForSequenceClassification]],
  ["hubert", ["HubertForSequenceClassification", HubertForSequenceClassification]],
  ["audio-spectrogram-transformer", ["ASTForAudioClassification", ASTForAudioClassification]]
]), MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["wavlm", ["WavLMForXVector", WavLMForXVector]]
]), MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["unispeech-sat", ["UniSpeechSatForAudioFrameClassification", UniSpeechSatForAudioFrameClassification]],
  ["wavlm", ["WavLMForAudioFrameClassification", WavLMForAudioFrameClassification]],
  ["wav2vec2", ["Wav2Vec2ForAudioFrameClassification", Wav2Vec2ForAudioFrameClassification]]
]), MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["vitmatte", ["VitMatteForImageMatting", VitMatteForImageMatting]]
]), MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["swin2sr", ["Swin2SRForImageSuperResolution", Swin2SRForImageSuperResolution]]
]), MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["dpt", ["DPTForDepthEstimation", DPTForDepthEstimation]],
  ["depth_anything", ["DepthAnythingForDepthEstimation", DepthAnythingForDepthEstimation]],
  ["glpn", ["GLPNForDepthEstimation", GLPNForDepthEstimation]]
]), MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
  ["clip", ["CLIPVisionModelWithProjection", CLIPVisionModelWithProjection]],
  ["siglip", ["SiglipVisionModel", SiglipVisionModel]]
]), MODEL_CLASS_TYPE_MAPPING = [
  [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],
  [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],
  [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],
  [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
  [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
  [MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],
  [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],
  [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],
  [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
  [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
  // Custom:
  [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly]
];
for (const [d, n] of MODEL_CLASS_TYPE_MAPPING)
  for (const [o, u] of d.values())
    MODEL_TYPE_MAPPING.set(o, n), MODEL_CLASS_TO_NAME_MAPPING.set(u, o), MODEL_NAME_TO_CLASS_MAPPING.set(o, u);
const CUSTOM_MAPPING = [
  ["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],
  ["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly],
  ["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],
  ["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly]
];
for (const [d, n, o] of CUSTOM_MAPPING)
  MODEL_TYPE_MAPPING.set(d, o), MODEL_CLASS_TO_NAME_MAPPING.set(n, d), MODEL_NAME_TO_CLASS_MAPPING.set(d, n);
class AutoModel extends PretrainedMixin {
  /** @type {Map<string, Object>[]} */
  // @ts-ignore
  static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map((n) => n[0]);
  static BASE_IF_FAIL = !0;
}
class AutoModelForTokenClassification extends PretrainedMixin {
  static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES];
}
class Seq2SeqLMOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits The output logits of the model.
   * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.
   * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.
   * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
   * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
   */
  constructor({ logits: n, past_key_values: o, encoder_outputs: u, decoder_attentions: l = null, cross_attentions: h = null }) {
    super(), this.logits = n, this.past_key_values = o, this.encoder_outputs = u, this.decoder_attentions = l, this.cross_attentions = h;
  }
}
class SequenceClassifierOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).
   */
  constructor({ logits: n }) {
    super(), this.logits = n;
  }
}
class XVectorOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.
   * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.
   */
  constructor({ logits: n, embeddings: o }) {
    super(), this.logits = n, this.embeddings = o;
  }
}
class TokenClassifierOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits Classification scores (before SoftMax).
   */
  constructor({ logits: n }) {
    super(), this.logits = n;
  }
}
class MaskedLMOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
   */
  constructor({ logits: n }) {
    super(), this.logits = n;
  }
}
class QuestionAnsweringModelOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.start_logits Span-start scores (before SoftMax).
   * @param {Tensor} output.end_logits Span-end scores (before SoftMax).
   */
  constructor({ start_logits: n, end_logits: o }) {
    super(), this.start_logits = n, this.end_logits = o;
  }
}
class CausalLMOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
   */
  constructor({ logits: n }) {
    super(), this.logits = n;
  }
}
class ImageMattingOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.
   */
  constructor({ alphas: n }) {
    super(), this.alphas = n;
  }
}
class VitsModelOutput extends ModelOutput {
  /**
   * @param {Object} output The output of the model.
   * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.
   * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.
   * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.
   */
  constructor({ waveform: n, spectrogram: o }) {
    super(), this.waveform = n, this.spectrogram = o;
  }
}
const BROWSER_ENV = typeof self < "u";
if (!BROWSER_ENV) {
  if (!sharp) throw new Error("Unable to load image processing library.");
}
let MODELS_BASE = "";
function initEnv({ wasmBase: d = "/wasm/", modelsBase: n = "", threads: o, simd: u, customCache: l } = {}) {
  if (env$1.allowLocalModels = !0, env$1.useBrowserCache = !0, env$1.backends.onnx.wasm.wasmPaths = d, MODELS_BASE = n || "", MODELS_BASE) {
    const h = MODELS_BASE.endsWith("/") ? MODELS_BASE.slice(0, -1) : MODELS_BASE;
    /^https?:\/\//i.test(h) ? (env$1.allowRemoteModels = !0, env$1.allowLocalModels = !1, env$1.remoteHost = h + "/", env$1.remotePathTemplate = "{model}/", console.debug("[aifw-js] using remote models base:", h)) : env$1.localModelPath = h;
  }
  l && (env$1.useCustomCache = !0, env$1.customCache = {
    async match(h) {
      return (await caches.open(typeof l == "string" ? l : l.name || "oneaifw-assets")).match(h);
    },
    async put(h, a) {
      return (await caches.open(typeof l == "string" ? l : l.name || "oneaifw-assets")).put(h, a);
    }
  }), typeof o == "number" && o > 0 && (env$1.backends.onnx.wasm.numThreads = o), typeof u == "boolean" && (env$1.backends.onnx.wasm.simd = u);
}
const SUPPORTED = /* @__PURE__ */ new Set([
  "Xenova/distilbert-base-cased-finetuned-conll03-english",
  "gagan3012/bert-tiny-finetuned-ner",
  "dslim/distilbert-NER",
  "funstory-ai/neurobert-mini",
  "boltuix/NeuroBERT-Mini",
  "hfl/minirbt-h256",
  "dmis-lab/TinyPubMedBERT-v1.0",
  "boltuix/NeuroBERT-Small",
  "ckiplab/bert-tiny-chinese-ner"
]), PREFER_BERT_FAST = /* @__PURE__ */ new Set([
  "ckiplab/bert-tiny-chinese-ner"
]);
function localDirFor(d) {
  return `${d}`;
}
class TokenClassificationPipeline {
  constructor({ model: n, tokenizer: o = null, processor: u = null }) {
    this.model = n, this.tokenizer = o, this.processor = u;
  }
  async run(n, { ignore_labels: o = ["O"], offsetText: u, tokenTransform: l } = {}) {
    const h = this.tokenizer([n], { padding: !0, truncation: !0, add_special_tokens: !0 }), a = h.input_ids[0], f = a.dims[0];
    let g = [];
    const c = new Array(f).fill(-1);
    for (let y = 0; y < f; y++) {
      const w = a[y].item(), T = this.tokenizer.decode([w], { skip_special_tokens: !0 });
      if (T) {
        const S = g.length;
        c[y] = S, g.push(T.startsWith("##") ? T.slice(2) : T);
      }
    }
    if (typeof l == "function") {
      const y = new Array(g.length);
      for (let w = 0; w < g.length; w++) y[w] = l(g[w]) || g[w];
      g = y;
    }
    const t = computeOffsetsFromTokens(typeof u == "string" ? u : n, g), r = (await this.model(h)).logits, p = (r.dims || [])[2] || 0, m = r.data, _ = this.model.config.id2label, b = [];
    for (let y = 0; y < f && !(!p || !m); y++) {
      const w = y * p;
      if (w + p > m.length) break;
      let T = 0, S = -1 / 0;
      for (let B = 0; B < p; B++) {
        const F = m[w + B];
        F > S && (S = F, T = B);
      }
      let E = 0;
      for (let B = 0; B < p; B++) E += Math.exp(m[w + B] - S);
      const O = E > 0 ? Math.exp(m[w + T] - S) / E : 0, v = _ ? _[T] : `LABEL_${T}`;
      if (o.includes(v)) continue;
      const A = c[y];
      if (A < 0) continue;
      const L = g[A] || "", j = t[A] || [null, null];
      b.push({ entity: v, score: O, index: y, word: L, start: j[0], end: j[1] });
    }
    return mergeSubwordItems(b);
  }
}
async function buildNerPipeline(d, { quantized: n = !0, preferWebGPU: o = !0 } = {}) {
  if (!SUPPORTED.has(d)) throw new Error(`Unsupported model: ${d}`);
  const l = `${localDirFor(d)}`, a = await (PREFER_BERT_FAST.has(d), AutoTokenizer).from_pretrained(l), f = [];
  o && typeof navigator < "u" && "gpu" in navigator && f.push("webgpu"), f.push("wasm");
  const g = await AutoModelForTokenClassification.from_pretrained(l, { quantized: !!n, device: f });
  return new TokenClassificationPipeline({ model: g, tokenizer: a });
}
function computeOffsetsFromTokens(d, n) {
  const o = new Array(n.length), u = d.toLowerCase(), l = buildStrippedMap(u), h = l.stripped, a = l.map;
  let f = 0, g = 0;
  for (let c = 0; c < n.length; c++) {
    const s = String(n[c] ?? ""), t = s.startsWith("##") ? s.slice(2) : s;
    if (!t) {
      o[c] = [f, f];
      continue;
    }
    const e = t.toLowerCase();
    let r = u.indexOf(e, f);
    if (r === -1 && (r = u.indexOf(e)), r !== -1) {
      const p = r, m = r + t.length;
      o[c] = [p, m], f = m, g = findStrippedIndexAtOrAfter(a, m);
      continue;
    }
    const i = stripAccents(e);
    if (i) {
      let p = h.indexOf(i, g);
      if (p === -1 && (p = h.indexOf(i)), p !== -1) {
        const m = a[p] ?? 0, _ = p + i.length, b = _ < a.length ? a[_] : d.length;
        o[c] = [m, b], f = b, g = _;
        continue;
      }
    }
    o[c] = [f, f];
  }
  return o;
}
function mergeSubwordItems(d) {
  if (!Array.isArray(d) || d.length === 0) return d;
  const n = [];
  let o = null, u = 0;
  const l = (h) => h.startsWith("B-") || h.startsWith("I-") || h.startsWith("E-") ? h.slice(2) : h;
  for (const h of d) {
    if (!o) {
      o = { ...h }, u = 1;
      continue;
    }
    const a = l(o.entity) === l(h.entity), f = o.end === h.start;
    a && f ? (o.word = o.word + h.word, o.end = h.end, o.score = (o.score * u + h.score) / (u + 1), u += 1) : (n.push(o), o = { ...h }, u = 1);
  }
  return o && n.push(o), n;
}
function stripAccents(d) {
  try {
    return d.normalize("NFD").replace(new RegExp("\\p{M}+", "gu"), "");
  } catch {
    return d;
  }
}
function buildStrippedMap(d) {
  const n = [], o = [];
  let u = 0;
  for (; u < d.length; ) {
    const l = d.codePointAt(u), h = String.fromCodePoint(l), a = h.normalize("NFD");
    for (let f = 0; f < a.length; f++) {
      const g = a[f];
      new RegExp("\\p{M}", "u").test(g) || isConnectorPunct(g) || (n.push(g), o.push(u));
    }
    u += h.length;
  }
  return { stripped: n.join(""), map: o };
}
function isConnectorPunct(d) {
  return /[-'`\u2010-\u2015\u2212\u00B7\u30FB\u2043\u2219]/u.test(d);
}
function findStrippedIndexAtOrAfter(d, n) {
  let o = 0, u = d.length;
  for (; o < u; ) {
    const l = o + u >>> 1;
    d[l] < n ? o = l + 1 : u = l;
  }
  return o;
}
function buildNerEntitiesBuffer(d, n, o) {
  if (!n?.length) return { ptr: 0, count: 0, owned: [], byteSize: 0 };
  const u = 20, l = n.length >>> 0, h = u * l, a = d.aifw_malloc(h);
  if (!a) throw new Error("aifw_malloc ner entities failed");
  const f = new DataView(d.memory.buffer), g = typeof o == "string", c = g ? o.length : Number(o || 0), s = g ? computeUtf8OffsetMap(o) : null, t = {
    None: 0,
    PHYSICAL_ADDRESS: 1,
    ORGANIZATION: 3,
    USER_MAME: 4
  }, e = { None: 0, Begin: 1, Inside: 2 }, r = (p) => {
    const m = String(p || "");
    return m.startsWith("B-") ? [m.slice(2), e.Begin] : m.startsWith("S-") ? [m.slice(2), e.Begin] : m.startsWith("I-") ? [m.slice(2), e.Inside] : m.startsWith("E-") ? [m.slice(2), e.Inside] : m ? [m, e.None] : ["MISC", e.None];
  }, i = (p) => {
    switch (p) {
      case "PER":
      case "PERSON":
        return t.USER_MAME;
      case "ORG":
        return t.ORGANIZATION;
      case "LOC":
      case "GPE":
      case "FAC":
      case "ADDRESS":
        return t.PHYSICAL_ADDRESS;
      case "MISC":
        return t.None;
      default:
        return t.None;
    }
  };
  for (let p = 0; p < l; p++) {
    const m = n[p];
    let _ = Math.max(0, Math.min(c, Number(m.start || 0))), b = Math.max(_, Math.min(c, Number(m.end || 0)));
    if (s) {
      const E = s[_] ?? 0, O = s[b] ?? s[c] ?? E;
      _ = E, b = Math.max(E, O);
    }
    const y = a + p * u, [w, T] = r(m.entity), S = i(w);
    f.setUint8(y + 0, S), f.setUint8(y + 1, T), f.setFloat32(y + 4, Number(m.score || 0), !0), f.setUint32(y + 8, Number(m.index || 0) >>> 0, !0), f.setUint32(y + 12, _ >>> 0, !0), f.setUint32(y + 16, b >>> 0, !0);
  }
  return { ptr: a, count: l, owned: [], byteSize: h };
}
function computeUtf8OffsetMap(d) {
  const n = new Array(d.length + 1);
  let o = 0, u = 0;
  for (; u < d.length; ) {
    n[u] = o;
    const l = d.codePointAt(u), h = l > 65535 ? 2 : 1;
    let a = 0;
    l <= 127 ? a = 1 : l <= 2047 ? a = 2 : l <= 65535 ? a = 3 : a = 4, o += a, u += h;
  }
  return n[d.length] = o, n;
}
export {
  SUPPORTED,
  TokenClassificationPipeline,
  buildNerEntitiesBuffer,
  buildNerPipeline,
  computeOffsetsFromTokens,
  initEnv,
  mergeSubwordItems
};
