|
var r=n(4699),s=n(9087),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function o(e){if(e>2147483647)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,a.prototype),t}function a(e,t,n){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return c(e)}return l(e,t,n)}function l(e,t,n){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!a.isEncoding(t))throw TypeError("Unknown encoding: "+t);var n=0|p(e,t),r=o(n),s=r.write(e,t);return s!==n&&(r=r.slice(0,s)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(C(e,Uint8Array)){var t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(C(e,ArrayBuffer)||e&&C(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(C(e,SharedArrayBuffer)||e&&C(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return a.from(r,t,n);var s=function(e){if(a.isBuffer(e)){var t,n=0|f(e.length),r=o(n);return 0===r.length||e.copy(r,0,0,n),r}return void 0!==e.length?"number"!=typeof e.length||(t=e.length)!=t?o(0):u(e):"Buffer"===e.type&&Array.isArray(e.data)?u(e.data):void 0}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return a.from(e[Symbol.toPrimitive]("string"),t,n);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function c(e){return h(e),o(e<0?0:0|f(e))}function u(e){for(var t=e.length<0?0:0|f(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e,t,n){var r;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),a.prototype),r}function f(e){if(e>=2147483647)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function p(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||C(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return M(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return T(e).length;default:if(s)return r?-1:M(e).length;t=(""+t).toLowerCase(),s=!0}}function _(e,t,n){var s,i,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===n||n>this.length)&&(n=this.length),n<=0||(n>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var s="",i=t;i<n;++i)s+=S[e[i]];return s}(this,t,n);case"utf8":case"utf-8":return w(this,t,n);case"ascii":return function(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}(this,t,n);case"latin1":case"binary":return function(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(e[s]);return r}(this,t,n);case"base64":return s=t,i=n,0===s&&i===this.length?r.fromByteArray(this):r.fromByteArray(this.slice(s,i));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,n){for(var r=e.slice(t,n),s="",i=0;i<r.length-1;i+=2)s+=String.fromCharCode(r[i]+256*r[i+1]);return s}(this,t,n);default:if(o)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,s){var i;if(0===e.length)return -1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),(i=n=+n)!=i&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return -1;n=e.length-1}else if(n<0){if(!s)return -1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,s);if("number"==typeof t)return(t&=255,"function"==typeof Uint8Array.prototype.indexOf)?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,s);throw TypeError("val must be string, number or Buffer")}function y(e,t,n,r,s){var i,o=1,a=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return -1;o=2,a/=2,l/=2,n/=2}function h(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){var c=-1;for(i=n;i<a;i++)if(h(e,i)===h(t,-1===c?0:i-c)){if(-1===c&&(c=i),i-c+1===l)return c*o}else -1!==c&&(i-=i-c),c=-1}else for(n+l>a&&(n=a-l),i=n;i>=0;i--){for(var u=!0,d=0;d<l;d++)if(h(e,i+d)!==h(t,d)){u=!1;break}if(u)return i}return -1}function w(e,t,n){n=Math.min(e.length,n);for(var r=[],s=t;s<n;){var i,o,a,l,h=e[s],c=null,u=h>239?4:h>223?3:h>191?2:1;if(s+u<=n)switch(u){case 1:h<128&&(c=h);break;case 2:(192&(i=e[s+1]))==128&&(l=(31&h)<<6|63&i)>127&&(c=l);break;case 3:i=e[s+1],o=e[s+2],(192&i)==128&&(192&o)==128&&(l=(15&h)<<12|(63&i)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[s+1],o=e[s+2],a=e[s+3],(192&i)==128&&(192&o)==128&&(192&a)==128&&(l=(15&h)<<18|(63&i)<<12|(63&o)<<6|63&a)>65535&&l<1114112&&(c=l)}null===c?(c=65533,u=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),s+=u}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=4096));return n}(r)}function b(e,t,n){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+t>n)throw RangeError("Trying to access beyond buffer length")}function k(e,t,n,r,s,i){if(!a.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<i)throw RangeError('"value" argument is out of bounds');if(n+r>e.length)throw RangeError("Index out of range")}function v(e,t,n,r,s,i){if(n+r>e.length||n<0)throw RangeError("Index out of range")}function x(e,t,n,r,i){return t=+t,n>>>=0,i||v(e,t,n,4,34028234663852886e22,-34028234663852886e22),s.write(e,t,n,r,23,4),n+4}function E(e,t,n,r,i){return t=+t,n>>>=0,i||v(e,t,n,8,17976931348623157e292,-17976931348623157e292),s.write(e,t,n,r,52,8),n+8}t.lW=a,t.h2=50,a.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),a.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}}),a.poolSize=8192,a.from=function(e,t,n){return l(e,t,n)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array),a.alloc=function(e,t,n){return(h(e),e<=0)?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)},a.allocUnsafe=function(e){return c(e)},a.allocUnsafeSlow=function(e){return c(e)},a.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==a.prototype},a.compare=function(e,t){if(C(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),C(t,Uint8Array)&&(t=a.from(t,t.offset,t.byteLength)),!a.isBuffer(e)||!a.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,i=Math.min(n,r);s<i;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},a.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(e,t){if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);if(void 0===t)for(n=0,t=0;n<e.length;++n)t+=e[n].length;var n,r=a.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var i=e[n];if(C(i,Uint8Array))s+i.length>r.length?a.from(i).copy(r,s):Uint8Array.prototype.set.call(r,i,s);else if(a.isBuffer(i))i.copy(r,s);else throw TypeError('"list" argument must be an Array of Buffers');s+=i.length}return r},a.byteLength=p,a.prototype._isBuffer=!0,a.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},a.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},a.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},a.prototype.toString=function(){var e=this.length;return 0===e?"":0==arguments.length?w(this,0,e):_.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(e){if(!a.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function(){var e="",n=t.h2;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(e,t,n,r,s){if(C(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return -1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,s>>>=0,this===e)return 0;for(var i=s-r,o=n-t,l=Math.min(i,o),h=this.slice(r,s),c=e.slice(t,n),u=0;u<l;++u)if(h[u]!==c[u]){i=h[u],o=c[u];break}return i<o?-1:o<i?1:0},a.prototype.includes=function(e,t,n){return -1!==this.indexOf(e,t,n)},a.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},a.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},a.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s,i,o,a,l,h,c,u,d=this.length-t;if((void 0===n||n>d)&&(n=d),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var f=!1;;)switch(r){case"hex":return function(e,t,n,r){n=Number(n)||0;var s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;var i=t.length;r>i/2&&(r=i/2);for(var o=0;o<r;++o){var a=parseInt(t.substr(2*o,2),16);if(a!=a)break;e[n+o]=a}return o}(this,e,t,n);case"utf8":case"utf-8":return s=t,i=n,B(M(e,this.length-s),this,s,i);case"ascii":case"latin1":case"binary":return o=t,a=n,B(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(e),this,o,a);case"base64":return l=t,h=n,B(T(e),this,l,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return c=t,u=n,B(function(e,t){for(var n,r,s=[],i=0;i<e.length&&!((t-=2)<0);++i)r=(n=e.charCodeAt(i))>>8,s.push(n%256),s.push(r);return s}(e,this.length-c),this,c,u);default:if(f)throw TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),f=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,a.prototype),r},a.prototype.readUintLE=a.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||b(e,t,this.length);for(var r=this[e],s=1,i=0;++i<t&&(s*=256);)r+=this[e+i]*s;return r},a.prototype.readUintBE=a.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||b(e,t,this.length);for(var r=this[e+--t],s=1;t>0&&(s*=256);)r+=this[e+--t]*s;return r},a.prototype.readUint8=a.prototype.readUInt8=function(e,t){return e>>>=0,t||b(e,1,this.length),this[e]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||b(e,t,this.length);for(var r=this[e],s=1,i=0;++i<t&&(s*=256);)r+=this[e+i]*s;return r>=(s*=128)&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||b(e,t,this.length);for(var r=t,s=1,i=this[e+--r];r>0&&(s*=256);)i+=this[e+--r]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*t)),i},a.prototype.readInt8=function(e,t){return(e>>>=0,t||b(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||b(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){e>>>=0,t||b(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return e>>>=0,t||b(e,4,this.length),s.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||b(e,4,this.length),s.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||b(e,8,this.length),s.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||b(e,8,this.length),s.read(this,e,!1,52,8)},a.prototype.writeUintLE=a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){var s=Math.pow(2,8*n)-1;k(this,e,t,n,s,0)}var i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){var s=Math.pow(2,8*n)-1;k(this,e,t,n,s,0)}var i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},a.prototype.writeUint8=a.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);k(this,e,t,n,s-1,-s)}var i=0,o=1,a=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);k(this,e,t,n,s-1,-s)}var i=n-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||k(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return E(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return E(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(!a.isBuffer(e))throw TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n||0===e.length||0===this.length)return 0;if(t<0)throw RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw RangeError("Index out of range");if(r<0)throw RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var s=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),s},a.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw TypeError("encoding must be a string");if("string"==typeof r&&!a.isEncoding(r))throw TypeError("Unknown encoding: "+r);if(1===e.length){var s,i=e.charCodeAt(0);("utf8"===r&&i<128||"latin1"===r)&&(e=i)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError("Out of range index");if(n<=t)return this;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=a.isBuffer(e)?e:a.from(e,r),l=o.length;if(0===l)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%l]}return this};var A=/[^+/0-9A-Za-z-_]/g;function M(e,t){t=t||1/0;for(var n,r=e.length,s=null,i=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!s){if(n>56319||o+1===r){(t-=3)>-1&&i.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),s=n;continue}n=(s-55296<<10|n-56320)+65536}else s&&(t-=3)>-1&&i.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else if(n<1114112){if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}else throw Error("Invalid code point")}return i}function T(e){return r.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(A,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function B(e,t,n,r){for(var s=0;s<r&&!(s+n>=t.length)&&!(s>=e.length);++s)t[s+n]=e[s];return s}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var S=function(){for(var e="0123456789abcdef",t=Array(256),n=0;n<16;++n)for(var r=16*n,s=0;s<16;++s)t[r+s]=e[n]+e[s];return t}()},9087:function(e,t){t.read=function(e,t,n,r,s){var i,o,a=8*s-r-1,l=(1<<a)-1,h=l>>1,c=-7,u=n?s-1:0,d=n?-1:1,f=e[t+u];for(u+=d,i=f&(1<<-c)-1,f>>=-c,c+=a;c>0;i=256*i+e[t+u],u+=d,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=r;c>0;o=256*o+e[t+u],u+=d,c-=8);if(0===i)i=1-h;else{if(i===l)return o?NaN:(f?-1:1)*(1/0);o+=Math.pow(2,r),i-=h}return(f?-1:1)*o*Math.pow(2,i-r)},t.write=function(e,t,n,r,s,i){var o,a,l,h=8*i-s-1,c=(1<<h)-1,u=c>>1,d=23===s?5960464477539062e-23:0,f=r?0:i-1,p=r?1:-1,_=t<0||0===t&&1/t<0?1:0;for(isNaN(t=Math.abs(t))||t===1/0?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?t+=d/l:t+=d*Math.pow(2,1-u),t*l>=2&&(o++,l/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(t*l-1)*Math.pow(2,s),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),o=0));s>=8;e[n+f]=255&a,f+=p,a/=256,s-=8);for(o=o<<s|a,h+=s;h>0;e[n+f]=255&o,f+=p,o/=256,h-=8);e[n+f-p]|=128*_}},2601:function(e,t,n){"use strict";var r,s;e.exports=(null==(r=n.g.process)?void 0:r.env)&&"object"==typeof(null==(s=n.g.process)?void 0:s.env)?n.g.process:n(8960)},692:function(e,t,n){!function(){var t={452:function(e){"use strict";e.exports=n(9875)}},r={};function s(e){var n=r[e];if(void 0!==n)return n.exports;var i=r[e]={exports:{}},o=!0;try{t[e](i,i.exports,s),o=!1}finally{o&&delete r[e]}return i.exports}s.ab="//";var i={};!function(){var e,t=(e=s(452))&&"object"==typeof e&&"default"in e?e.default:e,n=/https?|ftp|gopher|file/;function r(e){"string"==typeof e&&(e=m(e));var r,s,i,o,a,l,h,c,u,d=(s=(r=e).auth,i=r.hostname,o=r.protocol||"",a=r.pathname||"",l=r.hash||"",h=r.query||"",c=!1,s=s?encodeURIComponent(s).replace(/%3A/i,":")+"@":"",r.host?c=s+r.host:i&&(c=s+(~i.indexOf(":")?"["+i+"]":i),r.port&&(c+=":"+r.port)),h&&"object"==typeof h&&(h=t.encode(h)),u=r.search||h&&"?"+h||"",o&&":"!==o.substr(-1)&&(o+=":"),r.slashes||(!o||n.test(o))&&!1!==c?(c="//"+(c||""),a&&"/"!==a[0]&&(a="/"+a)):c||(c=""),l&&"#"!==l[0]&&(l="#"+l),u&&"?"!==u[0]&&(u="?"+u),{protocol:o,host:c,pathname:a=a.replace(/[?#]/g,encodeURIComponent),search:u=u.replace("#","%23"),hash:l});return""+d.protocol+d.host+d.pathname+d.search+d.hash}var o="http://",a=o+"w.w",l=/^([a-z0-9.+-]*:\/\/\/)([a-z0-9.+-]:\/*)?/i,h=/https?|ftp|gopher|file/;function c(e,t){var n="string"==typeof e?m(e):e;e="object"==typeof e?r(e):e;var s=m(t),i="";n.protocol&&!n.slashes&&(i=n.protocol,e=e.replace(n.protocol,""),i+="/"===t[0]||"/"===e[0]?"/":""),i&&s.protocol&&(i="",s.slashes||(i=s.protocol,t=t.replace(s.protocol,"")));var c=e.match(l);c&&!s.protocol&&(e=e.substr((i=c[1]+(c[2]||"")).length),/^\/\/[^/]/.test(t)&&(i=i.slice(0,-1)));var u=new URL(e,a+"/"),d=new URL(t,u).toString().replace(a,""),f=s.protocol||n.protocol;return f+=n.slashes||s.slashes?"//":"",!i&&f?d=d.replace(o,f):i&&(d=d.replace(o,"")),h.test(d)||~t.indexOf(".")||"/"===e.slice(-1)||"/"===t.slice(-1)||"/"!==d.slice(-1)||(d=d.slice(0,-1)),i&&(d=i+("/"===d[0]?d.substr(1):d)),d}function u(){}u.prototype.parse=m,u.prototype.format=r,u.prototype.resolve=c,u.prototype.resolveObject=c;var d=/^https?|ftp|gopher|file/,f=/^(.*?)([#?].*)/,p=/^([a-z0-9.+-]*:)(\/{0,3})(.*)/i,_=/^([a-z0-9.+-]*:)?\/\/\/*/i,g=/^([a-z0-9.+-]*:)(\/{0,2})\[(.*)\]$/i;function m(e,n,s){if(void 0===n&&(n=!1),void 0===s&&(s=!1),e&&"object"==typeof e&&e instanceof u)return e;var i=(e=e.trim()).match(f);e=i?i[1].replace(/\\/g,"/")+i[2]:e.replace(/\\/g,"/"),g.test(e)&&"/"!==e.slice(-1)&&(e+="/");var o=!/(^javascript)/.test(e)&&e.match(p),l=_.test(e),h="";o&&(d.test(o[1])||(h=o[1].toLowerCase(),e=""+o[2]+o[3]),o[2]||(l=!1,d.test(o[1])?(h=o[1],e=""+o[3]):e="//"+o[3]),3!==o[2].length&&1!==o[2].length||(h=o[1],e="/"+o[3]));var c,m=(i?i[1]:e).match(/^https?:\/\/[^/]+(:[0-9]+)(?=\/|$)/),y=m&&m[1],w=new u,b="",k="";try{c=new URL(e)}catch(t){b=t,h||s||!/^\/\//.test(e)||/^\/\/.+[@.]/.test(e)||(k="/",e=e.substr(1));try{c=new URL(e,a)}catch(e){return w.protocol=h,w.href=h,w}}w.slashes=l&&!k,w.host="w.w"===c.host?"":c.host,w.hostname="w.w"===c.hostname?"":c.hostname.replace(/(\[|\])/g,""),w.protocol=b?h||null:c.protocol,w.search=c.search.replace(/\\/g,"%5C"),w.hash=c.hash.replace(/\\/g,"%5C");var v=e.split("#");!w.search&&~v[0].indexOf("?")&&(w.search="?"),w.hash||""!==v[1]||(w.hash="#"),w.query=n?t.decode(c.search.substr(1)):w.search.substr(1),w.pathname=k+(o?c.pathname.replace(/['^|`]/g,function(e){return"%"+e.charCodeAt().toString(16).toUpperCase()}).replace(/((?:%[0-9A-F]{2})+)/g,function(e,t){try{return decodeURIComponent(t).split("").map(function(e){var t=e.charCodeAt();return t>256||/^[a-z0-9]$/i.test(e)?e:"%"+t.toString(16).toUpperCase()}).join("")}catch(e){return t}}):c.pathname),"about:"===w.protocol&&"blank"===w.pathname&&(w.protocol="",w.pathname=""),b&&"/"!==e[0]&&(w.pathname=w.pathname.substr(1)),h&&!d.test(h)&&"/"!==e.slice(-1)&&"/"===w.pathname&&(w.pathname=""),w.path=w.pathname+w.search,w.auth=[c.username,c.password].map(decodeURIComponent).filter(Boolean).join(":"),w.port=c.port,y&&!w.host.endsWith(y)&&(w.host+=y,w.port=y.slice(1)),w.href=k?""+w.pathname+w.search+w.hash:r(w);var x=/^(file)/.test(w.href)?["host","hostname"]:[];return Object.keys(w).forEach(function(e){~x.indexOf(e)||(w[e]=w[e]||null)}),w}i.parse=m,i.format=r,i.resolve=c,i.resolveObject=function(e,t){return m(c(e,t))},i.Url=u}(),e.exports=i}()},8960:function(e){!function(){var t={229:function(e){var t,n,r,s=e.exports={};function i(){throw Error("setTimeout has not been defined")}function o(){throw Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{n="function"==typeof clearTimeout?clearTimeout:o}catch(e){n=o}}();var l=[],h=!1,c=-1;function u(){h&&r&&(h=!1,r.length?l=r.concat(l):c=-1,l.length&&d())}function d(){if(!h){var e=a(u);h=!0;for(var t=l.length;t;){for(r=l,l=[];++c<t;)r&&r[c].run();c=-1,t=l.length}r=null,h=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===o||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function p(){}s.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new f(e,t)),1!==l.length||h||a(d)},f.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=p,s.addListener=p,s.once=p,s.off=p,s.removeListener=p,s.removeAllListeners=p,s.emit=p,s.prependListener=p,s.prependOnceListener=p,s.listeners=function(e){return[]},s.binding=function(e){throw Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw Error("process.chdir is not supported")},s.umask=function(){return 0}}},n={};function r(e){var s=n[e];if(void 0!==s)return s.exports;var i=n[e]={exports:{}},o=!0;try{t[e](i,i.exports,r),o=!1}finally{o&&delete n[e]}return i.exports}r.ab="//";var s=r(229);e.exports=s}()},9875:function(e){!function(){"use strict";var t={815:function(e){e.exports=function(e,n,r,s){n=n||"&",r=r||"=";var i={};if("string"!=typeof e||0===e.length)return i;var o=/\+/g;e=e.split(n);var a=1e3;s&&"number"==typeof s.maxKeys&&(a=s.maxKeys);var l=e.length;a>0&&l>a&&(l=a);for(var h=0;h<l;++h){var c,u,d,f,p=e[h].replace(o,"%20"),_=p.indexOf(r);(_>=0?(c=p.substr(0,_),u=p.substr(_+1)):(c=p,u=""),d=decodeURIComponent(c),f=decodeURIComponent(u),Object.prototype.hasOwnProperty.call(i,d))?t(i[d])?i[d].push(f):i[d]=[i[d],f]:i[d]=f}return i};var t=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},577:function(e){var t=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,i,o,a){return(i=i||"&",o=o||"=",null===e&&(e=void 0),"object"==typeof e)?r(s(e),function(s){var a=encodeURIComponent(t(s))+o;return n(e[s])?r(e[s],function(e){return a+encodeURIComponent(t(e))}).join(i):a+encodeURIComponent(t(e[s]))}).join(i):a?encodeURIComponent(t(a))+o+encodeURIComponent(t(e)):""};var n=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function r(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var s=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}}},n={};function r(e){var s=n[e];if(void 0!==s)return s.exports;var i=n[e]={exports:{}},o=!0;try{t[e](i,i.exports,r),o=!1}finally{o&&delete n[e]}return i.exports}r.ab="//";var s={};s.decode=s.parse=r(815),s.encode=s.stringify=r(577),e.exports=s}()},7731:function(e,t,n){"use strict";n.r(t),n.d(t,{InferenceSession:function(){return g},Tensor:function(){return p},env:function(){return a},registerBackend:function(){return i}});let r={},s=[],i=(e,t,n)=>{if(t&&"function"==typeof t.init&&"function"==typeof t.createSessionHandler){let i=r[e];if(void 0===i)r[e]={backend:t,priority:n};else if(i.priority>n)return;else if(i.priority===n&&i.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`);if(n>=0){let t=s.indexOf(e);-1!==t&&s.splice(t,1);for(let t=0;t<s.length;t++)if(r[s[t]].priority<=n){s.splice(t,0,e);return}s.push(e)}return}throw TypeError("not a valid backend")},o=async e=>{let t=0===e.length?s:e,n=[];for(let e of t){let t=r[e];if(t){if(t.initialized)return t.backend;if(t.aborted)continue;let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init()),await t.initPromise,t.initialized=!0,t.backend}catch(s){r||n.push({name:e,err:s}),t.aborted=!0}finally{delete t.initPromise}}}throw Error(`no available backend found. ERR: ${n.map(e=>`[${e.name}] ${e.err}`).join(", ")}`)},a=new class{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw Error(`Unsupported logging level: ${e}`);this.logLevelInternal=e}}get logLevel(){return this.logLevelInternal}},l="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,h="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from,c=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),u=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);l&&(c.set("int64",BigInt64Array),u.set(BigInt64Array,"int64")),h&&(c.set("uint64",BigUint64Array),u.set(BigUint64Array,"uint64"));let d=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if("number"!=typeof r||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t};class f{constructor(e,t,n){let r,s,i;if("string"==typeof e){if(r=e,i=n,"string"===e){if(!Array.isArray(t))throw TypeError("A string tensor's data must be a string array.");s=t}else{let n=c.get(e);if(void 0===n)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t))s=n.from(t);else if(t instanceof n)s=t;else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(i=t,Array.isArray(e)){if(0===e.length)throw TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)r="string",s=e;else if("boolean"===t)r="bool",s=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else{let t=u.get(e.constructor);if(void 0===t)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,s=e}if(void 0===i)i=[s.length];else if(!Array.isArray(i))throw TypeError("A tensor's dims must be a number array");let o=d(i);if(o!==s.length)throw Error(`Tensor's size(${o}) does not match data length(${s.length}).`);this.dims=i,this.type=r,this.data=s,this.size=o}static bufferToTensor(e,t){let n,r;if(void 0===e)throw Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw Error("Image height and width must be defined");let{height:s,width:i}=t,o=t.norm;n=void 0===o||void 0===o.mean?255:o.mean,r=void 0===o||void 0===o.bias?0:o.bias;let a=void 0!==t.bitmapFormat?t.bitmapFormat:"RGBA",l=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",h=s*i,c=new Float32Array("RGBA"===l?4*h:3*h),u=4,d=0,p=1,_=2,g=3,m=0,y=h,w=2*h,b=-1;"RGB"===a&&(u=3,d=0,p=1,_=2,g=-1),"RGBA"===l?b=3*h:"RBG"===l?(m=0,w=h,y=2*h):"BGR"===l&&(w=0,y=h,m=2*h);for(let t=0;t<h;t++,d+=u,_+=u,p+=u,g+=u)c[m++]=(e[d]+r)/n,c[y++]=(e[p]+r)/n,c[w++]=(e[_]+r)/n,-1!==b&&-1!==g&&(c[b++]=(e[g]+r)/n);let k="RGBA"===l?new f("float32",c,[1,4,s,i]):new f("float32",c,[1,3,s,i]);return k}static async fromImage(e,t){let n;let r="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,s="undefined"!=typeof ImageData&&e instanceof ImageData,i="undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap,o="undefined"!=typeof String&&(e instanceof String||"string"==typeof e),a={};if(r){let r=document.createElement("canvas"),s=r.getContext("2d");if(null!=s){let i=e.naturalHeight,o=e.naturalWidth;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(i=t.resizedHeight,o=t.resizedWidth),void 0!==t){if(a=t,void 0!==t.tensorFormat)throw Error("Image input config format must be RGBA for HTMLImageElement");if(a.tensorFormat="RGBA",void 0!==t.height&&t.height!==i)throw Error("Image input config height doesn't match HTMLImageElement height");if(a.height=i,void 0!==t.width&&t.width!==o)throw Error("Image input config width doesn't match HTMLImageElement width");a.width=o}else a.tensorFormat="RGBA",a.height=i,a.width=o;r.width=o,r.height=i,s.drawImage(e,0,0,o,i),n=s.getImageData(0,0,o,i).data}else throw Error("Can not access image data")}else if(s){let r,s;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,s=t.resizedWidth):(r=e.height,s=e.width),void 0!==t){if(a=t,void 0!==t.bitmapFormat&&"RGBA"!==t.bitmapFormat)throw Error("Image input config format must be RGBA for ImageData");a.bitmapFormat="RGBA"}else a.bitmapFormat="RGBA";if(a.height=r,a.width=s,void 0!==t){let t=document.createElement("canvas");t.width=s,t.height=r;let i=t.getContext("2d");if(null!=i)i.putImageData(e,0,0),n=i.getImageData(0,0,s,r).data;else throw Error("Can not access image data")}else n=e.data}else if(i){if(void 0===t)throw Error("Please provide image config with format for Imagebitmap");if(void 0!==t.bitmapFormat)throw Error("Image input config format must be defined for ImageBitmap");let r=document.createElement("canvas").getContext("2d");if(null!=r){let s=e.height,i=e.width;if(r.drawImage(e,0,0,i,s),n=r.getImageData(0,0,i,s).data,void 0!==t){if(void 0!==t.height&&t.height!==s)throw Error("Image input config height doesn't match ImageBitmap height");if(a.height=s,void 0!==t.width&&t.width!==i)throw Error("Image input config width doesn't match ImageBitmap width");a.width=i}else a.height=s,a.width=i;return f.bufferToTensor(n,a)}throw Error("Can not access image data")}else if(o)return new Promise((n,r)=>{let s=document.createElement("canvas"),i=s.getContext("2d");if(!e||!i)return r();let o=new Image;o.crossOrigin="Anonymous",o.src=e,o.onload=()=>{s.width=o.width,s.height=o.height,i.drawImage(o,0,0,s.width,s.height);let e=i.getImageData(0,0,s.width,s.height);if(void 0!==t){if(void 0!==t.height&&t.height!==s.height)throw Error("Image input config height doesn't match ImageBitmap height");if(a.height=s.height,void 0!==t.width&&t.width!==s.width)throw Error("Image input config width doesn't match ImageBitmap width");a.width=s.width}else a.height=s.height,a.width=s.width;n(f.bufferToTensor(e.data,a))}});else throw Error("Input data provided is not supported - aborted tensor creation");if(void 0!==n)return f.bufferToTensor(n,a);throw Error("Input data provided is not supported - aborted tensor creation")}toImageData(e){var t,n;let r;let s=document.createElement("canvas").getContext("2d");if(null!=s){let i=this.dims[3],o=this.dims[2],a=this.dims[1],l=void 0!==e&&void 0!==e.format?e.format:"RGB",h=void 0!==e&&(null===(t=e.norm)||void 0===t?void 0:t.mean)!==void 0?e.norm.mean:255,c=void 0!==e&&(null===(n=e.norm)||void 0===n?void 0:n.bias)!==void 0?e.norm.bias:0,u=o*i;if(void 0!==e){if(void 0!==e.height&&e.height!==o)throw Error("Image output config height doesn't match tensor height");if(void 0!==e.width&&e.width!==i)throw Error("Image output config width doesn't match tensor width");if(void 0!==e.format&&4===a&&"RGBA"!==e.format||3===a&&"RGB"!==e.format&&"BGR"!==e.format)throw Error("Tensor format doesn't match input tensor dims")}let d=0,f=1,p=2,_=3,g=0,m=u,y=2*u,w=-1;"RGBA"===l?(g=0,m=u,y=2*u,w=3*u):"RGB"===l?(g=0,m=u,y=2*u):"RBG"===l&&(g=0,y=u,m=2*u),r=s.createImageData(i,o);for(let e=0;e<o*i;d+=4,f+=4,p+=4,_+=4,e++)r.data[d]=(this.data[g++]-c)*h,r.data[f]=(this.data[m++]-c)*h,r.data[p]=(this.data[y++]-c)*h,r.data[_]=-1===w?255:(this.data[w++]-c)*h}else throw Error("Can not access image data");return r}reshape(e){return new f(this.type,this.data,e)}}let p=f;class _{constructor(e){this.handler=e}async run(e,t,n){let r={},s={};if("object"!=typeof e||null===e||e instanceof p||Array.isArray(e))throw TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if("object"==typeof t){if(null===t)throw TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof p)throw TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw TypeError("'fetches' cannot be an empty array.");for(let e of(i=!1,t)){if("string"!=typeof e)throw TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)s=n;else if(void 0!==n)throw TypeError("'options' must be an object.")}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==o.indexOf(n)){let s=t[n];(null===s||s instanceof p)&&(e=!0,i=!1,r[n]=s)}if(e){if("object"==typeof n&&null!==n)s=n;else if(void 0!==n)throw TypeError("'options' must be an object.")}else s=t}}else if(void 0!==t)throw TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of this.inputNames)if(void 0===e[t])throw Error(`input '${t}' is missing in 'feeds'.`);if(i)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,s),a={};for(let e in o)Object.hasOwnProperty.call(o,e)&&(a[e]=new p(o[e].type,o[e].data,o[e].dims));return a}static async create(e,t,n,r){let s;let i={};if("string"==typeof e){if(s=e,"object"==typeof t&&null!==t)i=t;else if(void 0!==t)throw TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,"object"==typeof t&&null!==t)i=t;else if(void 0!==t)throw TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer){let o=0,a=e.byteLength;if("object"==typeof t&&null!==t)i=t;else if("number"==typeof t){if(!Number.isSafeInteger(o=t))throw RangeError("'byteOffset' must be an integer.");if(o<0||o>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(a=e.byteLength-o,"number"==typeof n){if(!Number.isSafeInteger(a=n))throw RangeError("'byteLength' must be an integer.");if(a<=0||o+a>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-o}].`);if("object"==typeof r&&null!==r)i=r;else if(void 0!==r)throw TypeError("'options' must be an object.")}else if(void 0!==n)throw TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw TypeError("'options' must be an object.");s=new Uint8Array(e,o,a)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let a=i.executionProviders||[],l=a.map(e=>"string"==typeof e?e:e.name),h=await o(l),c=await h.createSessionHandler(s,i);return new _(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}let g=_},552:function(e,t,n){"use strict";let r,s,i,o;function a(e,t){null!==e&&e(t)}function l(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}n.d(t,{t25:function(){return tz},v3$:function(){return nB},OBj:function(){return U},qCb:function(){return Y}});let h=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function c(e){return Number.isInteger(e)||"bigint"==typeof e}function u(...e){return Array.prototype.concat.apply([],e)}var d=n(7147),f=n(1418),p=n(319),_=n(8386),g=n(3342),m=n(692),y=n(495),w=n.t(y,2),b=n(2018),k=n.t(b,2),v=n(2601);let x=["wasm"];if(void 0!==v&&v?.release?.name==="node")r=y??w,x.unshift("cpu");else{r=b??k;let e="undefined"!=typeof navigator&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);e&&(r.env.wasm.simd=!1)}let{env:E}=r,A="2.6.1",M="undefined"!=typeof self&&"caches"in self,T=!R(_),B=!R(g),C=T&&B,S=C?g.dirname(g.dirname(m.fileURLToPath("file:///workspaces/transformers.js/examples/semantic-image-search-client/node_modules/@xenova/transformers/src/env.js"))):"./",I=C?g.join(S,"/.cache/"):null,z="/models/",L=C?g.join(S,z):z;E.wasm.wasmPaths=C?g.join(S,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${A}/dist/`;let U={backends:{onnx:E,tfjs:{}},__dirname:S,version:A,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!0,localModelPath:L,useFS:T,useBrowserCache:M,useFSCache:T,cacheDir:I,useCustomCache:!1,customCache:null};function R(e){return 0===Object.keys(e).length}var j=n(2601),F=n(7133).lW;globalThis.ReadableStream||(globalThis.ReadableStream=p.ReadableStream);class O{_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"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=d.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=d.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(e){n.arrayBuffer().then(t=>{e.enqueue(new Uint8Array(t)),e.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new O(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){let e=await d.promises.readFile(this.filePath);return e.buffer}async blob(){let e=await d.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){let e=await d.promises.readFile(this.filePath,"utf8");return e}async json(){return JSON.parse(await this.text())}}function P(e,t=null){let n;try{n=new URL(e)}catch(e){return!1}return(!t||!!t.includes(n.hostname))&&("http:"===n.protocol||"https:"===n.protocol)}async function $(e){if(U.useFS&&!P(e))return new O(e);if(void 0===j||j?.release?.name!=="node")return fetch(e);{let t=!!j.env?.TESTING_REMOTELY,n=U.version,r=new Headers;r.set("User-Agent",`transformers.js/${n}; is_ci/${t};`);let s=P(e,["huggingface.co","hf.co"]);if(s){let e=j.env?.HF_ACCESS_TOKEN;e&&r.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:r})}}let N={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",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"};class q{constructor(e){this.path=e}async match(e){let t=f.join(this.path,e),n=new O(t);return n.exists?n:void 0}async put(e,t){let n=F.from(await t.arrayBuffer()),r=f.join(this.path,e);try{await d.promises.mkdir(f.dirname(r),{recursive:!0}),await d.promises.writeFile(r,n)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function D(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch(e){continue}}async function W(e,t,n=!0,r={}){let s,i,o;if(!U.allowLocalModels){if(r.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(!U.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}if(a(r.progress_callback,{status:"initiate",name:e,file:t}),!s&&U.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{s=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!s&&U.useFSCache&&(s=new q(r.cache_dir??U.cacheDir)),!s&&U.useCustomCache){if(!U.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!U.customCache.match||!U.customCache.put)throw 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");s=U.customCache}let l=r.revision??"main",h=H(e,t),c=H(U.localModelPath,h),u=H(U.remoteHost,U.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",l),t),d="main"===l?h:H(e,l,t),f=s instanceof q?d:u,p=!1;if(s&&(o=await D(s,c,f)),void 0===o){if(U.allowLocalModels){let e=P(h);if(e){if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${h}.`);if(!U.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${h}.`)}else try{o=await $(c),i=c}catch(e){console.warn(`Unable to load from local path "${c}": "${e}"`)}}if(void 0===o||404===o.status){if(r.local_files_only||!U.allowRemoteModels){if(!n)return null;throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${c}".`)}if(200!==(o=await $(u)).status)return function(e,t,n){if(!n)return null;let r=N[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}(o.status,u,n);i=f}p=s&&"undefined"!=typeof Response&&o instanceof Response&&200===o.status}a(r.progress_callback,{status:"download",name:e,file:t});let _=await V(o,n=>{a(r.progress_callback,{status:"progress",...n,name:e,file:t})});return p&&i&&await s.match(i)===void 0&&await s.put(i,new Response(_,{headers:o.headers})).catch(e=>{console.warn(`Unable to add response to browser cache: ${e}.`)}),a(r.progress_callback,{status:"done",name:e,file:t}),_}async function G(e,t,n=!0,r={}){let s=await W(e,t,n,r);return null===s?{}:JSON.parse(new TextDecoder("utf-8").decode(s))}async function V(e,t){let n=e.headers.get("Content-Length");null===n&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(n??"0"),s=new Uint8Array(r),i=0,o=e.body.getReader();async function a(){let{done:e,value:n}=await o.read();if(e)return;let l=i+n.length;if(l>r){r=l;let e=new Uint8Array(r);e.set(s),s=e}s.set(n,i),i=l;let h=i/r*100;return t({progress:h,loaded:i,total:r}),a()}return await a(),s}function H(...e){return(e=e.map((t,n)=>(n&&(t=t.replace(RegExp("^/"),"")),n!==e.length-1&&(t=t.replace(RegExp("/$"),"")),t))).join("/")}function K(e){let t=Q(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0),s=n.map(e=>e/r);return s}function X(e,t=0){return e=Array.from(e).map((e,t)=>[t,e]).sort((e,t)=>t[1]-e[1]),t>0&&(e=e.slice(0,t)),e}function Q(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],n=r);return[t,n]}function Y(e,t){if(t%2==0||t<=0)throw Error("Window size must be a positive odd number");let n=new e.constructor(e.length),r=new e.constructor(t),s=Math.floor(t/2);for(let t=0;t<e.length;++t){let i=0;for(let n=-s;n<=s;++n){let s=t+n;s<0?s=Math.abs(s):s>=e.length&&(s=2*(e.length-1)-s),r[i++]=e[s]}r.sort(),n[t]=r[s]}return n}function J(e,t){let n=Math.pow(10,t);return Math.round(e*n)/n}let Z=r.Tensor;class ee extends Z{constructor(...e){return e[0]instanceof r.Tensor?super(e[0].type,e[0].data,e[0].dims):super(...e),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r<e;++r)yield this._subarray(r,n,t)}else yield*this.data}_getitem(e){let[t,...n]=this.dims;if(e=er(e,t),!(n.length>0))return new ee(this.type,[this.data[e]],n);{let t=n.reduce((e,t)=>e*t);return this._subarray(e,t,n)}}indexOf(e){for(let t=0;t<this.data.length;++t)if(this.data[t]==e)return t;return -1}_subarray(e,t,n){let r=this.data.subarray(e*t,(e+1)*t);return new ee(this.type,r,n)}item(){if(1!==this.data.length)throw Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`);return this.data[0]}tolist(){return function(e,t){let n=e.length,r=t.reduce((e,t)=>e*t);if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let s=e;for(let e=t.length-1;e>=0;e--)s=s.reduce((n,r)=>{let s=n[n.length-1];return s.length<t[e]?s.push(r):n.push([r]),n},[[]]);return s[0]}(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){for(let e=0;e<this.data.length;++e)this.data[e]=1/(1+Math.exp(-this.data[e]));return this}clone(){return new ee(this.type,this.data.slice(),this.dims.slice())}slice(...e){let t=[],n=[];for(let r=0;r<this.dims.length;++r){let s=e[r];if(null==s)n.push([0,this.dims[r]]),t.push(this.dims[r]);else if("number"==typeof s)s=er(s,this.dims[r],r),n.push([s,s+1]);else if(Array.isArray(s)&&2===s.length){if(s[0]>s[1])throw Error(`Invalid slice: ${s}`);let e=[Math.max(s[0],0),Math.min(s[1],this.dims[r])];n.push(e),t.push(e[1]-e[0])}else throw Error(`Invalid slice: ${s}`)}let r=n.map(([e,t])=>t-e),s=r.reduce((e,t)=>e*t),i=new this.data.constructor(s),o=this.stride();for(let e=0;e<s;++e){let t=0;for(let s=r.length-1,i=e;s>=0;--s){let e=r[s];t+=(i%e+n[s][0])*o[s],i=Math.floor(i/e)}i[e]=this.data[t]}return new ee(this.type,i,t)}transpose(...e){return function(e,t){let[n,r]=function(e,t,n){let r=Array(n.length),s=Array(n.length);for(let e=n.length-1,i=1;e>=0;--e)s[e]=i,r[e]=t[n[e]],i*=r[e];let i=n.map((e,t)=>s[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n<e.length;++n){let r=0;for(let e=t.length-1,s=n;e>=0;--e)r+=s%t[e]*i[e],s=Math.floor(s/t[e]);o[r]=e[n]}return[o,r]}(e.data,e.dims,t);return new ee(e.type,n,r)}(this,e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,n=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);if(null===t){let t=this.data.reduce((t,n)=>t+n**e,0)**(1/e);return new ee(this.type,[t],[])}t=er(t,this.dims.length);let r=this.dims.slice();r[t]=1;let s=new this.data.constructor(this.data.length/this.dims[t]);for(let n=0;n<this.data.length;++n){let i=0;for(let e=this.dims.length-1,s=n,o=1;e>=0;--e){let n=this.dims[e];if(e!==t){let t=s%n;i+=t*o,o*=r[e]}s=Math.floor(s/n)}s[i]+=this.data[n]**e}if(1!==e)for(let t=0;t<s.length;++t)s[t]=s[t]**(1/e);return n||r.splice(t,1),new ee(this.type,s,r)}normalize_(e=2,t=1){t=er(t,this.dims.length);let n=this.norm(e,t,!0);for(let e=0;e<this.data.length;++e){let r=0;for(let n=this.dims.length-1,s=e,i=1;n>=0;--n){let e=this.dims[n];if(n!==t){let t=s%e;r+=t*i,i*=this.dims[n]}s=Math.floor(s/e)}this.data[e]/=n.data[r]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){let t=Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}(this.dims)}squeeze(e=null){return new ee(this.type,this.data,et(this.dims,e))}squeeze_(e=null){return this.dims=et(this.dims,e),this}unsqueeze(e=null){return new ee(this.type,this.data,en(this.dims,e))}unsqueeze_(e=null){return this.dims=en(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),s=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...s],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;n<e.length;++n)if(-1===e[n]){if(-1!==t)throw Error("Only one dimension can be inferred");t=n}if(-1!==t){let n=e.reduce((e,n,r)=>r!==t?e*n:e,1);e[t]=this.data.length/n}return new ee(this.type,this.data,e)}neg_(){for(let e=0;e<this.data.length;++e)this.data[e]=-this.data[e];return this}neg(){return this.clone().neg_()}}function et(e,t){return e=e.slice(),null===t?e=e.filter(e=>1!==e):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>1!==e||!t.includes(n))),e}function en(e,t){return t=er(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function er(e,t,n=null){if(e<-t||e>=t)throw Error(`IndexError: index ${e} is out of bounds for dimension${null===n?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function es(e,t=0){t=er(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),s=new e[0].data.constructor(r),i=e[0].type;if(0===t){let t=0;for(let n of e)s.set(n.data,t),t+=n.data.length}else{let r=0;for(let i=0;i<e.length;++i){let o=e[i];for(let e=0;e<o.data.length;++e){let i=0;for(let s=o.dims.length-1,a=e,l=1;s>=0;--s){let e=o.dims[s],h=a%e;s===t&&(h+=r),i+=h*l,l*=n[s],a=Math.floor(a/e)}s[i]=o.data[e]}r+=o.dims[t]}}return new ee(i,s,n)}function ei(e,t=null,n=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0);return new ee(e.type,[t/e.data.length],[])}t=er(t,e.dims.length);let r=e.dims.slice();r[t]=1;let s=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n<e.data.length;++n){let i=0;for(let s=e.dims.length-1,o=n,a=1;s>=0;--s){let n=e.dims[s];if(s!==t){let e=o%n;i+=e*a,a*=r[s]}o=Math.floor(o/n)}s[i]+=e.data[n]}if(1!==e.dims[t])for(let n=0;n<s.length;++n)s[n]=s[n]/e.dims[t];return n||r.splice(t,1),new ee(e.type,s,r)}class eo{constructor(e=(e,t)=>e>t){this._heap=[],this._comparator=e}get size(){return this._heap.length}isEmpty(){return 0===this.size}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)this._heap.push(t),this._siftUp();return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._siftDown(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._siftDown(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_siftUp(){let e=this.size-1;for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}}class ea{constructor(){this.root=el.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);void 0===e&&(e=el.default(),t.children.set(n,e)),t=e}t.isLeaf=!0}*commonPrefixSearch(e){let t=this.root,n="";for(let r=0;r<e.length&&void 0!==t;++r){let s=e[r];n+=s,void 0!==(t=t.children.get(s))&&t.isLeaf&&(yield n)}}}class el{constructor(e,t){this.isLeaf=e,this.children=t}static default(){return new el(!1,new Map)}}class eh{constructor(e,t,n){this.sentence=e,this.len=e.length,this.bosTokenId=t,this.eosTokenId=n,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},()=>[]),this.endNodes=Array.from({length:this.len+1},()=>[]);let r=new ec(this.bosTokenId,0,0,0,0),s=new ec(this.eosTokenId,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(s.clone()),this.beginNodes[this.len].push(s),this.endNodes[0].push(r)}insert(e,t,n,r){let s=this.nodes.length,i=new ec(r,s,e,t,n);this.beginNodes[e].push(i),this.endNodes[e+t].push(i),this.nodes.push(i)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(0==this.beginNodes[t].length)return[];for(let e of this.beginNodes[t]){e.prev=null;let n=0,r=null;for(let s of this.endNodes[t]){let t=s.backtraceScore+e.score;(null===r||t>n)&&(r=s.clone(),n=t)}if(null===r)return[];e.prev=r,e.backtraceScore=n}++t}let n=[],r=this.beginNodes[e][0],s=r.prev;if(null===s)return[];let i=s.clone();for(;null!==i.prev;){n.push(i.clone());let e=i.clone();i=e.prev.clone()}return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){let e=this.viterbi();return e.map(e=>this.piece(e))}tokenIds(){let e=this.viterbi();return e.map(e=>e.tokenId)}}class ec{constructor(e,t,n,r,s){this.tokenId=e,this.nodeId=t,this.pos=n,this.length=r,this.score=s,this.prev=null,this.backtraceScore=0}clone(){let e=new ec(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}async function eu(e,t){return await Promise.all([G(e,"tokenizer.json",!0,t),G(e,"tokenizer_config.json",!0,t)])}function ed(e,t=!0){return void 0!==e.Regex?RegExp(t?e.Regex:`(${e.Regex})`,"gu"):void 0!==e.String?e.String:(console.warn("Unknown pattern type:",e),null)}function ef(e){return new Map(Object.entries(e))}function ep(e){return e.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 e_(e){return e.replace(/[\u0300-\u036f]/g,"")}let eg="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";class em extends h{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=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}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new ey(e);case"Unigram":return new ew(e,...t);case"BPE":return new ev(e);default:if(e.vocab)return new ex(e,...t);throw Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return this.encode(e)}encode(e){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(e){let t=e.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id);return this.fuse_unk&&(t=function(e,t){let n=[],r=0;for(;r<e.length;){if(n.push(e[r]),e[r]!==t){++r;continue}for(;r<e.length&&e[r]===t;)++r}return n}(t,this.unk_token_id)),t}convert_ids_to_tokens(e){return e.map(e=>this.vocab[e]??this.unk_token)}}class ey extends em{constructor(e){for(let[t,n]of(super(e),this.tokens_to_ids=ef(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[n]=t}encode(e){let t=[];for(let n of e){let e=[...n],r=!1,s=0,i=[];for(;s<e.length;){let t=e.length,n=null;for(;s<t;){let r=e.slice(s,t).join("");if(s>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(null===n){r=!0;break}i.push(n),s=t}r?t.push(this.unk_token):t.push(...i)}return t}}class ew extends em{constructor(e,t){super(e);let n=e.vocab.length;this.vocab=Array(n),this.scores=Array(n);for(let t=0;t<n;++t){let n=e.vocab[t];this.vocab[t]=n[0],this.scores[t]=n[1]}this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,t)=>[e,t])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=t.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=function(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new ea,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){let t=e.sentence,n=t.length,r=0;for(;r<n;){let n=!1,s=[];for(let i of this.trie.commonPrefixSearch(t.slice(r))){s.push(i);let t=this.tokens_to_ids.get(i),o=this.scores[t],a=i.length;e.insert(r,a,o,t),n||1!==a||(n=!0)}n||e.insert(r,1,this.unkScore,this.unk_token_id),r+=1}}tokenize(e){let t=new eh(e,this.bosTokenId,this.eosTokenId);return this.populateNodes(t),t.tokens()}encode(e){let t=[];for(let n of e){let e=this.tokenize(n);t.push(...e)}return t}}let eb=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),ek=Object.fromEntries(Object.entries(eb).map(([e,t])=>[t,e]));class ev extends em{constructor(e){for(let[t,n]of(super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ef(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[n]=t;this.bpe_ranks=new Map(e.merges.map((e,t)=>[e,t])),this.merges=e.merges.map(e=>e.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=e.end_of_word_suffix,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(e){if(0===e.length)return[];let t=this.cache.get(e);if(void 0!==t)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new eo((e,t)=>e.score<t.score),t={token:n[0],bias:0,prev:null,next:null},s=t;for(let t=1;t<n.length;++t){let r={bias:t/n.length,token:n[t],prev:s,next:null};s.next=r,this._add_node(e,s),s=r}for(;!e.isEmpty();){let n=e.pop();if(n.deleted||!n.next||n.next.deleted)continue;if(n.deleted=!0,n.next.deleted=!0,n.prev){let e={...n.prev};n.prev.deleted=!0,n.prev=e,e.prev?e.prev.next=e:t=e}let r={token:n.token+n.next.token,bias:n.bias,prev:n.prev,next:n.next.next};r.prev?(r.prev.next=r,this._add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this._add_node(e,r))}for(let e=t;null!==e;e=e.next)r.push(e.token)}else r=n;return this.cache.set(e,r),r}_add_node(e,t){let n=this.bpe_ranks.get(t.token+this.BPE_SPLIT_TOKEN+t.next.token);void 0!==n&&(t.score=n+t.bias,e.push(t))}encode(e){let t=[];for(let n of e)for(let e of this.bpe(n))this.tokens_to_ids.has(e)?t.push(e):this.byte_fallback?t.push(...Array.from(this.text_encoder.encode(e)).map(e=>`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`)):t.push(this.unk_token);return t}}class ex extends em{constructor(e,t){for(let[n,r]of(super(e),this.tokens_to_ids=ef(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[r]=n}encode(e){return e}}class eE extends h{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new eL(e);case"Precompiled":return new e6(e);case"Sequence":return new ez(e);case"Replace":return new eA(e);case"NFC":return new eM(e);case"NFKD":return new eT(e);case"Strip":return new eB(e);case"StripAccents":return new eC(e);case"Lowercase":return new eS(e);case"Prepend":return new eI(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class eA extends eE{normalize(e){let t=ed(this.config.pattern);return null===t?e:e=e.replaceAll(t,this.config.content)}}class eM extends eE{normalize(e){return e=e.normalize("NFC")}}class eT extends eE{normalize(e){return e=e.normalize("NFKD")}}class eB extends eE{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class eC extends eE{normalize(e){return e=e_(e)}}class eS extends eE{normalize(e){return e=e.toLowerCase()}}class eI extends eE{normalize(e){return e=this.config.prepend+e}}class ez extends eE{constructor(e){super(e),this.normalizers=e.normalizers.map(e=>eE.fromConfig(e))}normalize(e){return this.normalizers.reduce((e,t)=>t.normalize(e),e)}}class eL extends eE{_tokenize_chinese_chars(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n],s=r.charCodeAt(0);this._is_chinese_char(s)?(t.push(" "),t.push(r),t.push(" ")):t.push(r)}return t.join("")}_is_chinese_char(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}stripAccents(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}normalize(e){return this.config.handle_chinese_chars&&(e=this._tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),!1!==this.config.strip_accents&&(e=this.stripAccents(e))):this.config.strip_accents&&(e=this.stripAccents(e)),e}}class eU extends h{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new eR(e);case"Sequence":return new e3(e);case"WhitespaceSplit":return new e8(e);case"Metaspace":return new e1(e);case"ByteLevel":return new ej(e);case"Split":return new eF(e);case"Punctuation":return new eO(e);case"Digits":return new eP(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e)):this.pre_tokenize_text(e)).flat()}_call(e){return this.pre_tokenize(e)}}class eR extends eU{constructor(e){super(),this.pattern=RegExp(`[^\\s${eg}]+|[${eg}]`,"gu")}pre_tokenize_text(e){return e.trim().match(this.pattern)||[]}}class ej extends eU{constructor(e){super(),this.config=e,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=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=eb,this.text_encoder=new TextEncoder}pre_tokenize_text(e){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(""))}}class eF extends eU{constructor(e){super(),this.config=e,this.pattern=ed(this.config.pattern,this.config.invert)}pre_tokenize_text(e){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:e.split(this.pattern).filter(e=>e)}}class eO extends eU{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${eg}]+|[${eg}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}}class eP extends eU{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}}class e$ extends h{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new eD(e);case"ByteLevel":return new eW(e);case"RobertaProcessing":return new eq(e);case"BertProcessing":return new eN(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class eN extends e${constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,t=null){return e=u([this.cls],e,[this.sep]),null!==t&&(e=u(e,[this.sep],t,[this.sep])),e}}class eq extends eN{}class eD extends e${constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,t=null){let n=null===t?this.single:this.pair,r=[];for(let s of n)"SpecialToken"in s?r.push(s.SpecialToken.id):"Sequence"in s&&("A"===s.Sequence.id?r=u(r,e):"B"===s.Sequence.id&&(r=u(r,t)));return r}}class eW extends e${post_process(e){return e}}class eG extends h{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){switch(e.type){case"WordPiece":return new eQ(e);case"Metaspace":return new e2(e);case"ByteLevel":return new eY(e);case"Replace":return new eV(e);case"ByteFallback":return new eH(e);case"Fuse":return new eK(e);case"Strip":return new eX(e);case"Sequence":return new eZ(e);case"CTC":return new eJ(e);case"BPEDecoder":return new e0(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class eV extends eG{decode_chain(e){let t=ed(this.config.pattern);return null===t?e:e.map(e=>e.replaceAll(t,this.config.content))}}class eH extends eG{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],n=[];for(let r of e){let e=null;if(6===r.length&&r.startsWith("<0x")&&r.endsWith(">")){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}}class eK extends eG{decode_chain(e){return[e.join("")]}}class eX extends eG{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n<this.start;++n){if(e[n]===this.content){t=n+1;continue}break}let n=e.length;for(let t=0;t<this.stop;++t){let r=e.length-t-1;if(e[r]===this.content){n=r;continue}break}return e.slice(t,n)})}}class eQ extends eG{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=ep(e)),e))}}class eY extends eG{constructor(e){super(e),this.byte_decoder=ek,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.includes(r)?(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r)):n.push(r);return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}}class eJ extends eG{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let n=t.filter(e=>e!==this.pad_token).join("");return this.cleanup&&(n=ep(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class eZ extends eG{constructor(e){super(e),this.decoders=e.decoders.map(e=>eG.fromConfig(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}}class e0 extends eG{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((t,n)=>t.replaceAll(this.suffix,n===e.length-1?"":" "))}}class e1 extends eU{constructor(e){super(),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement,this.strRep=e.str_rep||this.replacement}pre_tokenize(e){"string"==typeof e&&(e=e.trimStart().split(/\s+/));let t=[];for(let n of e){let e=n.replaceAll(" ",this.strRep);this.addPrefixSpace&&!e.startsWith(this.replacement)&&(e=this.strRep+e),t.push(e)}return t}}class e2 extends eG{constructor(e){super(e),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement}decode_chain(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n].replaceAll(this.replacement," ");this.addPrefixSpace&&0==n&&r.startsWith(" ")&&(r=r.substring(1)),t.push(r)}return t}}class e6 extends eE{constructor(e){super(e),this.charsmap=e.precompiled_charsmap}normalize(e){if((e=(e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,"")).replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm," ")).includes("~")){let t=e.split("~");e=t.map(e=>e.normalize("NFKC")).join("~")}else e=e.normalize("NFKC");return e}}class e3 extends eU{constructor(e){super(),this.tokenizers=e.pretokenizers.map(e=>eU.fromConfig(e))}pre_tokenize_text(e){return"string"==typeof e&&(e=[e]),this.tokenizers.reduce((e,t)=>t.pre_tokenize(e),e)}}class e8 extends eU{constructor(e){super()}pre_tokenize_text(e){return e.match(/\S+/g)||[]}}class e4 extends h{constructor(e,t){for(let n of(super(),this.normalizer=eE.fromConfig(e.normalizer),this.pre_tokenizer=eU.fromConfig(e.pre_tokenizer),this.model=em.fromConfig(e.model,t),this.post_processor=e$.fromConfig(e.post_processor),this.decoder=eG.fromConfig(e.decoder),this.decoder.end_of_word_suffix=this.model.end_of_word_suffix,this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],e.added_tokens)){let e=n.id,t=n.content;this.added_tokens.push(t),this.model.tokens_to_ids.set(t,e),this.model.vocab[e]=t,n.special&&(this.special_tokens.push(t),this.all_special_ids.push(e))}this.special_tokens.push(...t.additional_special_tokens??[]),this.special_tokens=[...new Set(this.special_tokens)],this.decoder.added_tokens=this.added_tokens,this.added_tokens_regex=this.added_tokens.length>0?RegExp("("+this.added_tokens.map(l).join("|")+")"):null,this.mask_token=this.getToken(t,"mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken(t,"pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken(t,"sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,this.padding_side="right"}getToken(e,...t){for(let n of t){let t=e[n];if(t){if("object"!=typeof t)return t;if("AddedToken"===t.__type)return t.content;throw Error(`Unknown token: ${t}`)}}return null}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:s=!1,revision:i="main"}={}){let o=await eu(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:s,revision:i});return new this(...o)}prepare_model_inputs(e){return e}_call(e,{text_pair:t=null,padding:n=!1,truncation:r=null,max_length:s=null,return_tensor:i=!0}={}){let o;if(Array.isArray(e)){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(Array.isArray(t)){if(e.length!==t.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");o=e.map((e,n)=>this.encode(e,t[n]))}else o=e.map(e=>this.encode(e))}else{if(null===e)throw Error("text may not be null");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");o=[this.encode(e,t)]}let a=Q(o.map(e=>e.length))[0];null===s&&(s=a),s=Math.min(s,this.model_max_length);let l=[];if(n||r)for(let e=0;e<o.length;++e){if(o[e].length===s){l.push(Array(o[e].length).fill(1));continue}if(o[e].length>s)r&&(o[e]=o[e].slice(0,s)),l.push(Array(o[e].length).fill(1));else if(n){let t=s-o[e].length;"right"===this.padding_side?(l.push(Array(o[e].length).fill(1).concat(Array(t).fill(0))),o[e].push(...Array(t).fill(this.pad_token_id))):(l.push(Array(t).fill(0).concat(Array(o[e].length).fill(1))),o[e].unshift(...Array(t).fill(this.pad_token_id)))}else l.push(Array(o[e].length).fill(1))}else l=o.map(e=>Array(e.length).fill(1));if(i){if(!(n&&r)&&o.some(e=>e.length!==o[0].length))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.");let e=[o.length,o[0].length];o=new ee("int64",BigInt64Array.from(o.flat().map(BigInt)),e),l=new ee("int64",BigInt64Array.from(l.flat().map(BigInt)),e)}else Array.isArray(e)||(o=o[0],l=l[0]);let h={input_ids:o,attention_mask:l};return this.prepare_model_inputs(h)}_encode_text(e){if(null===e)return null;let t=this.added_tokens_regex?e.split(this.added_tokens_regex).filter(e=>e):[e];return t.map(e=>{if(this.added_tokens.includes(e))return e;{!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=e_(e.toLowerCase())),null!==this.normalizer&&(e=this.normalizer(e));let t=null!==this.pre_tokenizer?this.pre_tokenizer(e):[e];return this.model(t)}}).flat()}encode(e,t=null){let n=this._encode_text(e),r=this._encode_text(t),s=null!==this.post_processor?this.post_processor(n,r):u(n??[],r??[]);return this.model.convert_tokens_to_ids(s)}batch_decode(e,t={}){return e.map(e=>this.decode(e,t))}decode(e,t={}){if(!Array.isArray(e)||0===e.length||!c(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){let r=this.model.convert_ids_to_tokens(e);t&&(r=r.filter(e=>!this.special_tokens.includes(e)));let s=this.decoder(r);return this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),t&&(s=s.trim())),(n??this.clean_up_tokenization_spaces)&&(s=ep(s)),s}}function e5(e){if(e.input_ids instanceof ee)e.token_type_ids=new ee("int64",new BigInt64Array(e.input_ids.data.length),e.input_ids.dims);else if(Array.isArray(e.input_ids))Array.isArray(e.input_ids[0])?e.token_type_ids=e.input_ids.map(e=>Array(e.length).fill(0)):e.token_type_ids=Array(e.input_ids.length).fill(0);else throw Error("Input ids must be a Tensor or an Array");return e}class e9 extends e4{prepare_model_inputs(e){return e5(e)}}class e7 extends e4{prepare_model_inputs(e){return e5(e)}}class te extends e4{prepare_model_inputs(e){return e5(e)}}class tt extends e4{prepare_model_inputs(e){return e5(e)}}class tn extends e4{prepare_model_inputs(e){return e5(e)}}class tr extends e4{prepare_model_inputs(e){return e5(e)}}class ts extends e4{prepare_model_inputs(e){return e5(e)}}class ti extends e4{}class to extends e4{}class ta extends e4{constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}prepare_model_inputs(e){return e5(e)}}class tl extends e4{}class th extends e4{}class tc extends e4{}class tu extends e4{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return tk(this,e,t,n)}}class td extends tu{}class tf extends e4{}class tp extends e4{constructor(e,t){let n=".,!?…。,、।۔،",r=e.pre_tokenizer?.pretokenizers[0]?.pattern;r&&r.Regex===` ?[^(\\s|[${n}])]+`&&(r.Regex=` ?[^\\s${n}]+`),super(e,t)}}class t_ extends e4{}class tg extends e4{}class tm extends e4{}class ty extends e4{}class tw extends e4{prepare_model_inputs(e){return e5(e)}}class tb extends e4{}function tk(e,t,n,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let s=r.src_lang,i=r.tgt_lang;if(!e.language_codes.includes(i))throw Error(`Target language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==s){if(!e.language_codes.includes(s))throw Error(`Source language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(let t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(s);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(i)])[0],e._call(t,n)}class tv extends e4{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return tk(this,e,t,n)}}class tx extends e4{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return tk(this,e,t,n)}}let tE=[["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"]],tA=new Map(tE),tM=new Map([...tE.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class tT extends e4{_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:s=!0}={}){if(null===r)throw Error("Must specify time_precision");let i=null,o="word"===t;function a(){return{language:i,timestamp:[null,null],text:""}}let l=[],h=a(),c=0,u=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1,d=[],f=[],p=!1,_=null,g=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,s=o?n.token_timestamps:null,m=null,y=u;if("stride"in n){let[t,s,i]=n.stride;if(c-=s,_=t-i,s&&(y=s/r+u),i)for(let t=e.length-1;t>=0;--t){let n=e[t];if(n>=u){if(null!==m&&(n-u)*r<_)break;m=n}}}let w=[],b=[];for(let n=0;n<e.length;++n){let _=e[n];if(g.has(_)){let e=this.decode([_]),n=tA.get(e.slice(2,-2));if(void 0!==n){if(null!==i&&n!==i&&!t){d.push(w);let e=this.findLongestCommonSequence(d)[0],t=this.decode(e);h.text=t,l.push(h),d=[],w=[],h=a()}i=h.language=n}}else if(_>=u){let e=(_-u)*r+c,t=J(e,2);if(null!==m&&_>=m)p=!0;else if(p||d.length>0&&_<y)p=!1;else if(null===h.timestamp[0])h.timestamp[0]=t;else if(t===h.timestamp[0]);else{h.timestamp[1]=t,d.push(w),o&&f.push(b);let[e,n]=this.findLongestCommonSequence(d,f),r=this.decode(e);h.text=r,o&&(h.words=this.collateWordTimestamps(e,n,i)),l.push(h),d=[],w=[],f=[],b=[],h=a()}}else if(w.push(_),o){let e,t=J(s[n]+c,2);e=n+1<s.length?J(s[n+1]+c,2):null,b.push([t,e])}}if("stride"in n){let[e,t,r]=n.stride;c+=e-r}w.length>0?(d.push(w),o&&f.push(b)):d.every(e=>0===e.length)&&(h=a(),d=[],w=[],f=[],b=[])}if(d.length>0){if(s&&t)throw 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.");let[e,n]=this.findLongestCommonSequence(d,f),r=this.decode(e);h.text=r,o&&(h.words=this.collateWordTimestamps(e,n,i)),l.push(h)}let m=Object.create(null),y=l.map(e=>e.text).join("");if(t||n){for(let e=0;e<l.length;++e){let r=l[e];t||delete r.timestamp,n||delete r.language}if(o){let e=[];for(let t of l)for(let n of t.words)e.push(n);m={chunks:e}}else m={chunks:l}}return[y,m]}findLongestCommonSequence(e,t=null){let n=e[0],r=n.length,s=[],i=Array.isArray(t)&&t.length>0,o=i?[]:null,a=i?t[0]:null;for(let l=1;l<e.length;++l){let h=e[l],c=0,u=[r,r,0,0],d=h.length;for(let e=1;e<r+d;++e){let t=e/1e4,s=Math.max(0,r-e),i=Math.min(r,r+d-e),o=n.slice(s,i),a=Math.max(0,e-r),l=Math.min(d,e),f=h.slice(a,l);if(o.length!==f.length)throw Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let p=o.filter((e,t)=>e===f[t]).length,_=p/e+t;p>1&&_>c&&(c=_,u=[s,i,a,l])}let[f,p,_,g]=u,m=Math.floor((p+f)/2),y=Math.floor((g+_)/2);s.push(...n.slice(0,m)),r=(n=h.slice(y)).length,i&&(o.push(...a.slice(0,m)),a=t[l].slice(y))}return(s.push(...n),i)?(o.push(...a),[s,o]):[s,[]]}collateWordTimestamps(e,t,n){let[r,s,i]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e<r.length;++e){let n=i[e];o.push({text:r[e],timestamp:[t[n.at(0)][0],t[n.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,n="\"'“\xa1\xbf([{-",r="\"'.。,,!!??::”)]}、"){let s,i,o;return["chinese","japanese","thai","lao","myanmar"].includes(t=t??"english")?[s,i,o]=this.splitTokensOnUnicode(e):[s,i,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(s,i,o,n,r)}decode(e,t){return t&&t.decode_with_timestamps?this.decodeWithTimestamps(e,t):super.decode(e,t)}decodeWithTimestamps(e,t){let n=t?.time_precision??.02,r=Array.from(this.all_special_ids).at(-1)+1,s=[[]];for(let t of e)if(t>=r){let e=(t-r)*n;e=J(e,2),s.push(`<|${e}|>`),s.push([])}else s[s.length-1].push(t);return(s=s.map(e=>"string"==typeof e?e:super.decode(e,t))).join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],s=[],i=[],o=[],a=0;for(let l=0;l<e.length;++l){let h=e[l];i.push(h),o.push(l);let c=this.decode(i,{decode_with_timestamps:!0});c.includes("�")&&"�"!==t[a+c.indexOf("�")]||(n.push(c),r.push(i),s.push(o),i=[],o=[],a+=c.length)}return[n,r,s]}splitTokensOnSpaces(e){let[t,n,r]=this.splitTokensOnUnicode(e),s=[],i=[],o=[],a=RegExp(`^[${eg}]$`,"gu");for(let e=0;e<t.length;++e){let l=t[e],h=n[e],c=r[e],u=h[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),d=l.startsWith(" "),f=l.trim(),p=a.test(f);if(u||d||p||0===s.length)s.push(l),i.push(h),o.push(c);else{let e=s.length-1;s[e]+=l,i[e].push(...h),o[e].push(...c)}}return[s,i,o]}mergePunctuations(e,t,n,r,s){let i=structuredClone(e),o=structuredClone(t),a=structuredClone(n),l=i.length-2,h=i.length-1;for(;l>=0;)i[l].startsWith(" ")&&r.includes(i[l].trim())?(i[h]=i[l]+i[h],o[h]=u(o[l],o[h]),a[h]=u(a[l],a[h]),i[l]="",o[l]=[],a[l]=[]):h=l,--l;for(l=0,h=1;h<i.length;)!i[l].endsWith(" ")&&s.includes(i[h])?(i[l]+=i[h],o[l]=u(o[l],o[h]),a[l]=u(a[l],a[h]),i[h]="",o[h]=[],a[h]=[]):l=h,++h;return[i.filter(e=>e),o.filter(e=>e.length>0),a.filter(e=>e.length>0)]}get_decoder_prompt_ids({language:e=null,task:t=null,no_timestamps:n=!0}={}){let r=[];if(e){e=e.toLowerCase();let t=tM.get(e);if(void 0===t){if(tA.has(e))t=e;else{let t=2===e.length,n=t?tA.keys():tA.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(n)}`)}}let n=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===n)throw Error(`Unable to find language "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);r.push(n)}else r.push(null);if(t){if("transcribe"!==(t=t.toLowerCase())&&"translate"!==t)throw Error(`Task "${t}" is not supported. Must be one of: ["transcribe", "translate"]`);let e=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===e)throw Error(`Unable to find task "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);r.push(e)}else r.push(null);if(n){let e=this.model.tokens_to_ids.get("<|notimestamps|>");if(void 0===e)throw Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');r.push(e)}return r.map((e,t)=>[t+1,e]).filter(e=>null!==e[1])}}class tB extends e4{}class tC extends e4{}class tS extends e4{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(e=>this.languageRegex.test(e)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(null===e)return null;let[t,...n]=e.trim().split(this.languageRegex);if(0===n.length)return super._encode_text(t);if(2===n.length){let[e,t]=n;return this.supported_language_codes.includes(e)||console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),u([e],super._encode_text(t))}}}class tI extends e4{}class tz{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:tl,DistilBertTokenizer:ti,CamembertTokenizer:to,DebertaTokenizer:tn,DebertaV2Tokenizer:tr,BertTokenizer:e9,HerbertTokenizer:ts,XLMTokenizer:ta,MobileBertTokenizer:te,SqueezeBertTokenizer:tt,AlbertTokenizer:e7,GPT2Tokenizer:th,BartTokenizer:tc,MBartTokenizer:tu,MBart50Tokenizer:td,RobertaTokenizer:tf,WhisperTokenizer:tT,CodeGenTokenizer:tB,CLIPTokenizer:tC,MarianTokenizer:tS,BloomTokenizer:tp,NllbTokenizer:tv,M2M100Tokenizer:tx,LlamaTokenizer:t_,CodeLlamaTokenizer:tg,XLMRobertaTokenizer:tm,MPNetTokenizer:ty,FalconTokenizer:tw,GPTNeoXTokenizer:tb,Wav2Vec2CTCTokenizer:tI,PreTrainedTokenizer:e4};static async from_pretrained(e,{quantized:t=!0,progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:o="main"}={}){let[a,l]=await eu(e,{quantized:t,progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:o}),h=l.tokenizer_class.replace(/Fast$/,""),c=this.TOKENIZER_CLASS_MAPPING[h];return c||(console.warn(`Unknown tokenizer class "${h}", attempting to construct from base class.`),c=e4),new c(a,l)}}async function tL(e,t){return await G(e,"config.json",!0,t)}class tU{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:s=!1,revision:i="main"}={}){let o=n??await tL(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:s,revision:i});return new this(o)}}class tR{static async from_pretrained(...e){return tU.from_pretrained(...e)}}class tj extends h{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){for(let n of t)this.processors.forEach(t=>t(e,n))}[Symbol.iterator](){return this.processors.values()}}class tF extends h{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class tO extends tF{constructor(e){super(),this.force_token_map=Object.fromEntries(e??[])}_call(e,t){let n=this.force_token_map[e.length];return null!=n&&(t.data.fill(-1/0),t.data[n]=0),t}}class tP extends tF{constructor(e){super(),this.bos_token_id=e}_call(e,t){return 1===e.length&&(t.data.fill(-1/0),t.data[this.bos_token_id]=0),t}}class t$ extends tF{constructor(e,t){super(),this.max_length=e,this.forced_eos_token_id=t}_call(e,t){}}class tN extends tF{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){if(e.length===this.begin_index)for(let e of this.begin_suppress_tokens)t.data[e]=-1/0;return t}}class tq extends tF{constructor(e){super(),this.eos_token_id=e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(e.forced_decoder_ids||[]).length+2,e.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){if(t.data[this.no_timestamps_token_id]=-1/0,e.length===this.begin_index-1)return t.data.fill(-1/0),t.data[this.timestamp_begin]=0,t;let n=e.slice(this.begin_index),r=n.length>=1&&n[n.length-1]>=this.timestamp_begin,s=n.length<2||n[n.length-2]>=this.timestamp_begin;if(r&&(s?t.data.subarray(this.timestamp_begin).fill(-1/0):t.data.subarray(0,this.eos_token_id).fill(-1/0)),e.length===this.begin_index&&null!==this.max_initial_timestamp_index){let e=this.timestamp_begin+this.max_initial_timestamp_index;t.data.subarray(e+1).fill(-1/0)}let i=function(e){let t=K(e),n=t.map(e=>Math.log(e));return n}(t.data),o=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t)),a=Q(i.subarray(0,this.timestamp_begin))[0];return o>a&&t.data.subarray(0,this.timestamp_begin).fill(-1/0),t}}class tD extends tF{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){let t=[];for(let n=0;n<this.no_repeat_ngram_size;++n)t.push(e[r+n]);n.push(t)}let r=new Map;for(let e of n){let t=e.slice(0,e.length-1),n=JSON.stringify(t),s=r.get(n)??[];s.push(e[e.length-1]),r.set(n,s)}return r}getGeneratedNgrams(e,t){let n=t.slice(t.length+1-this.no_repeat_ngram_size,t.length),r=e.get(JSON.stringify(n))??[];return r}calcBannedNgramTokens(e){if(e.length+1<this.no_repeat_ngram_size)return[];{let t=this.getNgrams(e),n=this.getGeneratedNgrams(t,e);return n}}_call(e,t){let n=this.calcBannedNgramTokens(e);for(let e of n)t.data[e]=-1/0;return t}}class tW extends tF{constructor(e){super(),this.penalty=e}_call(e,t){for(let n of e)t.data[n]<0?t.data[n]*=this.penalty:t.data[n]/=this.penalty;return t}}class tG extends tF{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){if(e.length<this.min_length)for(let e of this.eos_token_id)t.data[e]=-1/0;return t}}class tV extends tF{constructor(e,t,n){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(n)?n:[n]}_call(e,t){let n=e.length-this.prompt_length_to_skip;if(n<this.min_new_tokens)for(let e of this.eos_token_id)t.data[e]=-1/0;return t}}class tH{constructor(e={}){this.max_length=e.max_length??20,this.max_new_tokens=e.max_new_tokens??null,this.min_length=e.min_length??0,this.min_new_tokens=e.min_new_tokens??null,this.early_stopping=e.early_stopping??!1,this.max_time=e.max_time??null,this.do_sample=e.do_sample??!1,this.num_beams=e.num_beams??1,this.num_beam_groups=e.num_beam_groups??1,this.penalty_alpha=e.penalty_alpha??null,this.use_cache=e.use_cache??!0,this.temperature=e.temperature??1,this.top_k=e.top_k??50,this.top_p=e.top_p??1,this.typical_p=e.typical_p??1,this.epsilon_cutoff=e.epsilon_cutoff??0,this.eta_cutoff=e.eta_cutoff??0,this.diversity_penalty=e.diversity_penalty??0,this.repetition_penalty=e.repetition_penalty??1,this.encoder_repetition_penalty=e.encoder_repetition_penalty??1,this.length_penalty=e.length_penalty??1,this.no_repeat_ngram_size=e.no_repeat_ngram_size??0,this.bad_words_ids=e.bad_words_ids??null,this.force_words_ids=e.force_words_ids??null,this.renormalize_logits=e.renormalize_logits??!1,this.constraints=e.constraints??null,this.forced_bos_token_id=e.forced_bos_token_id??null,this.forced_eos_token_id=e.forced_eos_token_id??null,this.remove_invalid_values=e.remove_invalid_values??!1,this.exponential_decay_length_penalty=e.exponential_decay_length_penalty??null,this.suppress_tokens=e.suppress_tokens??null,this.begin_suppress_tokens=e.begin_suppress_tokens??null,this.forced_decoder_ids=e.forced_decoder_ids??null,this.num_return_sequences=e.num_return_sequences??1,this.output_attentions=e.output_attentions??!1,this.output_hidden_states=e.output_hidden_states??!1,this.output_scores=e.output_scores??!1,this.return_dict_in_generate=e.return_dict_in_generate??!1,this.pad_token_id=e.pad_token_id??null,this.bos_token_id=e.bos_token_id??null,this.eos_token_id=e.eos_token_id??null,this.encoder_no_repeat_ngram_size=e.encoder_no_repeat_ngram_size??0,this.decoder_start_token_id=e.decoder_start_token_id??null,this.generation_kwargs=e.generation_kwargs??{}}}class tK extends h{constructor(e){super(),this.generation_config=e}_call(e,t=-1){return this.sample(e,t)}sample(e,t){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let n=e.dims.at(-1),r=e.data;if(-1===t)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return this.generation_config.temperature>0&&(r=r.map(e=>e/this.generation_config.temperature)),r}randomSelect(e){let t=Math.random()*e.reduce((e,t)=>e+t,0);for(let n=0;n<e.length;++n)if((t-=e[n])<=0)return n;return 0}static getSampler(e){if(e.do_sample)return new tQ(e);if(e.num_beams>1)return new tY(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new tX(e)}}class tX extends tK{sample(e,t=-1){return[[Q(this.getLogits(e,t))[1],0]]}}class tQ extends tK{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));let r=this.getLogits(e,t),s=X(r,n),i=K(s.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[s[e][0],Math.log(i[e])]})}}class tY extends tK{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));let r=this.getLogits(e,t),s=X(r,n),i=K(s.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},(e,t)=>[s[t][0],Math.log(i[t])])}}let{InferenceSession:tJ,Tensor:tZ}=r,t0={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4},t1=new Map,t2=new Map,t6=new Map;async function t3(e,t,n){let r=`onnx/${t}${n.quantized?"_quantized":""}.onnx`,s=await W(e,r,!0,n);try{return await tJ.create(s,{executionProviders:x})}catch(e){if(1===x.length&&"wasm"===x[0])throw e;return console.warn(e),console.warn("Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "),await tJ.create(s,{executionProviders:["wasm"]})}}async function t8(e,t){let n={},r=[];for(let s of e.inputNames)void 0===t[s]?r.push(s):n[s]=t[s];if(r.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);let s=Object.keys(t).length,i=e.inputNames.length;return s>i&&console.warn(`WARNING: Too many inputs were provided (${s} > ${i}). The following inputs will be ignored: "${Object.keys(t).filter(t=>!e.inputNames.includes(t)).join(", ")}".`),n}async function t4(e,t){let n=await t8(e,t);try{let t=await e.run(n);return t=function e(t){for(let n in t)t[n]instanceof tZ?t[n]=new ee(t[n]):"object"==typeof t[n]&&e(t[n]);return t}(t)}catch(e){throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",n),e}}function t5(e,t){let n=e.config.pad_token_id??null,r=e.config.eos_token_id??null;c(r)&&(r=[r]);let s=-1!==t.indexOf(n),i=null===r||!r.includes(n);if(!s||!i)return new ee("int64",new BigInt64Array(t.data.length).fill(1n),t.dims);{let e=BigInt64Array.from(t.data.map(e=>e!=n));return new ee("int64",e,t.dims)}}function t9(e){return new ee("bool",[e],[1])}async function t7(e,t){let n=e.add_decoder_pkv??!0,{encoder_outputs:r,past_key_values:s}=t;r||(r=(await nr(e,t)).last_hidden_state);let i={input_ids:t.decoder_input_ids,encoder_hidden_states:r,use_cache_branch:t9(!!s)};e.decoder_merged_session.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask),e.addPastKeyValues(i,s,n);let o=await t4(e.decoder_merged_session,i),a=o.logits;s=e.getPastKeyValues(o,s);let l=e.getAttentions(o);return new ru({logits:a,past_key_values:s,encoder_outputs:r,...l})}function ne(e,t,n){let r=[],s=0,i=e.requires_attention_mask??!0,o=e.config.decoder_start_token_id;for(let n of(Array.isArray(o)||(o=[o]),t)){n.dims=[1,...n.dims];let t={inputs:n,encoder_outputs:null,prev_model_outputs:null,output_token_ids:o,done:!1,score:0,id:s++};i&&(t.attention_mask=t5(e,n)),r.push(t)}return r}async function nt(e,t){let n=e.main_input_name,r={[n]:t.inputs,decoder_input_ids:function(e){if(e instanceof ee)return e;if(0===e.length)throw Error("items must be non-empty");if(!Array.isArray(e[0]))return new ee("int64",BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length]);if(e.some(t=>t.length!==e[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 ee("int64",BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}(t.output_token_ids.slice(-1)),encoder_outputs:t.encoder_outputs,past_key_values:t.prev_model_outputs?.past_key_values};t.attention_mask&&(r.attention_mask=t.attention_mask);let s=await e.forward(r);return t.prev_model_outputs=s,t.encoder_outputs=s.encoder_outputs,s}function nn(e,t){e.output_token_ids=[...e.output_token_ids,t]}async function nr(e,t){let n={};for(let r of e.session.inputNames)n[r]=t[r];return await t4(e.session,n)}async function ns(e,t){let{input_ids:n,past_key_values:r,attention_mask:s}=t,i={input_ids:n,attention_mask:s??t5(e,n),use_cache_branch:t9(!!r)};e.addPastKeyValues(i,r);let o=await t4(e.session,i);return{logits:o.logits,past_key_values:r=e.getPastKeyValues(o,r)}}function ni(e,t,n,r){let s=[],i=0;for(let o of t){let t,a=o.tolist().map(Number);o.dims=[1,...o.dims],r?(t=r[i]).dims=[1,...t.dims]:t=t5(e,o);let l={input:o,model_input_ids:o,attention_mask:t,prev_model_outputs:null,output_token_ids:a,num_output_tokens:n,done:!1,score:0,id:i++};s.push(l)}return s}async function no(e,t){let n=new BigInt64Array(t.output_token_ids.length).fill(1n),r={input_ids:t.model_input_ids,attention_mask:new ee("int64",n,[1,n.length]),past_key_values:t.prev_model_outputs?.past_key_values},s=await e.forward(r);return t.prev_model_outputs=s,s}function na(e,t){e.output_token_ids=[...e.output_token_ids,t],e.model_input_ids=new ee("int64",[BigInt(t)],[1,1])}class nl extends h{main_input_name="input_ids";constructor(e,t){super(),this.config=e,this.session=t;let n=t6.get(this.constructor),r=t1.get(n);this.can_generate=!1,this._runBeam=null,this._getStartBeams=null,this._updateBeam=null,this._forward=null,r===t0.DecoderOnly?(this.can_generate=!0,this._runBeam=no,this._getStartBeams=ni,this._updateBeam=na,this._forward=ns):r===t0.Seq2Seq||r===t0.Vision2Seq?(this.can_generate=!0,this._runBeam=nt,this._getStartBeams=ne,this._updateBeam=nn,this._forward=t7):(t0.EncoderDecoder,this._forward=nr)}async dispose(){let e=[];for(let t of Object.keys(this)){let n=this[t];n instanceof tJ&&e.push(n.handler.dispose())}return await Promise.all(e)}static async from_pretrained(e,{quantized:t=!0,progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:o="main",model_file_name:a=null}={}){let l,h={quantized:t,progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:o,model_file_name:a},c=t6.get(this),u=t1.get(c);return u===t0.DecoderOnly?l=await Promise.all([tR.from_pretrained(e,h),t3(e,h.model_file_name??"decoder_model_merged",h),G(e,"generation_config.json",!1,h)]):u===t0.Seq2Seq||u===t0.Vision2Seq?l=await Promise.all([tR.from_pretrained(e,h),t3(e,"encoder_model",h),t3(e,"decoder_model_merged",h),G(e,"generation_config.json",!1,h)]):u===t0.EncoderDecoder?l=await Promise.all([tR.from_pretrained(e,h),t3(e,"encoder_model",h),t3(e,"decoder_model_merged",h)]):(u!==t0.EncoderOnly&&console.warn(`Model type for '${c}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),l=await Promise.all([tR.from_pretrained(e,h),t3(e,h.model_file_name??"model",h)])),new this(...l)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_processor(e,t,n=null){let r=new tj;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&r.push(new tW(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&r.push(new tD(e.no_repeat_ngram_size)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&r.push(new tG(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&r.push(new tV(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&r.push(new tP(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&r.push(new t$(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){let n=t>1||null===e.forced_bos_token_id?t:t+1;null!==e.forced_decoder_ids&&(n+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),r.push(new tN(e.begin_suppress_tokens,n))}return null!==e.forced_decoder_ids&&r.push(new tO(e.forced_decoder_ids)),null!==n&&r.extend(n),r}_get_generation_config(e){let t=new tH(this.config);return"generation_config"in this&&Object.assign(t,this.generation_config),null!==e&&Object.assign(t,e),t}async generate(e,t=null,n=null,{inputs_attention_mask:r=null}={}){let s;if(!this.can_generate){let e=t6.get(this.constructor),t=`The current model class (${e}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`,n=this.config.model_type,r=n7.get(n)??n9.get(n)??rn.get(n);throw r&&(t+=` Please use the following class instead: '${r[0]}'`),Error(t)}if(!(e instanceof ee)&&e?.prototype?.__proto__?.constructor?.name!=="TypedArray"&&!Array.isArray(e))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`);if(this.config.is_encoder_decoder)s=0;else if(0===(s=e instanceof ee?e.dims.at(-1):e.length))throw Error("Must supply a non-empty array of input token ids.");t=this._get_generation_config(t),n=n??new tj,n=this._get_logits_processor(t,s,n);let i=t.eos_token_id;null===i||Array.isArray(i)||(i=[i]);let o=1,a=o+(t.max_new_tokens??1/0),l=Number.isInteger(t.max_length)&&(t.max_new_tokens??null)===null,h=tK.getSampler(t),c=this.getStartBeams(e,o,r);for(;c.some(e=>!e.done)&&o<a;){let e=[];for(let r of c){if(r.done){e.push(r);continue}if(l&&r.output_token_ids.length>=t.max_length){r.done=!0,e.push(r);continue}let s=await this.runBeam(r);t.output_attentions&&this.addAttentionsToBeam(r,s),t.output_scores;let o=s.logits.slice(null,-1,null);for(let[t,s]of(n(r.output_token_ids,o),h(o))){let n={...r};this.updateBeam(n,t),n.score+=s,i&&i.includes(t)&&(n.done=!0),e.push(n)}}++o,c=(e=this.groupBeams(e).map(e=>e.sort((e,t)=>t.score-e.score).slice(0,t.num_beams))).flat(),t.callback_function&&t.callback_function(c)}let u=this.groupBeams(c),d=e=>u.map(n=>t.num_return_sequences>1?n.slice(0,t.num_return_sequences).map(t=>t[e]):[n[0][e]]).flat(),f=d("output_token_ids");if(!t.return_dict_in_generate)return f;{let e=d("decoder_attentions"),t=d("cross_attentions");return{sequences:f,decoder_attentions:e,cross_attentions:t}}}addAttentionsToBeam(e,t){if(this.config.is_encoder_decoder){if(!t.cross_attentions||0===t.cross_attentions.length)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`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(t.cross_attentions)}if(!t.decoder_attentions||0===t.decoder_attentions.length)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`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(t.decoder_attentions)}groupBeams(e){let t=Object.create(null);for(let n of e)void 0===t[n.id]?t[n.id]=[n]:t[n.id].push(n);return Object.values(t)}getPastKeyValues(e,t){let n=Object.create(null);for(let r in e)if(r.startsWith("present")){let s=r.replace("present","past_key_values");t&&r.includes("encoder")?n[s]=t[s]:n[s]=e[r]}return n}getAttentions(e){let t=Object.create(null);for(let n of["cross_attentions","decoder_attentions"]){let r=[];for(let t in e)if(t.startsWith(n)){let n=t.split(".").pop();r[n]=e[t]}t[n]=r}return t}addPastKeyValues(e,t,n=!1){if(t)Object.assign(e,t);else if(n){let t=[1,this.num_encoder_heads,0,this.encoder_dim_kv];for(let n=0;n<this.num_encoder_layers;++n)e[`past_key_values.${n}.encoder.key`]=new ee("float32",[],t),e[`past_key_values.${n}.encoder.value`]=new ee("float32",[],t);let n=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let t=0;t<this.num_decoder_layers;++t)e[`past_key_values.${t}.decoder.key`]=new ee("float32",[],n),e[`past_key_values.${t}.decoder.value`]=new ee("float32",[],n)}else if(this.config.multi_query){let t=[1,0,2*this.dim_kv];for(let n=0;n<this.num_layers;++n)e[`past_key_values.${n}.key_value`]=new ee("float32",[],t)}else if("bloom"===this.config.model_type){let t=[1*this.num_heads,this.dim_kv,0],n=[1*this.num_heads,0,this.dim_kv];for(let r=0;r<this.num_layers;++r)e[`past_key_values.${r}.key`]=new ee("float32",[],t),e[`past_key_values.${r}.value`]=new ee("float32",[],n)}else{let t=[1,this.num_heads,0,this.dim_kv];for(let n=0;n<this.num_layers;++n)e[`past_key_values.${n}.key`]=new ee("float32",[],t),e[`past_key_values.${n}.value`]=new ee("float32",[],t)}}getStartBeams(e,t,n){return this._getStartBeams(this,e,t,n)}async runBeam(e){return await this._runBeam(this,e)}updateBeam(e,t){return this._updateBeam(e,t)}}class nh{}class nc extends nl{}class nu extends nl{}class nd extends nl{}class nf extends nl{}class np extends nl{}class n_ extends nl{}class ng extends nl{}class nm extends nl{}class ny extends nl{}class nw extends nl{}class nb extends nl{}class nk extends nl{}class nv extends nl{}class nx extends nl{}class nE extends nl{}class nA extends nl{}class nM extends nl{}class nT extends nl{}class nB extends nT{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class nC extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nS extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nI extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nz extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nL extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nU extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nR extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nj extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nF extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nO extends nl{constructor(e,t,n){super(e,t),this.generation_config=n,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 nP extends nl{}class n$ extends nl{}class nN extends nl{}class nq extends nl{}class nD extends nh{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class nW extends nh{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}}class nG extends nl{}class nV extends nl{}class nH extends nl{}class nK extends nl{}class nX extends nh{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class nQ extends nl{}class nY extends nQ{async _call(e){return new nJ(await super._call(e))}}class nJ extends nh{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class nZ extends nl{}class n0 extends nl{}class n1 extends nl{}class n2 extends nl{}let n6=new Map([["bert",["BertModel",class extends nc{}]],["camembert",["CamembertModel",class extends nu{}]],["deberta",["DebertaModel",class extends nd{}]],["deberta-v2",["DebertaV2Model",class extends nf{}]],["mpnet",["MPNetModel",class extends ng{}]],["albert",["AlbertModel",class extends ny{}]],["distilbert",["DistilBertModel",class extends np{}]],["roberta",["RobertaModel",class extends nx{}]],["xlm",["XLMModel",class extends nE{}]],["xlm-roberta",["XLMRobertaModel",class extends nA{}]],["clip",["CLIPModel",class extends nT{}]],["mobilebert",["MobileBertModel",class extends n_{}]],["squeezebert",["SqueezeBertModel",class extends nm{}]],["wav2vec2",["Wav2Vec2Model",class extends n1{}]],["wavlm",["WavLMModel",class extends n2{}]],["detr",["DetrModel",class extends nq{}]],["vit",["ViTModel",class extends nP{}]],["mobilevit",["MobileViTModel",class extends n${}]],["beit",["BeitModel",class extends nN{}]],["deit",["DeiTModel",class extends nG{}]],["resnet",["ResNetModel",class extends nV{}]],["swin",["SwinModel",class extends nH{}]],["yolos",["YolosModel",class extends nK{}]],["sam",["SamModel",nY]]]),n3=new Map([["t5",["T5Model",class extends nw{}]],["mt5",["MT5Model",class extends nb{}]],["bart",["BartModel",class extends nk{}]],["mbart",["MBartModel",class extends nv{}]],["marian",["MarianModel",class extends nZ{}]],["whisper",["WhisperModel",class extends nM{}]],["m2m_100",["M2M100Model",class extends n0{}]]]),n8=new Map([["bloom",["BloomModel",class extends nj{}]],["gpt2",["GPT2Model",class extends nC{}]],["gptj",["GPTJModel",class extends nz{}]],["gpt_bigcode",["GPTBigCodeModel",class extends nL{}]],["gpt_neo",["GPTNeoModel",class extends nS{}]],["gpt_neox",["GPTNeoXModel",class extends nI{}]],["codegen",["CodeGenModel",class extends nU{}]],["llama",["LlamaModel",class extends nR{}]],["mpt",["MptModel",class extends nF{}]],["opt",["OPTModel",class extends nO{}]]]),n4=new Map([["bert",["BertForSequenceClassification",class extends nc{async _call(e){return new rd(await super._call(e))}}]],["camembert",["CamembertForSequenceClassification",class extends nu{async _call(e){return new rd(await super._call(e))}}]],["deberta",["DebertaForSequenceClassification",class extends nd{async _call(e){return new rd(await super._call(e))}}]],["deberta-v2",["DebertaV2ForSequenceClassification",class extends nf{async _call(e){return new rd(await super._call(e))}}]],["mpnet",["MPNetForSequenceClassification",class extends ng{async _call(e){return new rd(await super._call(e))}}]],["albert",["AlbertForSequenceClassification",class extends ny{async _call(e){return new rd(await super._call(e))}}]],["distilbert",["DistilBertForSequenceClassification",class extends np{async _call(e){return new rd(await super._call(e))}}]],["roberta",["RobertaForSequenceClassification",class extends nx{async _call(e){return new rd(await super._call(e))}}]],["xlm",["XLMForSequenceClassification",class extends nE{async _call(e){return new rd(await super._call(e))}}]],["xlm-roberta",["XLMRobertaForSequenceClassification",class extends nA{async _call(e){return new rd(await super._call(e))}}]],["bart",["BartForSequenceClassification",class extends nk{async _call(e){return new rd(await super._call(e))}}]],["mbart",["MBartForSequenceClassification",class extends nv{async _call(e){return new rd(await super._call(e))}}]],["mobilebert",["MobileBertForSequenceClassification",class extends n_{async _call(e){return new rd(await super._call(e))}}]],["squeezebert",["SqueezeBertForSequenceClassification",class extends nm{async _call(e){return new rd(await super._call(e))}}]]]),n5=new Map([["bert",["BertForTokenClassification",class extends nc{async _call(e){return new rf(await super._call(e))}}]],["camembert",["CamembertForTokenClassification",class extends nu{async _call(e){return new rf(await super._call(e))}}]],["deberta",["DebertaForTokenClassification",class extends nd{async _call(e){return new rf(await super._call(e))}}]],["deberta-v2",["DebertaV2ForTokenClassification",class extends nf{async _call(e){return new rf(await super._call(e))}}]],["mpnet",["MPNetForTokenClassification",class extends ng{async _call(e){return new rf(await super._call(e))}}]],["distilbert",["DistilBertForTokenClassification",class extends np{async _call(e){return new rf(await super._call(e))}}]],["roberta",["RobertaForTokenClassification",class extends nx{async _call(e){return new rf(await super._call(e))}}]],["xlm",["XLMForTokenClassification",class extends nE{async _call(e){return new rf(await super._call(e))}}]],["xlm-roberta",["XLMRobertaForTokenClassification",class extends nA{async _call(e){return new rf(await super._call(e))}}]]]),n9=new Map([["t5",["T5ForConditionalGeneration",class extends nw{constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}}]],["mt5",["MT5ForConditionalGeneration",class extends nb{constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}}]],["bart",["BartForConditionalGeneration",class extends nk{constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}}]],["mbart",["MBartForConditionalGeneration",class extends nv{constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}}]],["whisper",["WhisperForConditionalGeneration",class extends nM{requires_attention_mask=!1;main_input_name="input_features";constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}async generate(e,t=null,n=null){if(t=this._get_generation_config(t),t.return_timestamps??=!1,t.return_timestamps&&(n=[new tq(t)]),t.return_token_timestamps&&(t.output_attentions=!0,t.return_dict_in_generate=!0,"translate"===t.task&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),!t.alignment_heads))throw 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.");let r=await super.generate(e,t,n);return t.return_token_timestamps&&t.alignment_heads&&(r.token_timestamps=this._extract_token_timestamps(r,t.alignment_heads,t.num_frames)),r}_extract_token_timestamps(e,t,n=null,r=.02){if(!e.cross_attentions)throw 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 s=this.config.median_filter_width;void 0===s&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),s=7);let i=e.cross_attentions.map(e=>{let r=Array.from({length:this.config.decoder_layers},(t,n)=>es(e.map(e=>e[n]),2)),i=function(e,t=0){return es(e.map(e=>e.unsqueeze(t)),t)}(t.map(([e,t])=>n?r[e].slice(null,t,null,[0,n]):r[e].slice(null,t))),[o,a]=function(e,t=null,n=1,r=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0),r=t/e.data.length,s=Math.sqrt(e.data.reduce((e,t)=>e+(t-r)**2,0)/(e.data.length-n)),i=new ee(e.type,[r],[]),o=new ee(e.type,[s],[]);return[o,i]}t=er(t,e.dims.length);let s=ei(e,t,r),i=e.dims.slice();i[t]=1;let o=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n<e.data.length;++n){let r=0;for(let s=e.dims.length-1,o=n,a=1;s>=0;--s){let n=e.dims[s];if(s!==t){let e=o%n;r+=e*a,a*=i[s]}o=Math.floor(o/n)}o[r]+=(e.data[n]-s.data[r])**2}for(let r=0;r<o.length;++r)o[r]=Math.sqrt(o[r]/(e.dims[t]-n));r||i.splice(t,1);let a=new ee(e.type,o,i);return[a,s]}(i=i.transpose(1,0,2,3),-2,0,!0),l=i.clone();for(let e=0;e<l.dims[0];++e){let t=l[e];for(let n=0;n<t.dims[0];++n){let r=t[n],i=o[e][n][0],l=a[e][n][0];for(let e=0;e<r.dims[0];++e){let t=r[e];for(let e=0;e<t.data.length;++e)t.data[e]=(t.data[e]-l.data[e])/i.data[e];t.data.set(Y(t.data,s))}}}let h=ei(l,1);return h}),o=[e.sequences.length,e.sequences[0].length],a=new ee("float32",new Float32Array(o[0]*o[1]),o);for(let e=0;e<o[0];++e){let t=i[e].neg().squeeze_(0),[n,s]=function(e){let[t,n]=e.dims,r=[t+1,n+1],s=new ee("float32",new Float32Array(r[0]*r[1]).fill(1/0),r),i=new ee("float32",new Float32Array(r[0]*r[1]).fill(-1),r);s[0].data[0]=0;for(let r=1;r<n+1;++r)for(let n=1;n<t+1;++n){let t,o;let a=s[n-1][r-1].item(),l=s[n-1][r].item(),h=s[n][r-1].item();a<l&&a<h?(t=a,o=0):l<a&&l<h?(t=l,o=1):(t=h,o=2),s[n].data[r]=e[n-1][r-1].item()+t,i[n].data[r]=o}let o=t,a=n;i.data.fill(2,0,r[1]);for(let e=0;e<r[0];++e)i[e].data[0]=1;let l=[],h=[];for(;o>0||a>0;){l.push(o-1),h.push(a-1);let e=i[o][a].item();switch(e){case 0:--o,--a;break;case 1:--o;break;case 2:--a;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${a}]. Please file a bug report.`)}}return l.reverse(),h.reverse(),[l,h]}(t),o=u([1],Array.from({length:n.length-1},(e,t)=>n[t+1]-n[t])).map(e=>!!e),l=[];for(let e=0;e<o.length;++e)o[e]&&l.push(s[e]*r);a[e].data.set(l,1)}return a}}]],["marian",["MarianMTModel",class extends nZ{constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}async forward(e){return await t7(this,e)}}]],["m2m_100",["M2M100ForConditionalGeneration",class extends n0{constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,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}async forward(e){return await t7(this,e)}}]]]),n7=new Map([["bloom",["BloomForCausalLM",class extends nj{}]],["gpt2",["GPT2LMHeadModel",class extends nC{}]],["gptj",["GPTJForCausalLM",class extends nz{}]],["gpt_bigcode",["GPTBigCodeForCausalLM",class extends nL{}]],["gpt_neo",["GPTNeoForCausalLM",class extends nS{}]],["gpt_neox",["GPTNeoXForCausalLM",class extends nI{}]],["codegen",["CodeGenForCausalLM",class extends nU{}]],["llama",["LlamaForCausalLM",class extends nR{}]],["mpt",["MptForCausalLM",class extends nF{}]],["opt",["OPTForCausalLM",class extends nO{}]]]),re=new Map([["bert",["BertForMaskedLM",class extends nc{async _call(e){return new rp(await super._call(e))}}]],["camembert",["CamembertForMaskedLM",class extends nu{async _call(e){return new rp(await super._call(e))}}]],["deberta",["DebertaForMaskedLM",class extends nd{async _call(e){return new rp(await super._call(e))}}]],["deberta-v2",["DebertaV2ForMaskedLM",class extends nf{async _call(e){return new rp(await super._call(e))}}]],["mpnet",["MPNetForMaskedLM",class extends ng{async _call(e){return new rp(await super._call(e))}}]],["albert",["AlbertForMaskedLM",class extends ny{async _call(e){return new rp(await super._call(e))}}]],["distilbert",["DistilBertForMaskedLM",class extends np{async _call(e){return new rp(await super._call(e))}}]],["roberta",["RobertaForMaskedLM",class extends nx{async _call(e){return new rp(await super._call(e))}}]],["xlm",["XLMWithLMHeadModel",class extends nE{async _call(e){return new rp(await super._call(e))}}]],["xlm-roberta",["XLMRobertaForMaskedLM",class extends nA{async _call(e){return new rp(await super._call(e))}}]],["mobilebert",["MobileBertForMaskedLM",class extends n_{async _call(e){return new rp(await super._call(e))}}]],["squeezebert",["SqueezeBertForMaskedLM",class extends nm{async _call(e){return new rp(await super._call(e))}}]]]),rt=new Map([["bert",["BertForQuestionAnswering",class extends nc{async _call(e){return new r_(await super._call(e))}}]],["camembert",["CamembertForQuestionAnswering",class extends nu{async _call(e){return new r_(await super._call(e))}}]],["deberta",["DebertaForQuestionAnswering",class extends nd{async _call(e){return new r_(await super._call(e))}}]],["deberta-v2",["DebertaV2ForQuestionAnswering",class extends nf{async _call(e){return new r_(await super._call(e))}}]],["mpnet",["MPNetForQuestionAnswering",class extends ng{async _call(e){return new r_(await super._call(e))}}]],["albert",["AlbertForQuestionAnswering",class extends ny{async _call(e){return new r_(await super._call(e))}}]],["distilbert",["DistilBertForQuestionAnswering",class extends np{async _call(e){return new r_(await super._call(e))}}]],["roberta",["RobertaForQuestionAnswering",class extends nx{async _call(e){return new r_(await super._call(e))}}]],["xlm",["XLMForQuestionAnswering",class extends nE{async _call(e){return new r_(await super._call(e))}}]],["xlm-roberta",["XLMRobertaForQuestionAnswering",class extends nA{async _call(e){return new r_(await super._call(e))}}]],["mobilebert",["MobileBertForQuestionAnswering",class extends n_{async _call(e){return new r_(await super._call(e))}}]],["squeezebert",["SqueezeBertForQuestionAnswering",class extends nm{async _call(e){return new r_(await super._call(e))}}]]]),rn=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",class extends nl{main_input_name="pixel_values";add_decoder_pkv=!1;constructor(e,t,n,r){super(e,t),this.decoder_merged_session=n,this.generation_config=r,this.num_layers=this.config.decoder.n_layer,this.num_heads=this.config.decoder.n_head,this.dim_kv=this.config.decoder.n_embd/this.num_heads}}]]]),rr=new Map([["vit",["ViTForImageClassification",class extends nP{async _call(e){return new rd(await super._call(e))}}]],["mobilevit",["MobileViTForImageClassification",class extends n${async _call(e){return new rd(await super._call(e))}}]],["beit",["BeitForImageClassification",class extends nN{async _call(e){return new rd(await super._call(e))}}]],["deit",["DeiTForImageClassification",class extends nG{async _call(e){return new rd(await super._call(e))}}]],["resnet",["ResNetForImageClassification",class extends nV{async _call(e){return new rd(await super._call(e))}}]],["swin",["SwinForImageClassification",class extends nH{async _call(e){return new rd(await super._call(e))}}]]]),rs=new Map([["detr",["DetrForObjectDetection",class extends nq{async _call(e){return new nD(await super._call(e))}}]],["yolos",["YolosForObjectDetection",class extends nK{async _call(e){return new nX(await super._call(e))}}]]]),ri=new Map([["detr",["DetrForSegmentation",class extends nq{async _call(e){return new nW(await super._call(e))}}]]]),ro=new Map([["sam",["SamModel",nY]]]),ra=new Map([["wav2vec2",["Wav2Vec2ForCTC",class extends n1{async _call(e){return new rg(await super._call(e))}}]],["wavlm",["WavLMForCTC",class extends n2{async _call(e){return new rg(await super._call(e))}}]]]),rl=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",class extends n1{async _call(e){return new rd(await super._call(e))}}]],["wavlm",["WavLMForSequenceClassification",class extends n2{async _call(e){return new rd(await super._call(e))}}]]]),rh=[[n6,t0.EncoderOnly],[n3,t0.EncoderDecoder],[n8,t0.DecoderOnly],[n4,t0.EncoderOnly],[n5,t0.EncoderOnly],[n9,t0.Seq2Seq],[n7,t0.DecoderOnly],[re,t0.EncoderOnly],[rt,t0.EncoderOnly],[rn,t0.Vision2Seq],[rr,t0.EncoderOnly],[ri,t0.EncoderOnly],[rs,t0.EncoderOnly],[ro,t0.EncoderOnly],[ra,t0.EncoderOnly],[rl,t0.EncoderOnly]];for(let[e,t]of rh)for(let[n,r]of e.values())t1.set(n,t),t6.set(r,n),t2.set(n,r);let rc=[["CLIPTextModelWithProjection",nB,t0.EncoderOnly],["CLIPVisionModelWithProjection",class extends nT{static async from_pretrained(e,t={}){return t.model_file_name??="vision_model",super.from_pretrained(e,t)}},t0.EncoderOnly]];for(let[e,t,n]of rc)t1.set(e,n),t6.set(t,e),t2.set(e,t);class ru extends nh{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:s=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=s}}class rd extends nh{constructor({logits:e}){super(),this.logits=e}}class rf extends nh{constructor({logits:e}){super(),this.logits=e}}class rp extends nh{constructor({logits:e}){super(),this.logits=e}}class r_ extends nh{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class rg extends nh{constructor({logits:e}){super(),this.logits=e}}var rm=n(3380);let ry="undefined"!=typeof self;if(ry)s=(e,t)=>{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},o=self.createImageBitmap,i=self.ImageData;else if(rm)o=async e=>{let t=await e.metadata(),n=t.channels,{data:r,info:s}=await e.raw().toBuffer({resolveWithObject:!0}),i=new rb(new Uint8ClampedArray(r),s.width,s.height,s.channels);return void 0!==n&&n!==s.channels&&i.convert(n),i};else throw Error("Unable to load image processing library.");let rw={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"};class rb{_CONTENT_TYPE_MAP={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e,t,n,r){this._update(e,t,n,r)}static async read(e){if(e instanceof rb)return e;if("string"==typeof e||e instanceof String||e instanceof URL)return await this.fromURL(e);throw Error(`Unsupported input type: ${typeof e}`)}static async fromURL(e){let t=await $(e);if(200!==t.status)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(ry){let t=await o(e),n=s(t.width,t.height).getContext("2d");return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=rm(await e.arrayBuffer());return await o(t)}}grayscale(){if(1===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t<this.data.length;t+=this.channels){let r=this.data[t],s=this.data[t+1],i=this.data[t+2];e[n++]=Math.round(.2989*r+.587*s+.114*i)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(3===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t];break;case 4:for(let t=0,n=0;t<this.data.length;t+=4)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(4===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=255;break;case 3:for(let t=0,n=0;t<this.data.length;t+=3)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2],e[n++]=255;break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}async resize(e,t,{resample:n=2}={}){let r=rw[n]??n;if(ry){let n=this.channels,r=this.toCanvas(),i=s(e,t).getContext("2d");return i.drawImage(r,0,0,e,t),new rb(i.getImageData(0,0,e,t).data,e,t,4).convert(n)}{let n=this.toSharp();switch(r){case"box":case"hamming":("box"===r||"hamming"===r)&&(console.warn(`Resampling method ${r} is not yet supported. Using bilinear instead.`),r="bilinear");case"nearest":case"bilinear":case"bicubic":n=n.affine([e/this.width,0,0,t/this.height],{interpolator:r});break;case"lanczos":n=n.resize({width:e,height:t,fit:"fill",kernel:"lanczos3"});break;default:throw Error(`Resampling method ${r} is not supported.`)}return await o(n)}}async pad([e,t,n,r]){if(e=Math.max(e,0),t=Math.max(t,0),n=Math.max(n,0),r=Math.max(r,0),0===e&&0===t&&0===n&&0===r)return this;if(ry){let i=this.channels,o=this.toCanvas(),a=this.width+e+t,l=this.height+n+r,h=s(a,l).getContext("2d");return h.drawImage(o,0,0,this.width,this.height,e,n,a,l),new rb(h.getImageData(0,0,a,l).data,a,l,4).convert(i)}{let s=this.toSharp().extend({left:e,right:t,top:n,bottom:r});return await o(s)}}async center_crop(e,t){if(this.width===e&&this.height===t)return this;let n=(this.width-e)/2,r=(this.height-t)/2;if(ry){let i=this.channels,o=this.toCanvas(),a=s(e,t).getContext("2d"),l=0,h=0,c=0,u=0;return n>=0?l=n:c=-n,r>=0?h=r:u=-r,a.drawImage(o,l,h,e,t,c,u,e,t),new rb(a.getImageData(0,0,e,t).data,e,t,4).convert(i)}{let s=this.toSharp();if(n>=0&&r>=0)s=s.extract({left:Math.floor(n),top:Math.floor(r),width:e,height:t});else if(n<=0&&r<=0){let i=Math.floor(-r),o=Math.floor(-n);s=s.extend({top:i,left:o,right:e-this.width-o,bottom:t-this.height-i})}else{let i=[0,0],o=0;r<0?(i[0]=Math.floor(-r),i[1]=t-this.height-i[0]):o=Math.floor(r);let a=[0,0],l=0;n<0?(a[0]=Math.floor(-n),a[1]=e-this.width-a[0]):l=Math.floor(n),s=s.extend({top:i[0],bottom:i[1],left:a[0],right:a[1]}).extract({left:l,top:o,width:e,height:t})}return await o(s)}}toCanvas(){if(!ry)throw Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),t=s(e.width,e.height),n=new i(e.data,e.width,e.height);return t.getContext("2d").putImageData(n,0,0),t}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,null!==r&&(this.channels=r),this}clone(){return new rb(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}save(e){if(ry){let t=e.split(".").pop().toLowerCase(),n=this._CONTENT_TYPE_MAP[t]??"image/png",r=this.toCanvas(),s=r.toDataURL(n),i=document.createElement("a");i.href=s,i.download=e,i.click(),i.remove()}else if(U.useFS){let t=this.toSharp();t.toFile(e)}else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ry)throw Error("toSharp() is only supported in server-side environments.");return rm(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}}}]); |