uneeq-js 3.6.0 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Uneeq",[],t):"object"==typeof exports?exports.Uneeq=t():e.Uneeq=t()}("undefined"!=typeof self?self:this,(()=>(()=>{var __webpack_modules__={945:function(e,t){var n="undefined"!=typeof self?self:this,r=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n="URLSearchParams"in e,r="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in e,s="ArrayBuffer"in e;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function c(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function p(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new Promise((function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function g(e){var t=new FileReader,n=f(t);return t.readAsArrayBuffer(e),n}function m(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=m(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=m(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=p(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,n,r=p(this);if(r)return r;if(this._bodyBlob)return e=this._bodyBlob,n=f(t=new FileReader),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o&&(this.formData=function(){return this.text().then(w)}),this.json=function(){return this.text().then(JSON.parse)},this}h.prototype.append=function(e,t){e=l(e),t=c(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},h.prototype.delete=function(e){delete this.map[l(e)]},h.prototype.get=function(e){return e=l(e),this.has(e)?this.map[e]:null},h.prototype.has=function(e){return this.map.hasOwnProperty(l(e))},h.prototype.set=function(e,t){this.map[l(e)]=c(t)},h.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},h.prototype.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),d(e)},h.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),d(e)},h.prototype.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),d(e)},r&&(h.prototype[Symbol.iterator]=h.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(e,t){var n,r,i=(t=t||{}).body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new h(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new h(t.headers)),this.method=(r=(n=t.method||this.method||"GET").toUpperCase(),y.indexOf(r)>-1?r:n),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}})),t}function S(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},b.call(v.prototype),b.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},S.error=function(){var e=new S(null,{status:0,statusText:""});return e.type="error",e};var _=[301,302,303,307,308];S.redirect=function(e,t){if(-1===_.indexOf(t))throw new RangeError("Invalid status code");return new S(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,n){return new Promise((function(r,o){var s=new v(e,n);if(s.signal&&s.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function u(){a.abort()}a.onload=function(){var e,t,n={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();t.append(r,i)}})),t)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new S(i,n))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",u),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",u)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=h,e.Request=v,e.Response=S),t.Headers=h,t.Request=v,t.Response=S,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t},744:e=>{"use strict";var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===n}(e)}(e)},n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function r(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function i(e,t,n){return e.concat(t).map((function(e){return r(e,n)}))}function o(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return Object.propertyIsEnumerable.call(e,t)})):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}function a(e,n,u){(u=u||{}).arrayMerge=u.arrayMerge||i,u.isMergeableObject=u.isMergeableObject||t,u.cloneUnlessOtherwiseSpecified=r;var l=Array.isArray(n);return l===Array.isArray(e)?l?u.arrayMerge(e,n,u):function(e,t,n){var i={};return n.isMergeableObject(e)&&o(e).forEach((function(t){i[t]=r(e[t],n)})),o(t).forEach((function(o){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,o)||(s(e,o)&&n.isMergeableObject(t[o])?i[o]=function(e,t){if(!t.customMerge)return a;var n=t.customMerge(e);return"function"==typeof n?n:a}(o,n)(e[o],t[o],n):i[o]=r(t[o],n))})),i}(e,n,u):r(n,u)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,n){return a(e,n,t)}),{})};var u=a;e.exports=u},7:e=>{"use strict";var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}g(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function l(e,t,n,r){var i,o,s,l;if(a(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,l=c,console&&console.warn&&console.warn(l)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=c.bind(r);return i.listener=n,r.wrapFn=i,i}function h(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function g(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(void 0===u)return!1;if("function"==typeof u)r(u,this,t);else{var l=u.length,c=f(u,l);for(n=0;n<l;++n)r(c[n],this,t)}return!0},o.prototype.addListener=function(e,t){return l(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return l(this,e,t,!0)},o.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,r,i,o,s;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return h(this,e,!0)},o.prototype.rawListeners=function(e){return h(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},603:module=>{var t;self,t=()=>(()=>{var __webpack_modules__={8453:(e,t,n)=>{"use strict";n.r(t),n.d(t,{InferenceSession:()=>p,Tensor:()=>d,env:()=>s,registerBackend:()=>o});const r={},i=[],o=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createSessionHandler)throw new TypeError("not a valid backend");{const o=r[e];if(void 0===o)r[e]={backend:t,priority:n};else{if(o.priority>n)return;if(o.priority===n&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){const t=i.indexOf(e);-1!==t&&i.splice(t,1);for(let t=0;t<i.length;t++)if(r[i[t]].priority<=n)return void i.splice(t,0,e);i.push(e)}}},s=new class{constructor(){this.wasm={},this.webgl={},this.webgpu={},this.logLevelInternal="warning"}set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);this.logLevelInternal=e}}get logLevel(){return this.logLevelInternal}},a=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"]]);let l=!1;class c{constructor(e,t,n){let r,i,o;if((()=>{if(!l){l=!0;const e="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from;e&&(a.set("int64",BigInt64Array),u.set(BigInt64Array,"int64")),t&&(a.set("uint64",BigUint64Array),u.set(BigUint64Array,"uint64"))}})(),"string"==typeof e)if(r=e,o=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{const n=a.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t))i=n.from(t);else{if(!(t instanceof n))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);i=t}}else if(o=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");const t=typeof e[0];if("string"===t)r="string",i=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",i=Uint8Array.from(e)}}else{const t=u.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,i=e}if(void 0===o)o=[i.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");const s=(e=>{let t=1;for(let n=0;n<e.length;n++){const r=e[n];if("number"!=typeof r||!Number.isSafeInteger(r))throw new TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t})(o);if(s!==i.length)throw new Error(`Tensor's size(${s}) does not match data length(${i.length}).`);this.dims=o,this.type=r,this.data=i,this.size=s}static bufferToTensor(e,t){if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");const{height:n,width:r}=t,i=t.norm??{mean:255,bias:0};let o,s;o="number"==typeof i.mean?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],s="number"==typeof i.bias?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const a=void 0!==t.bitmapFormat?t.bitmapFormat:"RGBA",u=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",l=n*r,d="RGBA"===u?new Float32Array(4*l):new Float32Array(3*l);let h=4,p=0,f=1,g=2,m=3,b=0,y=l,v=2*l,w=-1;"RGB"===a&&(h=3,p=0,f=1,g=2,m=-1),"RGBA"===u?w=3*l:"RBG"===u?(b=0,v=l,y=2*l):"BGR"===u&&(v=0,y=l,b=2*l);for(let t=0;t<l;t++,p+=h,g+=h,f+=h,m+=h)d[b++]=(e[p]+s[0])/o[0],d[y++]=(e[f]+s[1])/o[1],d[v++]=(e[g]+s[2])/o[2],-1!==w&&-1!==m&&(d[w++]=(e[m]+s[3])/o[3]);return new c("float32",d,"RGBA"===u?[1,4,n,r]:[1,3,n,r])}static async fromImage(e,t){const n="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,r="undefined"!=typeof ImageData&&e instanceof ImageData,i="undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap,o="string"==typeof e;let s,a=t??{};if(n){const n=document.createElement("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");if(null==r)throw new Error("Can not access image data");{let n=e.height,i=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(n=t.resizedHeight,i=t.resizedWidth),void 0!==t){if(a=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");if(a.tensorFormat="RGBA",void 0!==t.height&&t.height!==n)throw new Error("Image input config height doesn't match HTMLImageElement height");if(a.height=n,void 0!==t.width&&t.width!==i)throw new Error("Image input config width doesn't match HTMLImageElement width");a.width=i}else a.tensorFormat="RGBA",a.height=n,a.width=i;r.drawImage(e,0,0),s=r.getImageData(0,0,i,n).data}}else{if(!r){if(i){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");if(void 0!==t.bitmapFormat)throw new Error("Image input config format must be defined for ImageBitmap");const n=document.createElement("canvas").getContext("2d");if(null!=n){const r=e.height,i=e.width;if(n.drawImage(e,0,0,i,r),s=n.getImageData(0,0,i,r).data,void 0!==t){if(void 0!==t.height&&t.height!==r)throw new Error("Image input config height doesn't match ImageBitmap height");if(a.height=r,void 0!==t.width&&t.width!==i)throw new Error("Image input config width doesn't match ImageBitmap width");a.width=i}else a.height=r,a.width=i;return c.bufferToTensor(s,a)}throw new Error("Can not access image data")}if(o)return new Promise(((n,r)=>{const i=document.createElement("canvas"),o=i.getContext("2d");if(!e||!o)return r();const s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=()=>{i.width=s.width,i.height=s.height,o.drawImage(s,0,0,i.width,i.height);const e=o.getImageData(0,0,i.width,i.height);if(void 0!==t){if(void 0!==t.height&&t.height!==i.height)throw new Error("Image input config height doesn't match height");if(a.height=i.height,void 0!==t.width&&t.width!==i.width)throw new Error("Image input config width doesn't match width");a.width=i.width}else a.height=i.height,a.width=i.width;n(c.bufferToTensor(e.data,a))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{const n="RGBA";let r,i;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,i=t.resizedWidth):(r=e.height,i=e.width),void 0!==t){if(a=t,void 0!==t.bitmapFormat&&t.bitmapFormat!==n)throw new Error("Image input config format must be RGBA for ImageData");a.bitmapFormat="RGBA"}else a.bitmapFormat="RGBA";if(a.height=r,a.width=i,void 0!==t){const t=document.createElement("canvas");t.width=i,t.height=r;const n=t.getContext("2d");if(null==n)throw new Error("Can not access image data");n.putImageData(e,0,0),s=n.getImageData(0,0,i,r).data}else s=e.data}}if(void 0!==s)return c.bufferToTensor(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")}toDataURL(e){const t=document.createElement("canvas");t.width=this.dims[3],t.height=this.dims[2];const n=t.getContext("2d");if(null!=n){let r,i;void 0!==e?.tensorLayout&&"NHWC"===e.tensorLayout?(r=this.dims[2],i=this.dims[3]):(r=this.dims[3],i=this.dims[2]);const o=void 0!==e?.format?e.format:"RGB",s=e?.norm;let a,u;void 0===s||void 0===s.mean?a=[255,255,255,255]:"number"==typeof s.mean?a=[s.mean,s.mean,s.mean,s.mean]:(a=[s.mean[0],s.mean[1],s.mean[2],0],void 0!==s.mean[3]&&(a[3]=s.mean[3])),void 0===s||void 0===s.bias?u=[0,0,0,0]:"number"==typeof s.bias?u=[s.bias,s.bias,s.bias,s.bias]:(u=[s.bias[0],s.bias[1],s.bias[2],0],void 0!==s.bias[3]&&(u[3]=s.bias[3]));const l=i*r;let c=0,d=l,h=2*l,p=-1;"RGBA"===o?(c=0,d=l,h=2*l,p=3*l):"RGB"===o?(c=0,d=l,h=2*l):"RBG"===o&&(c=0,h=l,d=2*l);for(let e=0;e<i;e++)for(let t=0;t<r;t++){const r=(this.data[c++]-u[0])*a[0],i=(this.data[d++]-u[1])*a[1],o=(this.data[h++]-u[2])*a[2],s=-1===p?255:(this.data[p++]-u[3])*a[3];n.fillStyle="rgba("+r+","+i+","+o+","+s+")",n.fillRect(t,e,1,1)}return t.toDataURL()}throw new Error("Can not access image data")}toImageData(e){const t=document.createElement("canvas").getContext("2d");let n;if(null==t)throw new Error("Can not access image data");{let r,i,o;void 0!==e?.tensorLayout&&"NHWC"===e.tensorLayout?(r=this.dims[2],i=this.dims[1],o=this.dims[3]):(r=this.dims[3],i=this.dims[2],o=this.dims[1]);const s=void 0!==e&&void 0!==e.format?e.format:"RGB",a=e?.norm;let u,l;void 0===a||void 0===a.mean?u=[255,255,255,255]:"number"==typeof a.mean?u=[a.mean,a.mean,a.mean,a.mean]:(u=[a.mean[0],a.mean[1],a.mean[2],255],void 0!==a.mean[3]&&(u[3]=a.mean[3])),void 0===a||void 0===a.bias?l=[0,0,0,0]:"number"==typeof a.bias?l=[a.bias,a.bias,a.bias,a.bias]:(l=[a.bias[0],a.bias[1],a.bias[2],0],void 0!==a.bias[3]&&(l[3]=a.bias[3]));const c=i*r;if(void 0!==e){if(void 0!==e.height&&e.height!==i)throw new Error("Image output config height doesn't match tensor height");if(void 0!==e.width&&e.width!==r)throw new Error("Image output config width doesn't match tensor width");if(void 0!==e.format&&4===o&&"RGBA"!==e.format||3===o&&"RGB"!==e.format&&"BGR"!==e.format)throw new Error("Tensor format doesn't match input tensor dims")}const d=4;let h=0,p=1,f=2,g=3,m=0,b=c,y=2*c,v=-1;"RGBA"===s?(m=0,b=c,y=2*c,v=3*c):"RGB"===s?(m=0,b=c,y=2*c):"RBG"===s&&(m=0,y=c,b=2*c),n=t.createImageData(r,i);for(let e=0;e<i*r;h+=d,p+=d,f+=d,g+=d,e++)n.data[h]=(this.data[m++]-l[0])*u[0],n.data[p]=(this.data[b++]-l[1])*u[1],n.data[f]=(this.data[y++]-l[2])*u[2],n.data[g]=-1===v?255:(this.data[v++]-l[3])*u[3]}return n}reshape(e){return new c(this.type,this.data,e)}}const d=c;class h{constructor(e){this.handler=e}async run(e,t,n){const r={};let i={};if("object"!=typeof e||null===e||e instanceof d||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof d)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else{let e=!1;const s=Object.getOwnPropertyNames(t);for(const n of this.outputNames)if(-1!==s.indexOf(n)){const i=t[n];(null===i||i instanceof d)&&(e=!0,o=!1,r[n]=i)}if(e){if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else i=t}}else if(void 0!==t)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of this.inputNames)if(void 0===e[t])throw new Error(`input '${t}' is missing in 'feeds'.`);if(o)for(const e of this.outputNames)r[e]=null;const s=await this.handler.run(e,r,i),a={};for(const e in s)Object.hasOwnProperty.call(s,e)&&(a[e]=new d(s[e].type,s[e].data,s[e].dims));return a}static async create(e,t,n,o){let s,a={};if("string"==typeof e){if(s=e,"object"==typeof t&&null!==t)a=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,"object"==typeof t&&null!==t)a=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else{if(!(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{const r=e;let i=0,u=e.byteLength;if("object"==typeof t&&null!==t)a=t;else if("number"==typeof t){if(i=t,!Number.isSafeInteger(i))throw new RangeError("'byteOffset' must be an integer.");if(i<0||i>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(u=e.byteLength-i,"number"==typeof n){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||i+u>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-i}].`);if("object"==typeof o&&null!==o)a=o;else if(void 0!==o)throw new TypeError("'options' must be an object.")}else if(void 0!==n)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw new TypeError("'options' must be an object.");s=new Uint8Array(r,i,u)}}const u=(a.executionProviders||[]).map((e=>"string"==typeof e?e:e.name)),l=await(async e=>{const t=0===e.length?i:e,n=[];for(const e of t){const t=r[e];if(t){if(t.initialized)return t.backend;if(t.aborted)continue;const r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init()),await t.initPromise,t.initialized=!0,t.backend}catch(i){r||n.push({name:e,err:i}),t.aborted=!0}finally{delete t.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`)})(u),c=await l.createSessionHandler(s,a);return new h(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}const p=h},5716:(e,t,n)=>{"use strict";t.R=void 0;const r=n(6027),i=n(1723);t.R=new class{async init(){}async createSessionHandler(e,t){const n=new r.Session(t);return await n.loadModel(e),new i.OnnxjsSessionHandler(n)}}},2818:(e,t,n)=>{"use strict";t.c8=t.rX=void 0;const r=n(8453),i=n(5381),o=n(9544),s=n(6640);t.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=!0),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=!1),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const e="undefined"==typeof navigator?(0,i.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},t.c8=new class{async init(){(0,t.rX)(),await(0,o.initWasm)()}async createSessionHandler(e,t){const n=new s.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(e,t),Promise.resolve(n)}}},1057:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(8453),t);const o=n(8453);{const e=n(5716).R;(0,o.registerBackend)("webgl",e,-10)}{const e=n(2818).c8;(0,o.registerBackend)("cpu",e,10),(0,o.registerBackend)("wasm",e,10),(0,o.registerBackend)("xnnpack",e,9)}},4910:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAttributeWithCacheKey=void 0;class n{constructor(e){Object.assign(this,e)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this._cacheKey}}t.createAttributeWithCacheKey=e=>new n(e)},6874:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Attribute=void 0;const r=n(1446),i=n(1287),o=n(9240),s=n(7273);var a=i.onnxruntime.experimental.fbs;class u{constructor(e){if(this._attributes=new Map,null!=e){for(const t of e)t instanceof r.onnx.AttributeProto?this._attributes.set(t.name,[u.getValue(t),u.getType(t)]):t instanceof a.Attribute&&this._attributes.set(t.name(),[u.getValue(t),u.getType(t)]);if(this._attributes.size<e.length)throw new Error("duplicated attribute names")}}set(e,t,n){this._attributes.set(e,[n,t])}delete(e){this._attributes.delete(e)}getFloat(e,t){return this.get(e,"float",t)}getInt(e,t){return this.get(e,"int",t)}getString(e,t){return this.get(e,"string",t)}getTensor(e,t){return this.get(e,"tensor",t)}getFloats(e,t){return this.get(e,"floats",t)}getInts(e,t){return this.get(e,"ints",t)}getStrings(e,t){return this.get(e,"strings",t)}getTensors(e,t){return this.get(e,"tensors",t)}get(e,t,n){const r=this._attributes.get(e);if(void 0===r){if(void 0!==n)return n;throw new Error(`required attribute not found: ${e}`)}if(r[1]!==t)throw new Error(`type mismatch: expected ${t} but got ${r[1]}`);return r[0]}static getType(e){const t=e instanceof r.onnx.AttributeProto?e.type:e.type();switch(t){case r.onnx.AttributeProto.AttributeType.FLOAT:return"float";case r.onnx.AttributeProto.AttributeType.INT:return"int";case r.onnx.AttributeProto.AttributeType.STRING:return"string";case r.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case r.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case r.onnx.AttributeProto.AttributeType.INTS:return"ints";case r.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case r.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[t]}`)}}static getValue(e){const t=e instanceof r.onnx.AttributeProto?e.type:e.type();if(t===r.onnx.AttributeProto.AttributeType.GRAPH||t===r.onnx.AttributeProto.AttributeType.GRAPHS)throw new Error("graph attribute is not supported yet");const n=this.getValueNoCheck(e);if(t===r.onnx.AttributeProto.AttributeType.INT&&s.LongUtil.isLong(n))return s.LongUtil.longToNumber(n);if(t===r.onnx.AttributeProto.AttributeType.INTS){const e=n,t=new Array(e.length);for(let n=0;n<e.length;n++){const r=e[n];t[n]=s.LongUtil.longToNumber(r)}return t}if(t===r.onnx.AttributeProto.AttributeType.TENSOR)return e instanceof r.onnx.AttributeProto?o.Tensor.fromProto(n):o.Tensor.fromOrtTensor(n);if(t===r.onnx.AttributeProto.AttributeType.TENSORS){if(e instanceof r.onnx.AttributeProto)return n.map((e=>o.Tensor.fromProto(e)));if(e instanceof a.Attribute)return n.map((e=>o.Tensor.fromOrtTensor(e)))}if(t===r.onnx.AttributeProto.AttributeType.STRING&&e instanceof r.onnx.AttributeProto){const e=n;return(0,s.decodeUtf8String)(e)}return t===r.onnx.AttributeProto.AttributeType.STRINGS&&e instanceof r.onnx.AttributeProto?n.map(s.decodeUtf8String):n}static getValueNoCheck(e){return e instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(e):this.getValueNoCheckFromOrtFormat(e)}static getValueNoCheckFromOnnxFormat(e){switch(e.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return e.f;case r.onnx.AttributeProto.AttributeType.INT:return e.i;case r.onnx.AttributeProto.AttributeType.STRING:return e.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return e.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return e.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return e.floats;case r.onnx.AttributeProto.AttributeType.INTS:return e.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return e.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return e.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return e.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[e.type]}`)}}static getValueNoCheckFromOrtFormat(e){switch(e.type()){case a.AttributeType.FLOAT:return e.f();case a.AttributeType.INT:return e.i();case a.AttributeType.STRING:return e.s();case a.AttributeType.TENSOR:return e.t();case a.AttributeType.GRAPH:return e.g();case a.AttributeType.FLOATS:return e.floatsArray();case a.AttributeType.INTS:{const t=[];for(let n=0;n<e.intsLength();n++)t.push(e.ints(n));return t}case a.AttributeType.STRINGS:{const t=[];for(let n=0;n<e.stringsLength();n++)t.push(e.strings(n));return t}case a.AttributeType.TENSORS:{const t=[];for(let n=0;n<e.tensorsLength();n++)t.push(e.tensors(n));return t}default:throw new Error(`unsupported attribute type: ${a.AttributeType[e.type()]}`)}}}t.Attribute=u},1975:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveBackend=t.backend=void 0;const r=n(4418),i=new Map;async function o(e){const n=t.backend;if(void 0!==n[e]&&function(e){const t=e;return"initialize"in t&&"function"==typeof t.initialize&&"createSessionHandler"in t&&"function"==typeof t.createSessionHandler&&"dispose"in t&&"function"==typeof t.dispose}(n[e])){const t=n[e];let r=t.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return i.set(e,t),t}}t.backend={webgl:new r.WebGLBackend},t.resolveBackend=async function e(t){if(!t)return e(["webgl"]);{const e="string"==typeof t?[t]:t;for(const t of e){const e=i.get(t);if(e)return e;const n=await o(t);if(n)return n}}throw new Error("no available backend to use")}},4418:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLBackend=void 0;const r=n(8453),i=n(1315),o=n(2171),s=n(3389);t.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(e){r.env.webgl.contextId=e}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){r.env.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(e){r.env.webgl.textureCacheMode=e}get pack(){return r.env.webgl.pack}set pack(e){r.env.webgl.pack=e}get async(){return r.env.webgl.async}set async(e){r.env.webgl.async=e}initialize(){try{return this.glContext=(0,s.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=!1),"boolean"!=typeof this.async&&(this.async=!1),i.Logger.setWithEnv(r.env),i.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return i.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new o.WebGLSessionHandler(this,e)}dispose(){this.glContext.dispose()}}},6859:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CoordsGlslLib=void 0;const r=n(7273),i=n(1997),o=n(6757),s=n(7618),a=n(432);class u extends i.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ")}}coordsToOffset(){return{coordsToOffset:new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ")}}getOutputSamplingSnippet(){const e=this.context.outputTextureLayout;return e.isPacked?this.getPackedOutputSamplingSnippet(e):this.getUnpackedOutputSamplingSnippet(e)}getPackedOutputSamplingSnippet(e){const t=e.unpackedShape,n=[e.width,e.height],r={},s="getOutputCoords";switch(t.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(t,n);break;case 2:r[s]=this.getOutputPacked2DCoords(t,n);break;case 3:r[s]=this.getOutputPacked3DCoords(t,n);break;default:r[s]=this.getOutputPackedNDCoords(t,n)}const a=`\n void setOutput(vec4 val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = val;\n }\n `;return r.floatTextureSetRGBA=new i.GlslLibRoutine(a),r}getUnpackedOutputSamplingSnippet(e){const t=e.unpackedShape,n=[e.width,e.height],r={},s="getOutputCoords";switch(t.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(t,n);break;case 2:r[s]=this.getOutputUnpacked2DCoords(t,n);break;case 3:r[s]=this.getOutputUnpacked3DCoords(t,n);break;case 4:r[s]=this.getOutputUnpacked4DCoords(t,n);break;case 5:r[s]=this.getOutputUnpacked5DCoords(t,n);break;case 6:r[s]=this.getOutputUnpacked6DCoords(t,n);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}const a=`\n void setOutput(float val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n }\n `;return r.floatTextureSetR=new i.GlslLibRoutine(a),r}getOutputScalarCoords(){return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ")}getOutputPacked1DCoords(e,t){const n=t;let r="";return 1===n[0]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.y * ${n[1]}.0);\n }\n `,new i.GlslLibRoutine(r)):1===n[1]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.x * ${n[0]}.0);\n }\n `,new i.GlslLibRoutine(r)):(r=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n }\n `,new i.GlslLibRoutine(r))}getOutputPacked2DCoords(e,t){let n="";if(r.ArrayUtil.arraysEqual(e,t))return n=`\n ivec2 getOutputCoords() {\n return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]}));\n }\n `,new i.GlslLibRoutine(n);const o=t,s=Math.ceil(e[1]/2);return n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${o[0]}, ${o[1]}));\n\n int index = resTexRC.y * ${o[0]} + resTexRC.x;\n\n // reverse r and c order for packed texture\n int r = imod(index, ${s}) * 2;\n int c = 2 * (index / ${s});\n\n return ivec2(r, c);\n }\n `,new i.GlslLibRoutine(n)}getOutputPacked3DCoords(e,t){const n=[t[0],t[1]],r=Math.ceil(e[2]/2),o=r*Math.ceil(e[1]/2),s=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec3(b, r, c);\n }\n `;return new i.GlslLibRoutine(s)}getOutputPackedNDCoords(e,t){const n=[t[0],t[1]],r=Math.ceil(e[e.length-1]/2),o=r*Math.ceil(e[e.length-2]/2);let s=o,a="",u="b, r, c";for(let t=2;t<e.length-1;t++)s*=e[e.length-t-1],a=`\n int b${t} = index / ${s};\n index -= b${t} * ${s};\n `+a,u=`b${t}, `+u;const l=`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n ${a}\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec${e.length}(${u});\n }\n `;return new i.GlslLibRoutine(l)}getOutputUnpacked1DCoords(e,t){const n=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.y * ${t[0]} + resTexRC.x;\n }\n `;return new i.GlslLibRoutine(n)}getOutputUnpacked2DCoords(e,t){const n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `;return new i.GlslLibRoutine(n)}getOutputUnpacked3DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec3(r, c, d);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked4DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d","d2"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec4(r, c, d, d2);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked5DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d","d2","d3"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec5(r, c, d, d2, d3);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked6DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d","d2","d3","d4"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec6(r, c, d, d2, d3, d4);\n }\n `,new i.GlslLibRoutine(n)}getCommonUtilFuncs(){const e={};let t="uvFromFlat";e[t]=new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "),t="packedUVfrom1D",e[t]=new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="packedUVfrom2D",e[t]=new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="packedUVfrom3D",e[t]=new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="sampleTexture";const n=(0,o.getGlsl)(this.context.glContext.version);return e[t]=new i.GlslLibRoutine(`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }`),e}getInputsSamplingSnippets(){const e={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach(((n,r)=>{const i=this.context.inputTextureLayouts[r],o=(0,a.generateShaderFuncNameFromInputSamplerName)(n);i.isPacked?e[o]=this.getPackedSamplerFromInput(o,n,i):e[o]=this.getUnpackedSamplerFromInput(o,n,i);const s=(0,a.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);i.unpackedShape.length<=t.unpackedShape.length&&(i.isPacked?e[s]=this.getPackedSamplerAtOutputCoords(s,i,t,n):e[s]=this.getUnpackedSamplerAtOutputCoords(s,i,t,n))})),e}getPackedSamplerAtOutputCoords(e,t,n,o){const s=t.unpackedShape,u=n.unpackedShape,l=o,c=(0,a.generateShaderFuncNameFromInputSamplerName)(l),d=s.length,h=u.length,p=r.BroadcastUtil.getBroadcastDims(s,u),f=(0,a.getCoordsDataType)(h),g=h-d;let m;const b=(0,a.getGlChannels)();m=0===d?"":h<2&&p.length>=1?"coords = 0;":p.map((e=>`coords.${b[e+g]} = 0;`)).join("\n");let y="";y=h<2&&d>0?"coords":s.map(((e,t)=>`coords.${b[t+g]}`)).join(", ");let v="return outputValue;";const w=1===r.ShapeUtil.size(s),S=1===r.ShapeUtil.size(u);if(1!==d||w||S){if(w&&!S)v=1===h?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(p.length){const e=d-2,t=d-1;p.indexOf(e)>-1&&p.indexOf(t)>-1?v="return vec4(outputValue.x);":p.indexOf(e)>-1?v="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":p.indexOf(t)>-1&&(v="return vec4(outputValue.xx, outputValue.zz);")}}else v="\n return vec4(outputValue.xy, outputValue.xy);\n ";const _=`\n vec4 ${e}() {\n ${f} coords = getOutputCoords();\n \n int lastDim = coords.${b[h-1]};\n coords.${b[h-1]} = coords.${b[h-2]};\n coords.${b[h-2]} = lastDim;\n \n ${m}\n vec4 outputValue = ${c}(${y});\n ${v}\n }\n `;return new i.GlslLibRoutine(_,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(e,t,n,o){const s=[n.width,n.height],u=[t.width,t.height],l=t.unpackedShape.length,c=n.unpackedShape.length,d=t.unpackedShape,h=n.unpackedShape,p=(0,a.generateShaderFuncNameFromInputSamplerName)(o);if(l===c&&r.ArrayUtil.arraysEqual(u,s)){const t=`\n float ${e}() {\n return sampleTexture(${o}, TexCoords);\n }\n `;return new i.GlslLibRoutine(t,["coordinates.sampleTexture"])}const f=(0,a.getCoordsDataType)(c),g=r.BroadcastUtil.getBroadcastDims(d,h),m=c-l;let b;const y=(0,a.getGlChannels)();b=0===l?"":c<2&&g.length>=1?"coords = 0;":g.map((e=>`coords.${y[e+m]} = 0;`)).join("\n");let v="";v=c<2&&l>0?"coords":t.unpackedShape.map(((e,t)=>`coords.${y[t+m]}`)).join(", ");const w=`\n float ${e}() {\n ${f} coords = getOutputCoords();\n ${b}\n return ${p}(${v});\n }\n `;return new i.GlslLibRoutine(w,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(e,t,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(e,t);case 1:return this.getPackedSampler1D(e,t,n);case 2:return this.getPackedSampler2D(e,t,n);case 3:return this.getPackedSampler3D(e,t,n);default:return this.getPackedSamplerND(e,t,n)}}getUnpackedSamplerFromInput(e,t,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(e,t,n);case 1:return this.getUnpackedSampler1D(e,t,n);case 2:return this.getUnpackedSampler2D(e,t,n);case 3:return this.getUnpackedSampler3D(e,t,n);case 4:return this.getUnpackedSampler4D(e,t,n);case 5:return this.getUnpackedSampler5D(e,t,n);case 6:return this.getUnpackedSampler6D(e,t,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(e,t){const n=`\n vec4 ${e}() {\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR);\n }\n `;return new i.GlslLibRoutine(n)}getPackedSampler1D(e,t,n){const r=[n.width,n.height],s=[r[1],r[0]],a=(0,o.getGlsl)(this.context.glContext.version),u=`vec4 ${e}(int index) {\n vec2 uv = packedUVfrom1D(\n ${s[0]}, ${s[1]}, index);\n return ${a.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(u,["coordinates.packedUVfrom1D"])}getPackedSampler2D(e,t,n){const s=n.unpackedShape,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=a[0],c=a[1];if(null!=a&&r.ArrayUtil.arraysEqual(s,a)){const n=`vec4 ${e}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${l}.0);\n return ${u.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(n)}const d=a,h=Math.ceil(s[1]/2),p=`vec4 ${e}(int row, int col) {\n vec2 uv = packedUVfrom2D(${d[1]}, ${d[0]}, ${h}, row, col);\n return ${u.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(p,["coordinates.packedUVfrom2D"])}getPackedSampler3D(e,t,n){const r=n.unpackedShape,s=[n.width,n.height],u=[s[0],s[1]],l=(0,o.getGlsl)(this.context.glContext.version);if(1===r[0]){const o=r.slice(1),s=[1,2],u=(0,a.squeezeInputShape)(r,o),l=["b","row","col"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=u;const d=this.getPackedSamplerFromInput(e,t,c),h=`${d.routineBody}\n vec4 ${e}(int b, int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(l,s)});\n } `;return new i.GlslLibRoutine(h,d.dependencies)}const c=u[0],d=u[1],h=Math.ceil(r[2]/2),p=`vec4 ${e}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${d}, ${c}, ${h*Math.ceil(r[1]/2)}, ${h}, b, row, col);\n return ${l.texture2D}(${t}, uv);}`;return new i.GlslLibRoutine(p,["coordinates.packedUVfrom3D"])}getPackedSamplerND(e,t,n){const r=n.unpackedShape,s=r.length,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=[a[0],a[1]],c=l[1],d=l[0],h=Math.ceil(r[s-1]/2);let p=h*Math.ceil(r[s-2]/2),f="int b, int row, int col",g=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let e=2;e<s-1;e++)f=`int b${e}, `+f,p*=r[s-e-1],g=`b${e} * ${p} + `+g;const m=`vec4 ${e}(${f}) {\n int index = ${g};\n int texR = index / ${d};\n int texC = index - texR * ${d};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${c});\n return ${u.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(m)}getUnpackedSamplerScalar(e,t,n){const[r,o]=[n.width,n.height];if(1===r&&1===o){const n=`\n float ${e}() {\n return sampleTexture(${t}, halfCR);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${e}() {\n int offset_${t} = coordsToOffset(TexCoords, ${r}, ${o});\n vec2 uv = uvFromFlat(${r}, ${o}, offset_${t});\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler1D(e,t,n){const r=n.width,o=n.height;if(1===o&&1===r){const n=`\n float ${e}(int index) {\n return sampleTexture(${t}, halfCR);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===o){const n=`\n float ${e}(int index) {\n vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===r){const n=`\n float ${e}(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${e}(int index) {\n vec2 uv = uvFromFlat(${r}, ${o}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(e,t,n){const o=n.unpackedShape,u=[n.height,n.width];if(null!=u&&r.ArrayUtil.arraysEqual(o,u)){const n=`\n float ${e}(int row, int col) {\n vec2 uv = (vec2(row, col) + halfCR) / vec2(${u[1]}.0, ${u[0]}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const{newShape:l,keptDims:c}=(0,s.squeezeShape)(o),d=l;if(d.length<o.length){const r=(0,a.squeezeInputShape)(o,d),s=JSON.parse(JSON.stringify(n));s.unpackedShape=r;const u=["col","row"],l=`\n ${this.getUnpackedSamplerFromInput(e,t,s).routineBody}\n float ${e}(int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(u,c)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture"])}const h=u[1],p=u[0];if(1===p){const n=`\n float ${e}(int row, int col) {\n int offset_${t} = coordsToOffset(TexCoords, ${h}, ${p});\n float index = dot(vec3(row, col, offset_${t}), vec3(${o[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}if(1===h){const n=`\n float ${e}(int row, int col) {\n int offset_${t} = coordsToOffset(TexCoords, ${h}, ${p});\n float index = dot(vec3(row, col, offset_${t}), vec3(${o[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}const f=`\n float ${e}(int row, int col) {\n int index = col * ${o[1]} + row;\n vec2 uv = uvFromFlat(${h}, ${p}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(e,t,n){const r=n.unpackedShape,o=r[1]*r[2],u=r[2],{newShape:l,keptDims:c}=(0,s.squeezeShape)(r),d=l;if(d.length<r.length){const o=(0,a.squeezeInputShape)(r,d),s=["batch","col","row"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=this.getUnpackedSamplerFromInput(e,t,u),h=c.reverse(),p=`\n ${l.routineBody}\n float ${e}(int batch, int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new i.GlslLibRoutine(p,l.dependencies)}const h=`\n float ${e}(int depth, int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = depth * ${o} + col * ${u} + row;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(h,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler4D(e,t,n){const r=n.unpackedShape,o=r[3],s=r[2]*o,a=`\n float ${e}(int row, int col, int depth, int depth2) {\n int index = row * ${r[1]*s} + col * ${s} +\n depth2 * ${o} + depth;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(a,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(e,t,n){const r=n.unpackedShape,o=r[4],u=r[3]*o,l=r[2]*u,c=r[1]*l,{newShape:d,keptDims:h}=(0,s.squeezeShape)(r);if(d.length<r.length){const o=(0,a.squeezeInputShape)(r,d),s=["row","col","depth","depth2","depth3"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=`\n ${this.getUnpackedSamplerFromInput(e,t,u).routineBody}\n float ${e}(int row, int col, int depth, int depth2, int depth3) {\n return ${e}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const p=`\n float ${e}(int row, int col, int depth, int depth2, int depth3) {\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth3 * ${o} + depth2;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(p,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(e,t,n){const r=n.unpackedShape,o=r[5],u=r[4]*o,l=r[3]*u,c=r[2]*l,d=r[1]*c,{newShape:h,keptDims:p}=(0,s.squeezeShape)(r);if(h.length<r.length){const o=(0,a.squeezeInputShape)(r,h),s=["row","col","depth","depth2","depth3","depth4"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=`\n ${this.getUnpackedSamplerFromInput(e,t,u).routineBody}\n float ${e}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${e}(${(0,a.getSqueezedParams)(s,p)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const f=`\n float ${e}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = row * ${d} + col * ${c} + depth * ${l} +\n depth2 * ${u} + depth3 * ${o} + depth4;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}toVec(){const e=this.context.outputTextureLayout,t=e.shape.length,n=e.strides,r=e.width,o=e.height,s=[];for(let e=0;e<t-1;++e)s.push(`\n c[${e}] = offset / ${n[e]};`),s.push(`\n offset -= c[${e}] * ${n[e]};`);s.push(`\n c[${t-1}] = offset;`);const a=`\n void toVec(vec2 texCoords, out int c[${t}]) {\n int offset = coordsToOffset(texCoords, ${r}, ${o});\n ${s.join("")}\n }\n void toVec(int offset, out int c[${t}]) {\n ${s.join("")}\n }\n `;return{toVec:new i.GlslLibRoutine(a,["coordinates.coordsToOffset"])}}valueFrom(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const r=this.context.inputTextureLayouts[n],o=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let s=`_${t}`;e[s]=new i.GlslLibRoutine(this.getValueFromSingle(t,o,r.width,r.height,!1),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),s+="_T",e[s]=new i.GlslLibRoutine(this.getValueFromSingle(t,o,r.width,r.height,!0),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])})),e}getValueFromSingle(e,t,n,r,i){let s=`_${e}`;return i&&(s+="_T"),`\n float ${s}(int m[${t}]) {\n int offset = indicesToOffset${s}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n float value = getColorAsFloat(${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, coords));\n return value;\n }\n `}getPackedValueFrom(e,t,n,r,i){let s=`_${e}_Pack`;return i&&(s+="_T"),`\n vec4 ${s}(int m[${t}]) {\n int offset = indicesToOffset_${e}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, coords);\n }\n `}}t.CoordsGlslLib=u},1997:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TopologicalSortGlslRoutines=t.GlslLibRoutineNode=t.GlslLibRoutine=t.GlslLib=t.GlslContext=t.FunctionType=void 0,(n=t.FunctionType||(t.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",t.GlslContext=class{constructor(e,t,n,r){this.glContext=e,this.programInfo=t,this.inputTextureLayouts=n,this.outputTextureLayout=r}},t.GlslLib=class{constructor(e){this.context=e}},t.GlslLibRoutine=class{constructor(e,t){this.routineBody=e,this.dependencies=t}},t.GlslLibRoutineNode=class{constructor(e,t,n){this.name=e,this.dependencies=n||[],t&&(this.routineBody=t)}addDependency(e){e&&this.dependencies.push(e)}},t.TopologicalSortGlslRoutines=class{static returnOrderedNodes(e){if(!e||0===e.length)return[];if(1===e.length)return e;const t=new Set,n=new Set,r=new Array;return this.createOrderedNodes(e,t,n,r),r}static createOrderedNodes(e,t,n,r){for(let i=0;i<e.length;++i)this.dfsTraverse(e[i],t,n,r)}static dfsTraverse(e,t,n,r){if(!e||n.has(e.name))return;if(t.has(e.name))throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");t.add(e.name);const i=e.dependencies;if(i&&i.length>0)for(let e=0;e<i.length;++e)this.dfsTraverse(i[e],t,n,r);r.push(e),n.add(e.name),t.delete(e.name)}}},1371:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingGlslLib=void 0;const r=n(1997);class i extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ")}}encodeUint8(){const e=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n highp vec4 encode(highp float f) {\n highp float F = abs(f);\n highp float Sign = step(0.0,-f);\n highp float Exponent = floor(log2(F));\n highp float Mantissa = (exp2(- Exponent) * F);\n Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n highp vec4 rgba;\n rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));\n rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n ${e}\n rgba = rgba / 255.0; // values need to be normalized to [0,1]\n return rgba;\n }\n `)}}decodeUint8(){const e=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n highp float decode(highp vec4 rgba) {\n rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n ${e}\n highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n return Result;\n }\n `)}}static isLittleEndian(){const e=new ArrayBuffer(4),t=new Uint32Array(e),n=new Uint8Array(e);if(t[0]=3735928559,239===n[0])return!0;if(222===n[0])return!1;throw new Error("unknown endianness")}}t.EncodingGlslLib=i},2691:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FragColorGlslLib=void 0;const r=n(1997),i=n(6757);class o extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const e=(0,i.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n void setFragColor(float value) {\n ${e.output} = encode(value);\n }\n `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ",["encoding.decode"])}}}t.FragColorGlslLib=o},3878:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;t.replaceInlines=function(e){const t={};let r;for(;null!==(r=n.exec(e));){const e=r[3].split(",").map((e=>{const t=e.trim().split(" ");return t&&2===t.length?{type:t[0],name:t[1]}:null})).filter((e=>null!==e));t[r[2]]={params:e,body:r[4]}}for(const n in t){const i="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),o=new RegExp(i,"gm");for(;null!==(r=o.exec(e));){const i=r[1],o=r[2],s=r[3].split(","),a=i?`${i} ${o};`:"";let u=t[n].body,l="";t[n].params.forEach(((e,t)=>{e&&(l+=`${e.type} ${e.name} = ${s[t]};\n`)})),u=`${l}\n ${u}`,u=u.replace("return",`${o} = `);const c=`\n ${a}\n {\n ${u}\n }\n `;e=e.replace(r[0],c)}}return e.replace(n,"")}},8897:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GlslPreprocessor=void 0;const r=n(1997),i=n(3878),o=n(1248),s=n(6757);t.GlslPreprocessor=class{constructor(e,t,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(e,t,n,i),Object.keys(o.glslRegistry).forEach((e=>{const t=new o.glslRegistry[e](this.context);this.libs[e]=t}));const s=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const t=this.libs[e].getFunctions();for(const n in t){const i=e+"."+n;let o;s[i]?(o=s[i],o.routineBody=t[n].routineBody):(o=new r.GlslLibRoutineNode(i,t[n].routineBody),s[i]=o);const a=t[n].dependencies;if(a)for(let e=0;e<a.length;++e)if(s[a[e]])o.addDependency(s[a[e]]);else{const t=new r.GlslLibRoutineNode(a[e]);s[a[e]]=t,o.addDependency(t)}}}}preprocess(){const e=this.context.programInfo;let t=e.shaderSource;return this.context.programInfo.hasMain||(t=`${t}\n ${(0,s.getDefaultFragShaderMain)(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),t=(0,i.replaceInlines)(t),`${(0,s.getFragShaderPreamble)(this.context.glContext.version)}\n ${this.getUniforms(e.inputNames,e.variables)}\n ${this.getImports(t)}\n ${t}`}getImports(e){const t=this.selectGlslLibRoutinesToBeIncluded(e);if(0===t.length)return"";let n="";for(let e=0;e<t.length;++e){if(!t[e].routineBody)throw new Error(`Missing body for the Glsl Library routine: ${t[e].name}`);n+=t[e].routineBody+"\n"}return n}selectGlslLibRoutinesToBeIncluded(e){const t=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach((n=>{const r=n.split(".")[1];-1!==e.indexOf(r)&&t.push(this.glslLibRoutineDependencyGraph[n])})),r.TopologicalSortGlslRoutines.returnOrderedNodes(t)}getUniforms(e,t){const n=[];if(e)for(const t of e)n.push(`uniform sampler2D ${t};`);if(t)for(const e of t)n.push(`uniform ${e.type} ${e.name}${e.arrayLength?`[${e.arrayLength}]`:""};`);return n.join("\n")}}},1248:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.glslRegistry=void 0;const r=n(6859),i=n(1371),o=n(2691),s=n(9183),a=n(9314);t.glslRegistry={encoding:i.EncodingGlslLib,fragcolor:o.FragColorGlslLib,vec:a.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},9183:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShapeUtilsGlslLib=void 0;const r=n(1997);class i extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const e=this.context.outputTextureLayout.shape.length,t={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=e){const i=o.length,s=e-i,a=`bcastIndices_${n}`;let u="";for(let e=0;e<i;++e)u+=`\n realIndices[${e}] = int( mod(float(bcastedIndices[${s+e}]), ${o[e]}.0) );\n `;const l=`\n void ${a} (int bcastedIndices[${e}], out int realIndices[${i}]) {\n ${u}\n }\n `;t[a]=new r.GlslLibRoutine(l)}})),t}bcastMatmulIndex(){const e=this.context.outputTextureLayout.shape.length,t={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>e)){const i=o.length,s=e-i,a=`bcastMatmulIndices_${n}`;let u="";for(let e=0;e<i-2;++e)u+=`\n realIndices[${e}] = int( mod(float(bcastedIndices[${s+e}]), ${o[e]}.0) );\n `;const l=`\n void ${a}(int bcastedIndices[${e}], out int realIndices[${i}]) {\n ${u}\n realIndices[${i-1}] = bcastedIndices[${e-1}];\n realIndices[${i-2}] = bcastedIndices[${e-2}];\n }\n `;t[a]=new r.GlslLibRoutine(l)}})),t}indicesToOffset(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`indicesToOffset_${t}`;e[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s)),u=`indicesToOffset_${t}_T`,e[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s.slice().reverse()))})),e}static indexToOffsetSingle(e,t,n){let r="";for(let e=t-1;e>=0;--e)r+=`\n offset += indices[${e}] * ${n[e]};\n `;return`\n int ${e}(int indices[${t}]) {\n int offset = 0;\n ${r}\n return offset;\n }\n `}offsetToIndices(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`offsetToIndices_${t}`;e[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s)),u=`offsetToIndices_${t}_T`,e[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s.slice().reverse()))})),e}static offsetToIndicesSingle(e,t,n){const r=[];for(let e=0;e<t-1;++e)r.push(`\n indices[${e}] = offset / ${n[e]};`),r.push(`\n offset -= indices[${e}] * ${n[e]};`);return r.push(`\n indices[${t-1}] = offset;`),`\n void ${e}(int offset, out int indices[${t}]) {\n ${r.join("")}\n }\n `}incrementIndices(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const i=this.context.inputTextureLayouts[n].shape,o=i.length,s=`incrementIndices_${t}`;let a="";for(let e=0;e<o;++e)a+=`\n shape[${e}] = ${i[e]};`;const u=`\n void ${s}(int axis, out int indices[${o}]) {\n int shape[${o}];\n ${a};\n for(int i = ${o} -1 ; i >= 0; --i) {\n if(i > axis) continue;\n indices[i] += 1;\n if(indices[i] < shape[i]) {\n break;\n }\n indices[i] = 0;\n }\n }\n `;e[s]=new r.GlslLibRoutine(u)})),e}}t.ShapeUtilsGlslLib=i},6757:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDefaultFragShaderMain=t.getFragShaderPreamble=t.getVertexShaderSource=t.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function i(e){return 1===e?n:r}t.getGlsl=i,t.getVertexShaderSource=function(e){const t=i(e);return`${t.version}\n precision highp float;\n ${t.attribute} vec3 position;\n ${t.attribute} vec2 textureCoord;\n\n ${t.varyingVertex} vec2 TexCoords;\n\n void main()\n {\n gl_Position = vec4(position, 1.0);\n TexCoords = textureCoord;\n }`},t.getFragShaderPreamble=function(e){const t=i(e);return`${t.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${t.varyingFrag} vec2 TexCoords;\n ${t.outputDeclaration}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n // Custom vector types to handle higher dimenalities.\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n `},t.getDefaultFragShaderMain=function(e,t){return`\n void main() {\n int indices[${t}];\n toVec(TexCoords, indices);\n vec4 result = vec4(process(indices));\n ${i(e).output} = result;\n }\n `}},9314:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VecGlslLib=void 0;const r=n(1997);class i extends r.GlslLib{constructor(e){super(e)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const e=this.context.outputTextureLayout.shape.length,t={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const i in t){const o=`${i}Vec`;let s="";for(let n=0;n<e;++n)s+=`\n dest[${n}] ${t[i]} src[${n}];\n `;const a=`\n void ${o}(int src[${e}], out int dest[${e}]) {\n ${s}\n }\n `;n[o]=new r.GlslLibRoutine(a)}return n}copyVec(){const e=this.context.outputTextureLayout.shape.length;let t="";for(let n=0;n<e;++n)t+=`\n dest[${n}] = src[${n}];\n `;const n=`\n void copyVec(int src[${e}], out int dest[${e}]) {\n ${t}\n }\n `;return{copyVec:new r.GlslLibRoutine(n)}}setVecItem(){const e=this.context.outputTextureLayout.shape.length;let t=`\n if(index < 0)\n index =${e} + index;\n if (index == 0)\n m[0] = value;\n `;for(let n=1;n<e-1;++n)t+=`\n else if (index == ${n})\n m[${n}] = value;\n `;t+=`\n else\n m[${e-1}] = value;\n `;const n=`\n void setVecItem(out int m[${e}], int index, int value) {\n ${t}\n }\n `;return{setVecItem:new r.GlslLibRoutine(n)}}getVecItem(){const e=this.context.outputTextureLayout.shape.length;let t=`\n if(index < 0)\n index = ${e} + index;\n if (index == 0)\n return m[0];\n `;for(let n=1;n<e-1;++n)t+=`\n else if (index == ${n})\n return m[${n}];\n `;t+=`\n else\n return m[${e-1}];\n `;const n=`\n int getVecItem(int m[${e}], int index) {\n ${t}\n }\n `;return{getVecItem:new r.GlslLibRoutine(n)}}}t.VecGlslLib=i},7860:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLInferenceHandler=void 0;const r=n(1315),i=n(9240),o=n(7273),s=n(9),a=n(7379),u=n(2488),l=n(540),c=n(3314),d=n(5639);t.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,t){return(0,c.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,t)}executeProgram(e,t){if(t.length<e.inputNames.length)throw new Error(`Input size mustn't be less than ${e.inputNames.length}.`);if(e.inputNames.length!==e.inputTypes.length)throw new Error("input names size does not match input types");const n=[];for(let r=0;r<e.inputNames.length;++r)n[r]=this.getOrCreateTextureData(t[r],e.inputTypes[r]);const r=((e,t)=>{const n=t.map((e=>`${e.unpackedShape.join(",")};${e.width}x${e.height}`)).join("_");let r=e.name;return e.cacheHint&&(r+="["+e.cacheHint+"]"),r+=":"+n,r})(e,n);let i=this.session.programManager.getArtifact(r);const o=i?i.programInfo:"function"==typeof e.get?e.get():e,s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o.output.dims,o.output.textureType),a=this.createTextureData(s,o.output.type);return i||(i=this.session.programManager.build(o,n,a),this.session.programManager.setArtifact(r,i)),this.runProgram(i,n,a),a}run(e,t){return this.executeProgram(e,t).tensor}runProgram(e,t,n){for(let n=0;n<t.length;++n)if(!!t[n].isPacked!=(e.programInfo.inputTypes[n]===d.TextureType.packed))throw new Error(`input[${n}] property packed inconsistent`);if(!!n.isPacked!=(e.programInfo.output.textureType===d.TextureType.packed))throw new Error("output property packed inconsistent");this.session.programManager.run(e,t,n)}getOrCreateTextureData(e,t){let n=this.getTextureData(e.dataId,t===d.TextureType.packed);if(!n&&(n=this.getTextureData(e.dataId,t!==d.TextureType.packed),n))return t===d.TextureType.packed?this.pack(n):this.unpack(n);if(!n){const r=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,e.dims,t);if(t===d.TextureType.packedLastDimension){const n=1,r=4,i=e.dims;if(4===i.length){const o=[i[0],Math.ceil(i[1]*i[2]*i[3]/r)],s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o,t);let a=e.numberData;if(i[1]*i[2]*i[3]%r!=0){const t=i[0],o=i[1]*i[2]*i[3],s=Math.ceil(o*n/r)*r;a=new Float32Array(t*s);for(let r=0;r<t;++r){const t=r*o,i=r*s+r%n*o;a.set(e.numberData.subarray(t,t+o),i)}}return this.createTextureData(s,e.type,a,e,1)}}if(t===d.TextureType.packed){const t=(0,c.createTextureLayoutFromShape)(this.session.layoutStrategy,e.dims,1,[],{reverseWH:!0}),r=this.createTextureData(t,e.type,e.numberData,e,1);n=this.pack(r)}else n=this.createTextureData(r,e.type,e.numberData,e,1)}return n}createTextureDataFromLayoutBindTensor(e,t,n,r){return this.createTextureData(e,t,n,r,1)}createTextureData(e,t,n,i,o){r.Logger.verbose("InferenceHandler",`Creating TextureData: layout:[${JSON.stringify(e)}]`);const s=this.session.textureManager.createTextureFromLayout(t,e,n,o);return this.createTextureDataFromTexture(e,t,s,i)}reshapeUnpacked(e,t){const n=this.getOrCreateTextureData(e,d.TextureType.unpacked),r={channels:n.channels,height:n.height,width:n.width,shape:0!==t.length?t:[1],strides:o.ShapeUtil.computeStrides(t),unpackedShape:t};return this.createTextureDataFromTexture(r,e.type,n.texture).tensor}reshapePacked(e,t){const n=this.getOrCreateTextureData(e,d.TextureType.packed);if((0,a.isReshapeCheap)(e.dims,t)){const r={channels:n.channels,height:n.height,width:n.width,shape:0!==t.length?t:[1],strides:o.ShapeUtil.computeStrides(t),unpackedShape:t,isPacked:!0};return this.createTextureDataFromTexture(r,e.type,n.texture).tensor}const r=(0,a.processDims3D)(e.dims),i=(0,a.processDims3D)(t),s=this.reshapePacked(e,r),u=this.run((0,a.createPackedReshape3DProgramInfoLoader)(this,s,i),[s]);return this.reshapePacked(u,t)}cast(e,t){const n=this.getOrCreateTextureData(e,d.TextureType.unpacked);return this.createTextureDataFromTexture(n,t,n.texture).tensor}createTextureDataFromTexture(e,t,n,r,o){const s=Object.assign(Object.assign({},e),{tensor:r||new i.Tensor(e.unpackedShape,t,(e=>this.readTexture(s)),(async e=>this.readTextureAsync(s)),void 0,o),texture:n});return this.setTextureData(s.tensor.dataId,s,e.isPacked),s}getTextureData(e,t=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,t):t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){this.session.isInitializer(e)?this.session.setTextureData(e,t,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,t)}isTextureLayoutCached(e,t=!1){return!!this.getTextureData(e.dataId,t)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((e=>this.session.textureManager.releaseTexture(e))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((e=>this.session.textureManager.releaseTexture(e))),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,l.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},4110:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WEBGL_OP_RESOLVE_RULES=void 0;const s=n(8817),a=o(n(5194)),u=n(4752),l=n(6668),c=n(9754),d=n(5042),h=n(6742),p=n(4125),f=n(6149),g=n(5378),m=n(6981),b=n(7413),y=n(7006),v=n(8276),w=n(5565),S=n(2834),_=n(1010),T=n(8126),x=n(2801),E=n(565),C=n(2444),P=n(815),O=n(564),A=n(5416),k=n(1240),I=n(5944),M=n(5707),R=o(n(9087)),D=n(7862),$=n(3980);t.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",R.abs],["Acos","","7+",R.acos],["Add","","7+",a.add],["And","","7+",a.and],["Asin","","7+",R.asin],["Atan","","7+",R.atan],["AveragePool","","7+",S.averagePool,S.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",u.cast,u.parseCastAttributes],["Ceil","","6+",R.ceil],["Clip","","6-10",R.clip,R.parseClipAttributes],["Clip","","11+",R.clipV11],["Concat","","4+",l.concat,l.parseConcatAttributes],["Conv","","1+",c.conv,c.parseConvAttributes],["ConvTranspose","","1+",d.convTranspose,d.parseConvTransposeAttributes],["Cos","","7+",R.cos],["Div","","7+",a.div],["Dropout","","7+",R.identity],["DepthToSpace","","1+",h.depthToSpace,h.parseDepthToSpaceAttributes],["Equal","","7+",a.equal],["Elu","","6+",R.elu,R.parseEluAttributes],["Exp","","6+",R.exp],["Flatten","","1+",p.flatten,p.parseFlattenAttributes],["Floor","","6+",R.floor],["FusedConv","com.microsoft","1+",c.conv,c.parseConvAttributes],["Gather","","1+",f.gather,f.parseGatherAttributes],["Gemm","","7-10",g.gemm,g.parseGemmAttributesV7],["Gemm","","11+",g.gemm,g.parseGemmAttributesV11],["GlobalAveragePool","","1+",S.globalAveragePool,S.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",S.globalMaxPool],["Greater","","7+",a.greater],["Identity","","1+",R.identity],["ImageScaler","","1+",m.imageScaler,m.parseImageScalerAttributes],["InstanceNormalization","","6+",b.instanceNormalization,b.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",R.leakyRelu,R.parseLeakyReluAttributes],["Less","","7+",a.less],["LRN","","1+",y.lrn,y.parseLrnAttributes],["Log","","6+",R.log],["MatMul","","1+",v.matMul,v.parseMatMulAttributes],["MaxPool","","1+",S.maxPool,S.parseMaxPoolAttributes],["Mul","","7+",a.mul],["Neg","","6+",R.neg],["Not","","1+",R.not],["Or","","7+",a.or],["Pad","","2-10",w.padV2,w.parsePadAttributesV2],["Pad","","11+",w.padV11,w.parsePadAttributesV11],["Pow","","7+",a.pow],["PRelu","","7+",a.pRelu],["ReduceLogSum","","1+",_.reduceLogSum,_.parseReduceAttributes],["ReduceMax","","1+",_.reduceMax,_.parseReduceAttributes],["ReduceMean","","1+",_.reduceMean,_.parseReduceAttributes],["ReduceMin","","1+",_.reduceMin,_.parseReduceAttributes],["ReduceProd","","1+",_.reduceProd,_.parseReduceAttributes],["ReduceSum","","1-12",_.reduceSum,_.parseReduceAttributes],["ReduceSumSquare","","1+",_.reduceLogSumSquare,_.parseReduceAttributes],["Relu","","6+",R.relu],["Reshape","","5+",T.reshape],["Resize","","10",x.resize,x.parseResizeAttributesV10],["Resize","","11+",x.resize,x.parseResizeAttributesV11],["Shape","","1+",E.shape],["Sigmoid","","6+",R.sigmoid],["Sin","","7+",R.sin],["Slice","","10+",C.sliceV10],["Slice","","1-9",C.slice,C.parseSliceAttributes],["Softmax","","1-12",P.softmax,P.parseSoftmaxAttributes],["Softmax","","13+",P.softmaxV13,P.parseSoftmaxAttributesV13],["Split","","2-12",O.split,O.parseSplitAttributes],["Sqrt","","6+",R.sqrt],["Squeeze","","1-12",A.squeeze,A.parseSqueezeAttributes],["Squeeze","","13+",A.squeezeV13],["Sub","","7+",a.sub],["Sum","","6+",k.sum],["Tan","","7+",R.tan],["Tanh","","6+",R.tanh],["Tile","","6+",I.tile],["Transpose","","1+",M.transpose,M.parseTransposeAttributes],["Upsample","","7-8",$.upsample,$.parseUpsampleAttributesV7],["Upsample","","9",$.upsample,$.parseUpsampleAttributesV9],["Unsqueeze","","1-12",D.unsqueeze,D.parseUnsqueezeAttributes],["Unsqueeze","","13+",D.unsqueezeV13],["Xor","","7+",a.xor]]},8817:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseBatchNormalizationAttributes=t.batchNormalization=void 0;const r=n(4910),i=n(6757),o=n(5639),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};t.batchNormalization=(e,t,n)=>(u(t),[e.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(e,t,n)}),t)]),t.parseBatchNormalizationAttributes=e=>{const t=e.attributes.getFloat("epsilon",1e-5),n=e.attributes.getFloat("momentum",.9),i=e.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:t,momentum:n,spatial:i})};const a=(e,t,n)=>{const r=(0,i.getGlsl)(e.session.backend.glContext.version),a=t[0].dims.length,[u,l]=e.calculateTextureWidthAndHeight(t[1].dims,o.TextureType.unpacked),c=`\n float process(int[${a}] indices) {\n vec2 position = offsetToCoords(indices[1], ${u}, ${l});\n float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n float b = getColorAsFloat(${r.texture2D}(B, position));\n\n return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n }`;return Object.assign(Object.assign({},s),{output:{dims:t[0].dims,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:c})},u=e=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs.");const t=e[0],n=e[1],r=e[2],i=e[3],o=e[4];if(t.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==i.dims.length||1!==o.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1]||o.dims[0]!==t.dims[1])throw new Error("invalid input shape.");if("float32"!==t.type&&"float64"!==t.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==i.type&&"float64"!==i.type||"float32"!==o.type&&"float64"!==o.type)throw new Error("invalid input tensor types.")}},5194:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.xor=t.sub=t.pRelu=t.pow=t.or=t.mul=t.less=t.greater=t.equal=t.div=t.and=t.add=t.glslPRelu=t.glslPow=t.glslXor=t.glslOr=t.glslAnd=t.glslLess=t.glslGreater=t.glslEqual=t.glslSub=t.glslMul=t.glslDiv=t.glslAdd=void 0;const r=n(7273),i=n(1997),o=n(6757),s=n(5639);function a(){const e="add_";return{body:`\n float ${e}(float a, float b) {\n return a + b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 + v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function u(){const e="div_";return{body:`\n float ${e}(float a, float b) {\n return a / b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 / v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function l(){const e="mul_";return{body:`\n float ${e}(float a, float b) {\n return a * b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 * v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function c(){const e="sub_";return{body:`\n float ${e}(float a, float b) {\n return a - b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 - v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function d(){const e="equal_";return{body:`\n float ${e}(float a, float b) {\n return float(a == b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4(equal(v1, v2));\n }\n `,name:e,type:i.FunctionType.ValueBased}}function h(){const e="greater_";return{body:`\n float ${e}(float a, float b) {\n return float(a > b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4( v1.r > v2.r ,\n v1.g > v2.g,\n v1.b > v2.b,\n v1.a > v2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function p(){const e="less_";return{body:`\n float ${e}(float a, float b) {\n return float(a < b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4( v1.r < v2.r ,\n v1.g < v2.g,\n v1.b < v2.b,\n v1.a < v2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function f(){const e="and_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) && bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r && b2.r ,\n b1.g && b2.g,\n b1.b && b2.b,\n b1.a && b2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function g(){const e="or_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) || bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r || b2.r ,\n b1.g || b2.g,\n b1.b || b2.b,\n b1.a || b2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function m(){const e="xor_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) ^^ bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r ^^ b2.r ,\n b1.g ^^ b2.g,\n b1.b ^^ b2.b,\n b1.a ^^ b2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function b(){return function(e){const t=`${e}_`;return{body:`\n float ${t}(float a, float b) {\n return ${e}(a, b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return ${e}(v1, v2);\n }\n `,name:t,type:i.FunctionType.ValueBased}}("pow")}function y(){const e="prelu_";return{body:`\n float ${e}(float a, float b) {\n return a < 0.0 ? a * b: a;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4(\n v1.r < 0.0 ? v1.r * v2.r: v1.r,\n v1.g < 0.0 ? v1.g * v2.g: v1.g,\n v1.b < 0.0 ? v1.b * v2.b: v1.b,\n v1.a < 0.0 ? v1.a * v2.a: v1.a\n );\n }\n `,name:e,type:i.FunctionType.ValueBased}}t.glslAdd=a,t.glslDiv=u,t.glslMul=l,t.glslSub=c,t.glslEqual=d,t.glslGreater=h,t.glslLess=p,t.glslAnd=f,t.glslOr=g,t.glslXor=m,t.glslPow=b,t.glslPRelu=y;const v=(e,t,n,r=t[0].type,i)=>{const o=e.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>w(e,t,n,r)}},w=(e,t,n,i=t[0].type)=>{const a=e.session.pack?s.TextureType.packed:s.TextureType.unpacked,u=!r.ShapeUtil.areEqual(t[0].dims,t[1].dims);let l=t[0].dims;const c=e.session.pack;if(u){const s=r.BroadcastUtil.calcShape(t[0].dims,t[1].dims,!1);if(!s)throw new Error("Can't perform binary op on the given tensors");l=s;const u=l.length,d=0!==t[0].dims.length?t[0].dims.length:1,h=0!==t[1].dims.length?t[1].dims.length:1,p=0!==t[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",f=0!==t[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",g=(0,o.getGlsl)(e.session.backend.glContext.version),m=c?`\n ${n.body}\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n vec4 result = ${n.name}(a, b);\n ${g.output} = result;\n }`:`\n ${n.body}\n float process(int indices[${u}]) {\n int aindices[${d}];\n int bindices[${h}];\n ${p}\n ${f}\n return ${n.name}(_A(aindices), _B(bindices));\n }`;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:l,type:i,textureType:a},shaderSource:m,hasMain:c}}const d=(0,o.getGlsl)(e.session.backend.glContext.version),h=`\n ${n.body}\n void main() {\n vec4 v1 = ${d.texture2D}(A, TexCoords);\n vec4 v2 = ${d.texture2D}(B, TexCoords);\n vec4 result = ${n.name}(v1, v2);\n ${d.output} = result;\n }\n `;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:t[0].dims,type:i,textureType:a},shaderSource:h,hasMain:!0}};t.add=(e,t)=>[e.run(v(e,t,a()),t)],t.and=(e,t)=>[e.run(v(e,t,f(),"bool"),t)],t.div=(e,t)=>[e.run(v(e,t,u()),t)],t.equal=(e,t)=>[e.run(v(e,t,d(),"bool"),t)],t.greater=(e,t)=>[e.run(v(e,t,h(),"bool"),t)],t.less=(e,t)=>[e.run(v(e,t,p(),"bool"),t)],t.mul=(e,t)=>[e.run(v(e,t,l()),t)],t.or=(e,t)=>[e.run(v(e,t,g(),"bool"),t)],t.pow=(e,t)=>[e.run(v(e,t,b()),t)],t.pRelu=(e,t)=>[e.run(v(e,t,y()),t)],t.sub=(e,t)=>[e.run(v(e,t,c()),t)],t.xor=(e,t)=>[e.run(v(e,t,m(),"bool"),t)]},4752:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseCastAttributes=t.cast=void 0;const r=n(7273);t.cast=(e,t,n)=>(i(t),[e.cast(t[0],n)]),t.parseCastAttributes=e=>r.ProtoUtil.tensorDataTypeFromProto(e.attributes.getInt("to"));const i=e=>{if(!e||1!==e.length)throw new Error("Cast requires 1 input.");if("string"===e[0].type)throw new Error("Invalid input type.")}},4595:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedConcatProgramInfoLoader=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614);t.createPackedConcatProgramInfoLoader=(e,t,n)=>{const u=(l=t.length,c=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:l},((e,t)=>`X${t}`)),inputTypes:Array(l).fill(i.TextureType.packed),cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=n[0].dims.slice();if(u>=l.length||u<-1*l.length)throw new Error("axis specified for concat doesn't match input dimensionality");u<0&&(u=l.length+u);const c=l.slice(0);for(let e=1;e<n.length;e++){const t=n[e].dims.slice();for(let e=0;e<l.length;e++)if(e===u)c[u]+=t[e];else if(l[e]!==t[e])throw new Error("non concat dimensions must match")}const d=c.length,h=(0,s.getChannels)("coords",d),p=(0,o.getCoordsDataType)(d),f=(0,s.unpackFromChannel)(),g=n.map((e=>e.dims)),m=(0,o.getGlChannels)(d),b=new Array(g.length-1);b[0]=g[0][u];for(let e=1;e<b.length;e++)b[e]=b[e-1]+g[e][u];const y=m[u],v=m.slice(-2),w=m.join();let S=`if (${y} < ${b[0]}) {\n return getChannel(\n getX0(${w}), vec2(${v.join()}));\n }`;for(let e=1;e<b.length;e++){const t=b[e-1];S+=`\n if (${y} < ${b[e]} && ${y} >= ${b[e-1]}) {\n return getChannel(\n getX${e}(${a(m,y,t)}),\n vec2(${a(v,y,t)}));\n }`}const _=b.length,T=b[b.length-1];S+=`\n return getChannel(\n getX${_}(${a(m,y,T)}),\n vec2(${a(v,y,T)}));`;const x=(0,r.getGlsl)(e.session.backend.glContext.version),E=`\n ${f}\n float getValue(${m.map((e=>"int "+e))}) {\n ${S}\n }\n\n void main() {\n ${p} coords = getOutputCoords();\n int lastDim = coords.${m[d-1]};\n coords.${m[d-1]} = coords.${m[d-2]};\n coords.${m[d-2]} = lastDim;\n\n vec4 result = vec4(getValue(${h}), 0., 0., 0.);\n\n ${h[d-1]} = ${h[d-1]} + 1;\n if (${h[d-1]} < ${c[d-1]}) {\n result.g = getValue(${h});\n }\n\n ${h[d-2]} = ${h[d-2]} + 1;\n if (${h[d-2]} < ${c[d-2]}) {\n result.a = getValue(${h});\n }\n\n ${h[d-1]} = ${h[d-1]} - 1;\n if (${h[d-2]} < ${c[d-2]} &&\n ${h[d-1]} < ${c[d-1]}) {\n result.b = getValue(${h});\n }\n ${x.output} = result;\n }\n `;return Object.assign(Object.assign({},t),{output:{dims:c,type:n[0].type,textureType:i.TextureType.packed},shaderSource:E,hasMain:!0})})(e,u,t,n.axis)})};const a=(e,t,n)=>{const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}},6668:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseConcatAttributes=t.concat=void 0;const r=n(4910),i=n(5639),o=n(4595);t.concat=(e,t,n)=>(d(t),e.session.pack&&t[0].dims.length>1?[e.run((0,o.createPackedConcatProgramInfoLoader)(e,t,n),t)]:[e.run(s(e,t,n),t)]);const s=(e,t,n)=>{const r=(o=t.length,s=n.cacheKey,{name:"Concat",inputNames:Array.from({length:o},((e,t)=>`X${t}`)),inputTypes:Array(o).fill(i.TextureType.unpacked),cacheHint:s});var o,s;return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const o=n[0].dims.slice();if(r>=o.length||r<-1*o.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=o.length+r);const s=o.slice(0);for(let e=1;e<n.length;e++){const t=n[e].dims.slice();for(let e=0;e<o.length;e++)if(e===r)s[r]+=t[e];else if(o[e]!==t[e])throw new Error("non concat dimensions must match")}const d=s.length,h=new Array(n.length);let p=0;for(let e=0;e<h.length;++e)p+=n[e].dims[r],h[e]=p;let f="";f=n.length<5?a(h):u(h);const g=`\n ${l(n.length,d)}\n ${c(h)}\n ${f}\n float process(int indices[${d}]) {\n int textureIndex = getTextureWhereDataResides (indices[${r}]);\n\n if(textureIndex != 0) {\n indices[${r}] = indices[${r}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));\n }\n\n return fetchDataFromCorrectTexture(textureIndex, indices);\n }`;return Object.assign(Object.assign({},t),{output:{dims:s,type:n[0].type,textureType:i.TextureType.unpacked},shaderSource:g})})(0,r,t,n.axis)})},a=e=>`int getTextureWhereDataResides(int index) {\n ${e.map(((e,t)=>`if(index<${e}) {return ${t};}\n`)).join("")}\n }`,u=e=>a(e),l=(e,t)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${t}]) {`];for(let t=0;t<e;++t)0===t?n.push(`\tif (textureIndex == ${t}) { return _X${t}(indices); }`):t===e-1?n.push(`\telse { return _X${t}(indices); }`):n.push(`\telse if (textureIndex == ${t}) { return _X${t}(indices); }`);return n.push("\t}"),n.join("\n")},c=e=>{const t=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n<e.length;++n)0===n?t.push(`\tif (index == ${n}) { return ${e[n]}; }`):n===e.length-1?t.push(`\telse { return ${e[n]}; }`):t.push(`\telse if (index == ${n}) { return ${e[n]}; }`);return t.push("\t}"),t.join("\n")};t.parseConcatAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const d=e=>{if(!e||e.length<1)throw new Error("too few inputs");const t=e[0].type,n=e[0].dims.length;if("string"===t)throw new Error("string tensor is not supported yet");for(const r of e){if(r.type!==t)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},7825:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(1315),i=n(6757),o=n(5639),s=n(9754),a=n(2150);t.createUnpackedGroupedConvProgramInfoLoader=(e,t,n)=>{const u=(l=t.length>2,c=n.cacheKey,{name:"GroupedConv",inputNames:l?["X","W","Bias"]:["X","W"],inputTypes:l?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=t.length>2?"value += getBias(output_channel);":"",c=t[0].dims.slice(),d=t[1].dims.slice(),h=d[0]/u.group;r.Logger.verbose("GroupedConv",`autpPad:${u.autoPad}, dilations:${u.dilations}, group:${u.group}, kernelShape:${u.kernelShape}, pads:${u.pads}, strides:${u.strides}`);const p=(0,s.calculateOutputShape)(c,d,u.dilations,u.pads,u.strides),f=(0,i.getGlsl)(e.session.backend.glContext.version),{activationFunction:g,applyActivation:m}=(0,a.getActivationSnippet)(u),b=`\n const ivec2 strides = ivec2(${u.strides[0]}, ${u.strides[1]});\n const ivec2 pads = ivec2(${u.pads[0]}, ${u.pads[1]});\n ${g}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n ivec2 xRCCorner = coords.zw * strides - pads;\n int group_id = output_channel / ${h};\n\n float value = 0.0;\n for (int wInChannel = 0; wInChannel < ${d[1]}; wInChannel++) {\n int input_channel = group_id * ${d[1]} + wInChannel;\n for (int wHeight = 0; wHeight < ${d[2]}; wHeight++) {\n int xHeight = xRCCorner.x + wHeight * ${u.dilations[0]};\n\n if (xHeight < 0 || xHeight >= ${c[2]}) {\n continue;\n }\n\n for (int wWidth = 0; wWidth < ${d[3]}; wWidth++) {\n int xWidth = xRCCorner.y + wWidth * ${u.dilations[1]};\n if (xWidth < 0 || xWidth >= ${c[3]}) {\n continue;\n }\n\n float xVal = getX(batch, input_channel, xWidth, xHeight);\n float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n value += xVal*wVal;\n }\n }\n }\n ${l}\n ${m}\n ${f.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:p,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:b,hasMain:!0})})(e,t,u,n)})}},7708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.conv2DPacked=t.conv2DPackedPointwise=void 0;const r=n(9754),i=n(5950),o=n(5632);t.conv2DPackedPointwise=(e,t,n)=>{const i=t[0].dims,s=t[1].dims,a=(0,r.calculateOutputShape)(i,s,n.dilations,n.pads,n.strides),u=e.reshapePacked(t[0],[i[1],i[2]*i[3]]),l=e.reshapePacked(t[1],[s[0],s[1]]),c=t.length>2?[l,u,t[2]]:[l,u],d=e.run((0,o.createPackedMatmulProgramInfoLoader)(e,c,n),c);return e.reshapePacked(d,a)},t.conv2DPacked=(e,t,n)=>{const s=t[0].dims,a=t[1].dims,u=(0,r.calculateOutputShape)(s,a,n.dilations,n.pads,n.strides),l=e.run((0,i.createPackedIm2ColProgramInfoLoader)(e,t[0],t[1],u,n),[t[0]]),c=e.reshapePacked(t[1],[a[0],a[1]*a[2]*a[3]]),d=3===t.length?[c,l,t[2]]:[c,l],h=e.run((0,o.createPackedMatmulProgramInfoLoader)(e,d,n),d);return e.reshapePacked(h,u)}},5042:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseConvTransposeAttributes=t.convTranspose=void 0;const r=n(4910),i=n(6757),o=n(5639),s=n(2150),a=(e,t,n,r,i,o)=>(e-1)*t+n+(r-1)*i+1-o,u=(e,t,n,r,i)=>{const o=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=o,n[i]=e-o):"SAME_LOWER"===t&&(n[r]=e-o,n[i]=o)};t.convTranspose=(e,t,n)=>(h(t,n),l(e,t,n));const l=(e,t,n)=>{const r=d(n,t);return[c(e,t,r)]},c=(e,t,n)=>e.run(((e,t,n)=>{const r=(a=t.length>2,u=n.cacheKey,{name:"ConvTranspose",inputNames:a?["X","W","B"]:["X","W"],inputTypes:a?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:u});var a,u;return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const a=t.length>2?"getB(output_channel)":"0.0",u=t[0].dims,l=t[1].dims,c=l[1],d=l[0]/r.group,h=[t[0].dims[0],t[1].dims[1]*r.group,...r.outputShape],p=(0,i.getGlsl)(e.session.backend.glContext.version),{activationFunction:f,applyActivation:g}=(0,s.getActivationSnippet)(r),m=`\n const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n ${f}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n\n ivec2 loc = coords.zw + pads;\n\n int group_id = output_channel / ${c};\n int wOutChannel = output_channel - group_id * ${c};\n\n float value = ${a};\n for (int inChannelOffset = 0; inChannelOffset < ${d}; inChannelOffset++) {\n int input_channel = group_id * ${d} + inChannelOffset;\n for (int wWOff = 0; wWOff < ${l[2]}; wWOff++) {\n for (int wHOff = 0; wHOff < ${l[3]}; wHOff++) {\n ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n ivec2 wLoc = loc - wOff;\n ivec2 wLocIn = wLoc / strides;\n if (\n wLocIn * strides == wLoc &&\n wLocIn.x >= 0 && wLocIn.x < ${u[2]} &&\n wLocIn.y >= 0 && wLocIn.y < ${u[3]}\n ) {\n float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n value += xVal * wVal;\n }\n }\n }\n }\n ${g}\n ${p.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:h,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:m,hasMain:!0})})(e,t,r,n)})})(e,t,n),t),d=(e,t)=>{const n=e.kernelShape.slice();if(0===e.kernelShape.length)for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e]);const r=e.pads.slice(),i=e.outputShape.slice();((e,t,n,r,i,o,s,l)=>{const c=e.length-2,d=0===l.length;for(let h=0;h<c;++h){const p=d?e[h+2]*o[h]:l[h],f=a(e[h+2],o[h],i[h],t[h],n[h],p);u(f,r,i,h,h+c),d&&l.push(o[h]*(e[h+2]-1)+s[h]+(t[h]-1)*n[h]+1-i[h]-i[h+c])}})(t[0].dims,n,e.dilations,e.autoPad,r,e.strides,e.outputPadding,i);const o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:r,outputShape:i,cacheKey:e.cacheKey}),o};t.parseConvTransposeAttributes=e=>{const t=e.attributes,n=(0,s.parseInternalActivationAttributes)(t),i=t.getString("auto_pad","NOTSET"),o=t.getInts("dilations",[1,1]),a=t.getInt("group",1),u=t.getInts("kernel_shape",[]),l=t.getInts("output_padding",[0,0]),c=t.getInts("output_shape",[]),d=t.getInts("pads",[0,0,0,0]),h=t.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:a,kernelShape:u,outputPadding:l,outputShape:c,pads:d,strides:h},n))};const h=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length||4!==e[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims[1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");const r=e[0].dims.length-2;if(t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==e[0].type||"float32"!==e[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===e.length&&"float32"!==e[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},9754:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseConvAttributes=t.conv=t.calculateOutputShape=void 0;const r=n(4910),i=n(7273),o=n(7825),s=n(7708),a=n(3281),u=n(2150),l=n(1625),c=n(8276);t.calculateOutputShape=(e,t,n,r,i)=>{const o=e[0],s=e.slice(2),a=s.length,u=t[0],l=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),c=s.map(((e,t)=>e+r[t]+r[t+a])).map(((e,t)=>Math.floor((e-l[t]+i[t])/i[t])));return[o,u].concat(...c)},t.conv=(e,t,n)=>(g(t,n),d(e,t,n));const d=(e,t,n)=>{const r=f(n,t),i=e.session.pack,a=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[e.run((0,o.createUnpackedGroupedConvProgramInfoLoader)(e,t,r),t)]:a&&i?[h(e,t,r)]:i&&4===t[0].dims.length&&1===t[0].dims[0]&&!a?[(0,s.conv2DPacked)(e,t,r)]:[p(e,t,r)]},h=(e,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,t.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),a=e.reshapeUnpacked(n[0],[i[1],i[2]*i[3]]),u=e.reshapeUnpacked(n[1],[o[0],o[1]]),l=n.length>2?[u,a,n[2]]:[u,a],d=e.run((0,c.createMatmulProgramInfoLoader)(l,r),l);return e.reshapeUnpacked(d,s)},p=(e,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,t.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),u=e.run((0,l.createIm2ColProgramInfoLoader)(e,n[0],n[1],s,r),[n[0]]),c=3===n.length?[u,n[1],n[2]]:[u,n[1]];return e.run((0,a.createDotProductProgramInfoLoader)(e,n,s,r),c)},f=(e,t)=>{const n=e.kernelShape.slice();if(0===e.kernelShape.length)for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e]);const r=e.pads.slice();i.PoolConvUtil.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,r,e.autoPad);const o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:r,cacheKey:e.cacheKey}),o};t.parseConvAttributes=e=>{const t=e.attributes,n=(0,u.parseInternalActivationAttributes)(t),i=t.getString("auto_pad","NOTSET"),o=t.getInts("dilations",[1,1]),s=t.getInt("group",1),a=t.getInts("kernel_shape",[]),l=t.getInts("pads",[0,0,0,0]),c=t.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:s,kernelShape:a,pads:l,strides:c},n))};const g=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length||4!==e[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims[1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");const n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==e[0].type||"float32"!==e[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===e.length&&"float32"!==e[2].type)throw new Error("Conv input(bias) should be float tensor")}},6742:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDepthToSpaceAttributes=t.depthToSpace=void 0;const r=n(5707);t.depthToSpace=(e,t,n)=>{i(t);const o=n.blocksize,s=o*o,a="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],u="DCR"===n.mode?[t[0].dims[0],o,o,t[0].dims[1]/s,t[0].dims[2],t[0].dims[3]]:[t[0].dims[0],t[0].dims[1]/s,o,o,t[0].dims[2],t[0].dims[3]],l=e.reshapeUnpacked(t[0],u),c={perm:a,cacheKey:`${a}`},[d]=(0,r.transpose)(e,[l],c),h=[t[0].dims[0],t[0].dims[1]/s,t[0].dims[2]*o,t[0].dims[3]*o];return[e.reshapeUnpacked(d,h)]},t.parseDepthToSpaceAttributes=e=>{const t=e.attributes.getInt("blocksize");if(t<1)throw new Error(`blocksize must be >= 1, but got : ${t} for DepthToSpace`);const n=e.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:t}};const i=e=>{if(1!==e.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${e.length}`);if("string"===e[0].type||4!==e[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},3281:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createDotProductProgramInfoLoader=void 0;const r=n(7273),i=n(6757),o=n(5639),s=n(2150),a=n(1625);t.createDotProductProgramInfoLoader=(e,t,n,u)=>{const l=((e,t)=>({name:"ConvDotProduct",inputNames:e?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:e?[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.packedLastDimension],cacheKey:t.activationCacheKey}))(t.length>2,u);return Object.assign(Object.assign({},l),{get:()=>((e,t,n,u,l)=>{const c=n[0].dims,d=n[1].dims,h=[d[0],Math.ceil(c[1]*d[2]*d[3]/4)],p=(0,a.calculateIm2ColDims)(c,d,u),[f,g]=e.calculateTextureWidthAndHeight(h,o.TextureType.packedLastDimension),m=r.ShapeUtil.computeStrides(p),[b,y]=e.calculateTextureWidthAndHeight(p,o.TextureType.packedLastDimension),v=u.length,w=n.length<3?"0.0":"_B(b)",S=Math.ceil(c[1]*d[2]*d[3]/4),{activationFunction:_,applyActivation:T}=(0,s.getActivationSnippet)(l),x=(0,i.getGlsl)(e.session.backend.glContext.version),E=`\n${_}\nfloat process(int indices[${v}]) {\n int b[1];\n b[0] = indices[1];\n int im2col[4];\n im2col[0] = indices[0];\n im2col[1] = indices[2];\n im2col[2] = indices[3];\n int im2colOffset = im2col[0] * ${m[0]} + im2col[1] * ${m[1]} + im2col[2] * ${m[2]};\n int kernelOffset = indices[1] * ${h[1]};\n float value = ${w};\n for (int i = 0; i < ${S}; ++i) {\n vec2 im2colCoords = offsetToCoords(im2colOffset, ${b}, ${y});\n vec2 kernelCoords = offsetToCoords(kernelOffset, ${f}, ${g});\n value += dot(${x.texture2D}(Im2Col, im2colCoords), ${x.texture2D}(K, kernelCoords));\n ++im2colOffset;\n ++kernelOffset;\n }\n ${T}\n return value;\n}`;return Object.assign(Object.assign({},t),{output:{dims:u,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:E})})(e,l,t,n,u)})}},4125:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseFlattenAttributes=t.flatten=void 0;const r=n(7273);t.flatten=(e,t,n)=>{i(t,n);const o=r.ShapeUtil.flattenShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],o)]},t.parseFlattenAttributes=e=>e.attributes.getInt("axis",1);const i=(e,t)=>{if(!e||1!==e.length)throw new Error("Flatten requires 1 input.");const n=e[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(t<-n||t>n)throw new Error("Invalid axis");if("string"===e[0].type)throw new Error("string tensor is not supported.")}},2150:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseInternalActivationAttributes=t.getActivationSnippet=void 0;const r=n(7273),i=n(9087);t.getActivationSnippet=function(e){let t;switch(e.activation){case"Relu":t=(0,i.glslRelu)();break;case"Sigmoid":t=(0,i.glslSigmoid)();break;case"Clip":t=(0,i.glslClip)(e.clipMin,e.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=t.name;return{activationFunction:t.body,applyActivation:`value = ${n}_(value);`}},t.parseInternalActivationAttributes=e=>{const t=e.getString("activation","");if("Clip"===t){const[n,i]=e.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:t,clipMax:i,clipMin:n,activationCacheKey:`${t}:${n},${i}`}}return{activation:t,activationCacheKey:t}}},6149:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseGatherAttributes=t.gather=void 0;const r=n(4910),i=n(6145),o=n(7273),s=n(5639);t.gather=(e,t,n)=>(l(t,n.axis),[e.run(u(e,t,n),t)]),t.parseGatherAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",0)});const a={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},u=(e,t,n)=>{const r=Object.assign(Object.assign({},a),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const i=n[0].dims.slice(),a=n[1].dims.slice(),u=new Array(i.length+a.length-1);r=o.ShapeUtil.normalizeAxis(r,i.length);const l=[];for(let e=0;e<u.length;e++)e<r?(u[e]=i[e],l.push(`inputIdx[${e}] = outputIdx[${e}];`)):e<r+a.length?(u[e]=a[e-r],l.push(`indexDataIdx[${e-r}] = outputIdx[${e}];`)):(u[e]=i[e-a.length+1],l.push(`inputIdx[${e-a.length+1}] = outputIdx[${e}];`));const c=`\n float process(int outputIdx[${u.length||1}]) {\n int inputIdx[${i.length}];\n int indexDataIdx[${a.length||1}];\n indexDataIdx[0] = 0;\n ${l.join("\n ")}\n int idx = int(_B(indexDataIdx));\n inputIdx[${r}] = idx < 0 ? idx + ${i[r]} : idx;\n return _A(inputIdx);\n }`;return Object.assign(Object.assign({},t),{output:{dims:u,type:n[0].type,textureType:s.TextureType.unpacked},shaderSource:c})})(0,r,t,n.axis)})},l=(e,t)=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.");const n=e[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(t<-n||t>n-1)throw new Error("Invalid axis.");if(-1===i.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invaid input type.");if("int32"!==e[1].type&&"int16"!==e[1].type)throw new Error("Invaid input type.")}},5378:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseGemmAttributesV11=t.parseGemmAttributesV7=t.gemm=void 0;const r=n(4910),i=n(7273),o=n(5639);t.gemm=(e,t,n)=>(l(t,n),[e.run(a(t,n),t)]);const s=(e,t)=>{const n=0!==e.attributes.getInt("transA",0),i=0!==e.attributes.getInt("transB",0),o=e.attributes.getFloat("alpha",1),s=e.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:i,alpha:o,beta:s,isOptionalC:t})};t.parseGemmAttributesV7=e=>s(e,!1),t.parseGemmAttributesV11=e=>s(e,!0);const a=(e,t)=>{const n={name:"Gemm",inputNames:3===e.length?["A","B","C"]:["A","B"],inputTypes:3===e.length?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},n),{get:()=>u(n,e,t)})},u=(e,t,n)=>{const r=t[0].dims.slice(),s=t[1].dims.slice(),[a,u]=i.GemmUtil.getShapeOfGemmResult(r,n.transA,s,n.transB,3===t.length?t[2].dims:void 0),l=[a,u];if(!l)throw new Error("Can't use gemm on the given tensors");let c=r[r.length-1],d="";n.transA&&(c=r[0]),n.transA&&n.transB?d="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?d="value += _A_T(a) * _B(b);":!n.transA&&n.transB?d="value += _A(a) * _B_T(b);":n.transA||n.transB||(d="value += _A(a) * _B(b);");const h=l.length,p=`\n float process(int indices[${h}]) {\n int a[${h}];\n int b[${h}];\n ${3===t.length?`int c[${t[2].dims.length}];`:""}\n\n copyVec(indices, a);\n copyVec(indices, b);\n ${3===t.length?"bcastIndices_C(indices, c);":""}\n\n float value = 0.0;\n for (int k=0; k<${c}; ++k) {\n a[${h-1}] = k;\n b[${h-2}] = k;\n ${d}\n }\n\n value = value * alpha;\n ${3===t.length?"value += beta * _C(c);":""}\n return value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:l,type:t[0].type,textureType:o.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:p})},l=(e,t)=>{if(!e)throw new Error("Input is missing");if(t.isOptionalC&&(e.length<2||e.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&3!==e.length)throw new Error("Gemm requires 3 inputs");if(3===e.length&&1!==e[2].dims.length&&2!==e[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==e[0].type&&"float64"!==e[0].type||"float32"!==e[1].type&&"float64"!==e[1].type||3===e.length&&"float32"!==e[2].type&&"float64"!==e[2].type)throw new Error("Invalid input type.");if(e[0].type!==e[1].type||3===e.length&&e[0].type!==e[2].type)throw new Error("Input types are mismatched")}},5950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedIm2ColProgramInfoLoader=void 0;const r=n(6757),i=n(5639),o=n(5614);t.createPackedIm2ColProgramInfoLoader=(e,t,n,s,a)=>{const u=(l=a.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[i.TextureType.packed],cacheHint:l});var l;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,s,a,u)=>{const l=n.dims,c=s.dims,d=a.length,h=[c[1]*c[2]*c[3],a[2]*a[3]],p=c[2]*c[3],f=(0,o.unpackFromChannel)(),g=(0,r.getGlsl)(e.session.backend.glContext.version);let m="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)m+=`\n blockIndex = rc.x + ${t};\n pos = rc.y + ${e};\n\n if(blockIndex < ${h[1]} && pos < ${h[0]}) {\n offsetY = int(blockIndex / (${a[d-1]})) * ${u.strides[0]} -\n ${u.pads[0]};\n d0 = offsetY + ${u.dilations[0]} * (imod(pos, ${p}) / ${c[2]});\n\n if(d0 < ${l[2]} && d0 >= 0) {\n offsetX = imod(blockIndex, ${a[d-1]}) * ${u.strides[1]} -\n ${u.pads[1]};\n d1 = offsetX + ${u.dilations[1]} * imod(imod(pos, ${p}), ${c[2]});\n\n if(d1 < ${l[3]} && d1 >= 0) {\n\n ch = int(float(pos)/ ${p}.);\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(0, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n\n `;const b=`\n ${f}\n\n void main() {\n ivec2 rc = getOutputCoords();\n vec4 result = vec4(0.0);\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n ${m}\n ${g.output} = result;\n }\n `;return Object.assign(Object.assign({},t),{output:{dims:h,type:n.type,textureType:i.TextureType.packed},shaderSource:b,hasMain:!0})})(e,u,t,n,s,a)})}},1625:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateIm2ColDims=t.createIm2ColProgramInfoLoader=void 0;const r=n(5639);t.createIm2ColProgramInfoLoader=(e,n,i,o,s)=>{const a=(u=s.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:u});var u;return Object.assign(Object.assign({},a),{get:()=>((e,n,i,o,s,a)=>{const u=i.dims,l=o.dims,c=s.length,d=(0,t.calculateIm2ColDims)(u,l,s,4),h=`\n const int XC = ${u[1]};\n const int XH = ${u[2]};\n const int XW = ${u[3]};\n const int KH = ${a.kernelShape[0]};\n const int KW = ${a.kernelShape[1]};\n const int dilationH = ${a.dilations[0]};\n const int dilationW = ${a.dilations[1]};\n const int strideH = ${a.strides[0]};\n const int strideW = ${a.strides[1]};\n const int padH = ${a.pads[0]};\n const int padW = ${a.pads[1]};\n const int KHKW = KH*KW;\n const int XCKHKW = XC * KHKW;\n const int outputChannels = 4;\n vec4 process(int indices[${c}]) {\n int b = indices[0]; // batch size\n int oh = indices[1] * strideH - padH; //output height\n int ow = indices[2] * strideW - padW; //output width\n int p = indices[3] * outputChannels; //patch\n vec4 value = vec4(0.0);\n for(int i=0; i < outputChannels; ++i) {\n if(p < XCKHKW) {\n int patchC = p / KHKW;\n int patchH = (p - patchC*KHKW) / KW;\n int patchW = (p - patchC*KHKW) - patchH * KW;\n int xh2 = oh + patchH * dilationH;\n int xw2 = ow + patchW * dilationW;\n int x[${u.length}];\n x[0] = b;\n x[1] = patchC;\n x[2] = xh2;\n x[3] = xw2;\n if(xh2 >= 0 &&\n xh2 < XH &&\n xw2 >= 0 &&\n xw2 < XW) {\n value[i] = _X(x);\n }\n }\n ++p;\n }\n return value;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:d,type:i.type,textureType:r.TextureType.packedLastDimension},shaderSource:h})})(0,a,n,i,o,s)})},t.calculateIm2ColDims=(e,t,n,r=4)=>[n[0],n[2],n[3],Math.ceil(e[1]*t[2]*t[3]/r)]},6981:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseImageScalerAttributes=t.imageScaler=void 0;const r=n(4910),i=n(5639);t.imageScaler=(e,t,n)=>(u(t),[e.run(s(e,t,n),t)]),t.parseImageScalerAttributes=e=>{const t=e.attributes.getFloat("scale"),n=e.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:t,bias:n})};const o={name:"ImageScaler",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=(e,t,n)=>{const r=Object.assign(Object.assign({},o),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const o=n[0].dims.slice(),s=o.length,u=`\n ${a(r.bias.length)}\n float process(int indices[${s}]) {\n return _X(indices) * scale + getBias(bias, indices[1]);\n }`;return Object.assign(Object.assign({},t),{output:{dims:o,type:n[0].type,textureType:i.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:u})})(0,r,t,n)})},a=e=>{const t=[`float getBias(float bias[${e}], int channel) {`];for(let n=0;n<e;++n)0===n?t.push(`\tif (channel == ${n}) { return bias[${n}]; }`):n===e-1?t.push(`\telse { return bias[${n}]; }`):t.push(`\telse if (channel == ${n}) { return bias[${n}]; }`);return t.push("\t}"),t.join("\n")},u=e=>{if(!e||1!==e.length)throw new Error("ImageScaler requires 1 input.");if(4!==e[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")}},7413:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseInstanceNormalizationAttributes=t.instanceNormalization=void 0;const r=n(6757),i=n(5639);t.instanceNormalization=(e,t,n)=>{l(t);const r=e.run(s(t[0]),t);return[e.run(u(e,t[0],n,r.dims),[t[0],r,t[1],t[2]])]},t.parseInstanceNormalizationAttributes=e=>e.attributes.getFloat("epsilon",1e-5);const o={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=e=>Object.assign(Object.assign({},o),{get:()=>((e,t)=>{const n=t.dims.slice(),r=n[1],o=n[2]*n[3],s=[n[0],r],a=`\n vec4 process(int[2] indices) {\n vec4 v = vec4(0.0);\n int a[4];\n a[0] = indices[0];\n a[1] = indices[1];\n float temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += x;\n }\n }\n float mean = temp / float(${o});\n temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += (x - mean) * (x - mean);\n }\n }\n v.r = mean;\n v.g = temp / float(${o});\n\n return v;\n }`;return Object.assign(Object.assign({},e),{output:{dims:s,type:t.type,textureType:i.TextureType.packedLastDimension},shaderSource:a})})(o,e)}),a={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked,i.TextureType.unpacked]},u=(e,t,n,o)=>{const s=Object.assign(Object.assign({},a),{cacheHint:`${n}`});return Object.assign(Object.assign({},s),{get:()=>((e,t,n,o,s)=>{const a=(0,r.getGlsl)(e.session.backend.glContext.version),[u,l]=e.calculateTextureWidthAndHeight(s,i.TextureType.packedLastDimension),[c,d]=[u/4,l],h=`\n vec4 get_MeanAndVariance(int[2] mv) {\n int offset = indicesToOffset_MeanAndVariance(mv);\n vec2 coords = offsetToCoords(offset, ${c}, ${d});\n return ${a.texture2D}(MeanAndVariance, coords);\n }\n\n float process(int[4] indices) {\n int mv[2];\n mv[0] = indices[0];\n mv[1] = indices[1];\n vec4 mean_and_variance = get_MeanAndVariance(mv);\n float mean = mean_and_variance.r;\n float variance = mean_and_variance.g;\n\n int sb[1];\n sb[0] = indices[1];\n float scale = _Scale(sb);\n float b = _B(sb);\n\n return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n }`;return Object.assign(Object.assign({},t),{output:{dims:n.dims,type:n.type,textureType:i.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:o}],shaderSource:h})})(e,s,t,n,o)})},l=e=>{if(!e||3!==e.length)throw new Error("InstanceNormalization requires 3 inputs.");const t=e[0],n=e[1],r=e[2];if(t.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==t.type&&"float64"!==t.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==e[0].dims.length)throw new Error("Only support 4-D input shape.")}},7006:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createLrnProgramInfoLoader=t.parseLrnAttributes=t.lrn=void 0;const r=n(4910),i=n(5639);t.lrn=(e,t,n)=>(a(t),[e.run(s(t,n),t)]),t.parseLrnAttributes=e=>{const t=e.attributes.getFloat("alpha",1e-4),n=e.attributes.getFloat("beta",.75),i=e.attributes.getFloat("bias",1),o=e.attributes.getInt("size");return(0,r.createAttributeWithCacheKey)({alpha:t,beta:n,bias:i,size:o})};const o={name:"LRN",inputNames:["X"],inputTypes:[i.TextureType.unpacked]};function s(e,t){return Object.assign(Object.assign({},o),{cacheHint:t.cacheKey,get:()=>function(e,t){const n=e[0].dims[1],r=e[0].dims.length,s=-Math.floor((t.size-1)/2),a=Math.ceil((t.size-1)/2),u=`float(${t.alpha}) / float(${t.size})`,l=`\n float process(int indices[${r}]) {\n int c = indices[1];\n float x = _X(indices);\n float square_sum = 0.0;\n\n for (int i = ${s}; i <= ${a}; i++) {\n int idx = c + i;\n if (c >= 0 && c < ${n}) {\n indices[1] = idx;\n float j = _X(indices);\n square_sum += j * j;\n }\n }\n return x / pow(float(${t.bias}) + ${u} * square_sum, float(${t.beta}));\n }`;return Object.assign(Object.assign({},o),{cacheHint:t.cacheKey,output:{dims:e[0].dims,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:l})}(e,t)})}t.createLrnProgramInfoLoader=s;const a=e=>{if(!e||1!==e.length)throw new Error("LRN requires 1 input.");if(4!==e[0].dims.length)throw new Error('currently only support LRN for input with "NCHW" format');if("float32"!==e[0].type)throw new Error("input should be float type")}},5632:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedMatmulProgramInfoLoader=void 0;const r=n(7273),i=n(6757),o=n(5639),s=n(432),a=n(2150),u=n(8276);t.createPackedMatmulProgramInfoLoader=(e,t,n)=>{const l=(c=t.length>2,d=n.activationCacheKey,{name:"MatMul (packed)",inputNames:c?["A","B","Bias"]:["A","B"],inputTypes:c?[o.TextureType.packed,o.TextureType.packed,o.TextureType.packed]:[o.TextureType.packed,o.TextureType.packed],cacheHint:d});var c,d;return Object.assign(Object.assign({},l),{get:()=>((e,t,n,l)=>{const c=n.length>2,d=c?"value += getBiasForMatmul();":"",h=n[0].dims,p=n[1].dims,f=r.BroadcastUtil.calcShape(h,p,!0),g=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!f)throw new Error("Can't use matmul on the given tensors");const m=h[h.length-1],b=Math.ceil(m/2),y=h.length,v=p.length,w=(0,i.getGlsl)(e.session.backend.glContext.version),S=(0,s.getCoordsDataType)(f.length),_=f.length,T=(0,s.getGlChannels)(),{activationFunction:x,applyActivation:E}=(0,a.getActivationSnippet)(l),C=c?`${(0,u.getBiasForMatmul)(S,T,n[2].dims,f,!0)}`:"",P=g?`${function(e,t,n,i){let o=[],s=[];const a=n[0].dims,u=n[1].dims,l=a.length,c=u.length,d=i.length,h=d-l,p=d-c;o=a.map(((e,n)=>`coords.${t[n+h]}`)),o[l-1]="i*2",o.join(", "),s=u.map(((e,n)=>`coords.${t[n+p]}`)),s[c-2]="i*2",s.join(", ");const f=r.BroadcastUtil.getBroadcastDims(a,i),g=r.BroadcastUtil.getBroadcastDims(u,i),m=f.map((e=>`coords.${t[e+h]} = 0;`)).join("\n"),b=g.map((e=>`coords.${t[e+p]} = 0;`)).join("\n"),y=`int lastDim = coords.${t[d-1]};\n coords.${t[d-1]} = coords.${t[d-2]};\n coords.${t[d-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n ${e} coords = getOutputCoords();\n ${y}\n ${m}\n vec4 outputValue = getA(${o});\n return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n ${e} coords = getOutputCoords();\n ${y}\n ${b}\n vec4 outputValue = getB(${s});\n return outputValue;\n}`}(S,T,n,f)}`:"",O=g?"getAAtOutCoordsMatmul(i)":`getA(${function(e,t){let n="";for(let r=0;r<t-2;r++)n+=`rc.${e[r]}, `;return n+=`rc.${e[t-2]}, i*2`,n}(T,y)})`,A=g?"getBAtOutCoordsMatmul(i)":`getB(${function(e,t){let n="";for(let r=0;r<t-2;r++)n+=`rc.${e[r]}, `;return n+=`i*2, rc.${e[t-1]}`,n}(T,v)})`,k=`\n ${P}\n ${C}\n ${x}\n void main() {\n ${g?"":`${S} rc =\n getOutputCoords(); int lastDim = rc.${T[_-1]}; rc.${T[_-1]} =\n rc.${T[_-2]}; rc.${T[_-2]} = lastDim;\n `}\n\n vec4 value = vec4(0);\n for (int i = 0; i < ${b}; i++) {\n vec4 a = ${O};\n vec4 b = ${A};\n\n value += (a.rrbb * b.rgrg);\n value += (a.ggaa * b.baba);\n }\n ${d}\n ${E}\n ${w.output} = value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:f,type:n[0].type,textureType:o.TextureType.packed},shaderSource:k,hasMain:!0})})(e,l,t,n)})}},8276:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getBiasForMatmul=t.createMatmulProgramInfoLoader=t.parseMatMulAttributes=t.matMul=void 0;const r=n(7273),i=n(5639),o=n(432),s=n(2150),a=n(5632);t.matMul=(e,t,n)=>(c(t),e.session.pack?[e.run((0,a.createPackedMatmulProgramInfoLoader)(e,t,n),t)]:[e.run(l(t,n),t)]),t.parseMatMulAttributes=e=>(0,s.parseInternalActivationAttributes)(e.attributes);const u=(e,t)=>({name:"MatMul",inputNames:e?["A","B","Bias"]:["A","B"],inputTypes:e?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:t});function l(e,t){const n=u(e.length>2,t.activationCacheKey);return Object.assign(Object.assign({},n),{get:()=>function(e,t,n){const a=t[0].dims,u=t[1].dims,l=r.BroadcastUtil.calcShape(a,u,!0);if(!l)throw new Error("Can't use matmul on the given tensors");const c=(0,o.getCoordsDataType)(l.length),h=(0,o.getGlChannels)(),{activationFunction:p,applyActivation:f}=(0,s.getActivationSnippet)(n),g=t.length>2,m=g?"value += getBiasForMatmul();":"",b=g?`${d(c,h,t[2].dims,l,!1)}`:"",y=l.length,v=a.length,w=u.length,S=`\n ${p}\n ${b}\n float process(int indices[${y}]) {\n int a[${v}];\n int b[${w}];\n bcastMatmulIndices_A(indices, a);\n bcastMatmulIndices_B(indices, b);\n\n float value;\n for (int k=0; k<${a[a.length-1]}; ++k) {\n a[${v-1}] = k;\n b[${w-2}] = k;\n value += _A(a) * _B(b);\n }\n ${m}\n ${f}\n return value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:l,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:S})}(n,e,t)})}t.createMatmulProgramInfoLoader=l;const c=e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.");if("float32"!==e[0].type&&"float64"!==e[0].type||"float32"!==e[1].type&&"float64"!==e[1].type)throw new Error("inputs should be float type");if(e[0].type!==e[1].type)throw new Error("inputs types should match")};function d(e,t,n,i,o){let s="";const a=n.length,u=i.length,l=u-a;s=u<2&&a>0?"coords":n.map(((e,n)=>`coords.${t[n+l]}`)).join(", ");const c=r.BroadcastUtil.getBroadcastDims(n,i).map((e=>`coords.${t[e+l]} = 0;`)).join("\n");let d="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(d="vec4(outputValue.x)"),o?`\nvec4 getBiasForMatmul() {\n ${e} coords = getOutputCoords();\n ${c}\n vec4 outputValue = getBias(${s});\n return ${d};\n}`:`\nfloat getBiasForMatmul() {\n ${e} coords = getOutputCoords();\n ${c}\n return getBias(coords.x);\n}`}t.getBiasForMatmul=d},9:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackProgramInfoLoader=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614),a={name:"pack",inputNames:["A"],inputTypes:[i.TextureType.unpackedReversed]};t.createPackProgramInfoLoader=(e,t)=>Object.assign(Object.assign({},a),{get:()=>((e,t)=>{const n=(0,r.getGlsl)(e.session.backend.glContext.version),u=t.dims,l=u.length,c=t.dims.length,d=(0,o.getCoordsDataType)(c),h=(0,s.getChannels)("rc",c),p=(f=c,g=h,m=u[u.length-2],b=u[u.length-1],0===f||1===f?"":`\n int r = ${g[f-2]};\n int c = ${g[f-1]};\n int rp1 = ${g[f-2]} + 1;\n int cp1 = ${g[f-1]} + 1;\n bool rEdge = rp1 >= ${b};\n bool cEdge = cp1 >= ${m};\n `);var f,g,m,b;let y;y=0===l?[1,1]:1===l?[u[0],1]:[u[c-1],u[c-2]];const v=function(e,t,n){if(0===e)return"false";if(1===e)return`rc > ${t[0]}`;let r="";for(let i=e-2;i<e;i++)r+=`${n[i]} >= ${t[i-e+2]}`,i<e-1&&(r+="||");return r}(c,y,h),w=function(e,t){const n=e.length;if(0===n)return"getA(), 0, 0, 0";if(1===n)return`getA(rc),\n rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),\n 0, 0`;let r="";if(n>2)for(let e=0;e<n-2;++e)r+=`${t[e]},`;return`getA(${r}r, c),\n rEdge ? 0. : getA(${r}rp1, c),\n cEdge ? 0. : getA(${r}r, cp1),\n rEdge || cEdge ? 0. : getA(${r}rp1, cp1)`}(u,h),S=`\n void main() {\n ${d} rc = getOutputCoords();\n\n if(${v}) {\n ${n.output} = vec4(0);\n } else {\n ${p}\n\n ${n.output} = vec4(${w});\n }\n }\n `;return Object.assign(Object.assign({},a),{hasMain:!0,output:{dims:t.dims,type:t.type,textureType:i.TextureType.packed},shaderSource:S})})(e,t)})},5614:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unpackFromChannel=t.getChannels=t.getVecChannels=void 0;const r=n(432);function i(e,t){return(0,r.getGlChannels)(t).map((t=>`${e}.${t}`))}t.getVecChannels=i,t.getChannels=function(e,t){return 1===t?[e]:i(e,t)},t.unpackFromChannel=function(){return"\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "}},5565:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parsePadAttributesV11=t.padV11=t.parsePadAttributesV2=t.padV2=void 0;const r=n(4910),i=n(7273),o=n(6757),s=n(5639),a={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};t.padV2=(e,t,n)=>(c(t),[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>l(e,t[0],n)}),t)]),t.parsePadAttributesV2=e=>{const t=e.attributes.getString("mode","constant"),n=e.attributes.getFloat("value",0),i=e.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:t,value:n,pads:i})},t.padV11=(e,n,r)=>{d(n);const i=u(e,n,r);return(0,t.padV2)(e,[n[0]],i)},t.parsePadAttributesV11=e=>e.attributes.getString("mode","constant");const u=(e,t,n)=>{if(!e.session.isInitializer(t[1].dataId)||t.length>=3&&!e.session.isInitializer(t[2].dataId))throw new Error("dynamic pad attributes are not allowed");const i=Array.from(t[1].integerData),o=t.length>=3?t[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:i,value:o})},l=(e,t,n)=>{const r=i.ShapeUtil.padShape(t.dims.slice(),n.pads),o=r.length,a=`\n ${h(e,t,n)}\n float process(int[${o}] indices) {\n return padA(indices);\n }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:r,type:t.type,textureType:s.TextureType.unpacked},shaderSource:a}},c=e=>{if(!e||1!==e.length)throw new Error("Pad requires 1 input");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")},d=e=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==e[1].type)throw new Error("Invalid input type.");if(e.length>=3&&"string"===e[2].type)throw new Error("Invalid input type.")},h=(e,t,n)=>{const r=(0,o.getGlsl)(e.session.backend.glContext.version),[a,u]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),l=i.ShapeUtil.computeStrides(t.dims);switch(n.mode){case"constant":return p(r,t.dims,l,a,u,n.pads,n.value);case"reflect":return f(r,t.dims,l,a,u,n.pads);case"edge":return g(r,t.dims,l,a,u,n.pads);default:throw new Error("Invalid mode")}},p=(e,t,n,r,i,o,s)=>{const a=t.length;let u="";for(let e=a-1;e>=0;--e)u+=`\n k = m[${e}] - ${o[e]};\n if (k < 0) return constant;\n if (k >= ${t[e]}) return constant;\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${a}]) {\n const float constant = float(${s});\n int offset = 0;\n int k = 0;\n ${u}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `},f=(e,t,n,r,i,o)=>{const s=t.length;let a="";for(let e=s-1;e>=0;--e)a+=`\n k = m[${e}] - ${o[e]};\n if (k < 0) { k = -k; }\n {\n const int _2n_1 = ${2*(t[e]-1)};\n k = int( mod( float(k), float(_2n_1) ) ) ;\n if(k >= ${t[e]}) { k = _2n_1 - k; }\n }\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `},g=(e,t,n,r,i,o)=>{const s=t.length;let a="";for(let e=s-1;e>=0;--e)a+=`\n k = m[${e}] - ${o[e]};\n if (k < 0) k = 0;\n if (k >= ${t[e]}) k = ${t[e]-1};\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `}},2834:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.globalMaxPool=t.parseMaxPoolAttributes=t.maxPool=t.parseGlobalAveragePoolAttributes=t.globalAveragePool=t.parseAveragePoolAttributes=t.averagePool=void 0;const r=n(4910),i=n(7273),o=n(5639);t.averagePool=(e,t,n)=>{d(t);const r={name:"AveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[e.run(Object.assign(Object.assign({},r),{get:()=>s(t,r,!1,n)}),t)]},t.parseAveragePoolAttributes=e=>{const t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=0!==e.attributes.getInt("count_include_pad",0),o=e.attributes.getInts("kernel_shape"),s=e.attributes.getInts("strides",[]),a=e.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:t,ceilMode:n,countIncludePad:i,kernelShape:o,strides:s,pads:a})};const s=(e,t,n,r)=>{const[s,a]=u(e,r,n),l=i.ShapeUtil.size(s.kernelShape);let c="";s.countIncludePad?c+=`value /= float(${l});`:c+=`value /= float(${l} - pad);`;const d=`\n ${h(e[0].dims,s,"value += _X(x);",c,"0.0")}\n `;return Object.assign(Object.assign({},t),{output:{dims:a,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:d})};t.globalAveragePool=(e,t,n)=>{d(t);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[e.run(Object.assign(Object.assign({},r),{get:()=>s(t,r,!0,n)}),t)]},t.parseGlobalAveragePoolAttributes=e=>{const t=0!==e.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:t,kernelShape:[],strides:[],pads:[]})},t.maxPool=(e,t,n)=>{d(t);const r={name:"MaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[e.run(Object.assign(Object.assign({},r),{get:()=>a(t,r,!1,n)}),t)]},t.parseMaxPoolAttributes=e=>{const t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=e.attributes.getInts("kernel_shape"),o=e.attributes.getInts("strides",[]),s=e.attributes.getInts("pads",[]),a=e.attributes.getInt("storage_order",0),u=e.attributes.getInts("dilations",[]);if(0!==a)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:t,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:o,pads:s,storageOrder:a,dilations:u})};const a=(e,t,n,r)=>{const[i,s]=u(e,r,n),a=`\n ${h(e[0].dims,i,"\n value = max(_X(x), value);\n ","","-1e5")}\n `;return Object.assign(Object.assign({},t),{output:{dims:s,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:a})},u=(e,t,n)=>{const r=e[0].dims.slice(),o=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),a=t.strides.slice(),u=o?t.dilations.slice():[],l=t.pads.slice();i.PoolConvUtil.adjustPoolAttributes(n,r,s,a,u,l);const c=i.PoolConvUtil.computePoolOutputShape(n,r,a,u,s,l,t.autoPad),d=Object.assign({},t);return o?Object.assign(d,{kernelShape:s,strides:a,pads:l,dilations:u,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:s,strides:a,pads:l,cacheKey:t.cacheKey}),[d,c]},l={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},c={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};t.globalMaxPool=(e,t)=>(d(t),[e.run(Object.assign(Object.assign({},c),{get:()=>a(t,c,!0,l)}),t)]);const d=e=>{if(!e||1!==e.length)throw new Error("Pool ops requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")},h=(e,t,n,r,o)=>{const s=e.length;if(t.kernelShape.length<=2){const i=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],u=t.pads[t.pads.length/2-1],l=t.pads[t.pads.length-1],c=e[s-1];let d="",h="",p="";if(d=u+l!==0?`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n if (x[${s} - 1] < 0 || x[${s} - 1] >= ${c}) {\n pad++;\n continue;\n }\n ${n}\n }`:`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n ${n}\n }`,2===t.kernelShape.length){const n=t.kernelShape[t.kernelShape.length-2],r=t.strides[t.strides.length-2],o=t.pads[t.pads.length/2-2],a=t.pads[t.pads.length-2],u=e[s-2];h=o+a!==0?`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n if (x[${s} - 2] < 0 || x[${s} - 2] >= ${u}) {\n pad+= ${i};\n continue;\n }\n `:`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n `,p="\n }\n "}return`\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n\n float value = ${o};\n int pad = 0;\n ${h}\n ${d}\n ${p}\n ${r}\n return value;\n }\n `}{const a=i.ShapeUtil.size(t.kernelShape),u=i.ShapeUtil.computeStrides(t.kernelShape),l=u.length,c=t.pads.length,d=f(l),h=p(e,"inputDims"),g=p(t.pads,"pads"),m=p(u,"kernelStrides"),b=p(t.strides,"strides");let y="";return y=t.pads.reduce(((e,t)=>e+t))?`\n if (x[j] >= inputDims[j] || x[j] < 0) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n ${n}\n }`:`\n }\n ${n}\n `,`\n ${d}\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n int offset[${l}];\n int pads[${c}];\n int inputDims[${s}];\n int kernelStrides[${l}];\n int strides[${l}];\n ${g}\n ${h}\n ${b}\n ${m}\n\n float value = ${o};\n int pad = 0;\n bool isPad = false;\n for (int i = 0; i < ${a}; i++) {\n offsetToIndices(i, kernelStrides, offset);\n isPad = false;\n for (int j = ${s} - ${l}; j < ${s}; j++) {\n x[j] = indices[j] * strides[j - ${s} + ${l}]\n + offset[j - ${s} + ${l}] - pads[j - 2];\n ${y}\n }\n ${r}\n\n return value;\n }\n `}},p=(e,t)=>{let n="";for(let r=0;r<e.length;r++)n+=`\n ${t}[${r}] = ${e[r]};\n `;return n},f=e=>`\n void offsetToIndices(int offset, int[${e}] strides, out int[${e}] indices) {\n if (${e} == 0) {\n return;\n }\n for (int i = 0; i < ${e} - 1; ++i) {\n indices[i] = offset / strides[i];\n offset -= indices[i] * strides[i];\n }\n indices[${e} - 1] = offset;\n }`},1010:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reduceLogSumSquare=t.reduceLogSum=t.reduceProd=t.reduceMin=t.reduceMax=t.reduceMean=t.reduceSum=t.parseReduceAttributes=void 0;const r=n(4910),i=n(6145),o=n(7273),s=n(5639),a=(e,t,n,r,i)=>{l(t);const o={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[e.run(Object.assign(Object.assign({},o),{cacheHint:n.cacheKey,get:()=>u(e,t,n,r,i,o)}),t)]};t.parseReduceAttributes=e=>{const t=e.attributes.getInts("axes",[]),n=1===e.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:t,keepDims:n})};const u=(e,t,n,r,i,a)=>{const u=[],l=t[0].dims.length||1,c=[],d=o.ShapeUtil.normalizeAxes(n.axes,t[0].dims.length),h=i(t,d);let p=h[1];for(let e=0;e<t[0].dims.length;e++)d.indexOf(e)>=0||0===d.length?(n.keepDims&&u.push(1),p=`\n for(int j${e} = 0; j${e} < ${t[0].dims[e]}; j${e}++) {\n inputIdx[${e}] = j${e};\n ${p}\n }`):(c.push(`inputIdx[${e}] = outputIdx[${u.length}];`),u.push(t[0].dims[e]));const f=`\n float process(int outputIdx[${u.length||1}]) {\n float value; // final result\n int inputIdx[${l}]; // addressing input data\n ${c.join("\n")}\n ${h[0]} // init ops for reduce max/min\n ${p}\n ${h[2]} // final computation for reduce mean\n return value;\n }`;return Object.assign(Object.assign({},a),{output:{dims:u,type:t[0].type,textureType:s.TextureType.unpacked},shaderSource:f})},l=e=>{if(!e||1!==e.length)throw new Error("Reduce op requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.")};t.reduceSum=(e,t,n)=>a(e,t,n,"ReduceSum",(()=>["value = 0.0;","value += _A(inputIdx);",""])),t.reduceMean=(e,t,n)=>a(e,t,n,"ReduceMean",((e,t)=>{let n=1;for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&(n*=e[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]})),t.reduceMax=(e,t,n)=>a(e,t,n,"ReduceMax",((e,t)=>{const n=[];for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]})),t.reduceMin=(e,t,n)=>a(e,t,n,"ReduceMin",((e,t)=>{const n=[];for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]})),t.reduceProd=(e,t,n)=>a(e,t,n,"ReduceProd",(()=>["value = 1.0;","value *= _A(inputIdx);",""])),t.reduceLogSum=(e,t,n)=>a(e,t,n,"ReduceLogSum",(()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"])),t.reduceLogSumSquare=(e,t,n)=>a(e,t,n,"ReduceLogSumSquare",(()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""]))},7379:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isReshapeCheap=t.processDims3D=t.createPackedReshape3DProgramInfoLoader=void 0;const r=n(7273),i=n(6757),o=n(5639),s=n(5614);t.createPackedReshape3DProgramInfoLoader=(e,t,n)=>{const a=(e=>({name:"Reshape (packed)",inputTypes:[o.TextureType.packed],inputNames:["A"],cacheHint:`${e}`}))(n);return Object.assign(Object.assign({},a),{get:()=>((e,t,n,a)=>{const u=t.dims,l=a;let c="";for(let e=0;e<4;e++){let t="";switch(e){case 0:t="outputCoords = rc;";break;case 1:t="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:t="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:t="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}c+=`\n ${t}\n ${e>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n int flattenedIndex = getFlattenedIndex(outputCoords);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n ${e>0?"}":""}\n `}const d=(0,i.getGlsl)(e.session.backend.glContext.version),h=`\n ${function(e){const t=r.ShapeUtil.computeStrides(e),n=["b","r","c"],i="index";return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${t.map(((e,r)=>`int ${n[r]} = ${i} / ${e}; ${r===t.length-1?`int ${n[r+1]} = ${i} - ${n[r]} * ${e}`:`index -= ${n[r]} * ${e}`};`)).join("")}\n return ivec3(b, r, c);\n }\n `}(u)}\n ${function(e){const t=r.ShapeUtil.computeStrides(e);return`\n int getFlattenedIndex(ivec3 coords) {\n // reverse y, z order\n return coords.x * ${t[0]} + coords.z * ${t[1]} + coords.y;\n }\n`}(l)}\n ${(0,s.unpackFromChannel)()}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.0);\n\n ivec3 outputCoords;\n int rows = ${l[2]};\n int cols = ${l[1]};\n\n ${c}\n ${d.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:l,type:t.type,textureType:o.TextureType.packed},shaderSource:h,hasMain:!0})})(e,t,a,n)})},t.processDims3D=function(e){if(0===e.length)return[1,1,1];let t=1;for(let n=0;n<e.length-2;++n)t*=e[n];return[t,e.length>1?e[e.length-2]:1,e[e.length-1]]},t.isReshapeCheap=function(e,t){let n=!1;return n=0===e.length||0===t.length||(e.length<2||t.length<2?e[e.length-1]===t[t.length-1]:e[e.length-1]===t[t.length-1]&&e[e.length-2]===t[t.length-2]),n}},8126:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reshape=void 0;const r=n(7273);t.reshape=(e,t)=>{const n=r.ShapeUtil.calculateReshapedDims(t[0].dims,t[1].integerData);return e.session.pack?[e.reshapePacked(t[0],n)]:[e.reshapeUnpacked(t[0],n)]}},2801:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseResizeAttributesV11=t.parseResizeAttributesV10=t.resize=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614),a=n(3980),u={name:"Resize",inputNames:["A"],inputTypes:[i.TextureType.packed]};t.resize=(e,t,n)=>((0,a.validateInputs)(t,n),[e.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>l(e,t,n)}),t)]),t.parseResizeAttributesV10=e=>(0,a.parseUpsampleAttributes)(e,10),t.parseResizeAttributesV11=e=>(0,a.parseUpsampleAttributes)(e,11);const l=(e,t,n)=>{const a=(0,r.getGlsl)(e.session.backend.glContext.version),[l,d]=c(t,n);if(l.every((e=>1===e))&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},u),{output:{dims:d,type:t[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:`void main() {\n vec4 v = ${a.texture2D}(X, TexCoords);\n ${a.output} = v;\n }`});const h=d.length;if(h<2)throw new Error(`output dimension should be at least 2, but got ${h}`);const p=d[h-2],f=d[h-1],g=t[0].dims;if(h!==g.length)throw new Error(`output dimension should match input ${g.length}, but got ${h}`);const m=g[h-2],b=g[h-1],y=l[h-2],v=l[h-1];let w="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":w="\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n ";break;case"half_pixel":w="\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n ";break;case"pytorch_half_pixel":w=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 fcoords = vec4(coords);\n return vec4(\n ${f}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n ${f}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n );\n }\n `;break;case"align_corners":w=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 resized = vec4(${f}.0 - 1.0, ${p}.0 - 1.0, ${f}.0 - 1.0,\n ${p}.0 - 1.0);\n vec4 original = vec4(${b}.0 - 1.0, ${m}.0 - 1.0, ${b}.0 - 1.0,\n ${m}.0 - 1.0);\n vec4 new_scale = original / resized;\n return vec4(coords) * new_scale;\n }\n `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}const S=(0,o.getCoordsDataType)(h),_=`\n const vec2 inputWH = vec2(${m}.0, ${b}.0);\n const vec4 scaleWHWH = vec4(float(${y}), float(${v}), float(${y}), float(${v}));\n ${(0,s.unpackFromChannel)()}\n ${w}\n float getAValue(int x10, int r, int c, int d) {\n return getChannel(getA(x10, r, c, d), vec2(c, d));\n }\n void main() {\n ${S} rc = getOutputCoords();\n\n int batch = rc[0];\n int depth = rc[1];\n\n // retrieve the 4 coordinates that is used in the 4 packed output values.\n ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n // calculate the source index in fraction\n vec4 sourceFrac = getSourceFracIndex(coords);\n\n // get the lower and upper bound of the 4 values that will be packed into one texel.\n ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n bool hasNextRow = rc.w < ${p-1};\n bool hasNextCol = rc.z < ${f-1};\n\n // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n vec4 topLeft = vec4(\n getAValue(batch, depth, x00.x, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n vec4 topRight = vec4(\n getAValue(batch, depth, x00.x, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n vec4 bottomLeft = vec4(\n getAValue(batch, depth, x00.z, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n vec4 bottomRight = vec4(\n getAValue(batch, depth, x00.z, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n // calculate the interpolation fraction on u and v direction\n vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n ${a.output} = vec4(newValue);\n }\n `;return Object.assign(Object.assign({},u),{output:{dims:d,type:t[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:_})},c=(e,t)=>{const n=e[0].dims;let r,i=t.scales;if(0===i.length){const o=e[t.scalesInputIdx];if(o&&0!==o.size){if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=d(o,t.mode,t.isResize)}else{const o=e[t.sizesInputIdx];if(!o||0===o.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(o.integerData),i=h(r,n,t.mode,t.isResize)}}else if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const o=r||n.map(((e,t)=>Math.floor(e*i[t])));return[i,o]},d=(e,t,n)=>{const r=Array.from(e.floatData);return(0,a.scalesValidation)(r,t,n),r},h=(e,t,n,r)=>{const i=t.length,o=new Array(i);for(let n=0,r=i;n<r;n++)if(0===t[n]){if(0!==e[n])throw new Error("Input dim is zero but required output dim is non-zero.");o[n]=1}else o[n]=e[n]/t[n];return(0,a.scalesValidation)(o,n,r),o}},565:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shape=void 0;const r=n(9240);t.shape=(e,t)=>(i(t),[new r.Tensor([t[0].dims.length],"int32",void 0,void 0,new Int32Array(t[0].dims))]);const i=e=>{if(!e||1!==e.length)throw new Error("Shape requires 1 input.")}},2444:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sliceV10=t.parseSliceAttributes=t.slice=void 0;const r=n(4910),i=n(6145),o=n(7273),s=n(5639),a={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};t.slice=(e,t,n)=>(l(t),[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(e,t[0],n)}),t)]),t.parseSliceAttributes=e=>{const t=e.attributes.getInts("starts"),n=e.attributes.getInts("ends"),i=e.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:t,ends:n,axes:i})};const u=(e,t,n)=>{const r=0===n.axes.length?t.dims.slice(0).map(((e,t)=>t)):n.axes,i=o.ShapeUtil.normalizeAxes(r,t.dims.length),u=n.starts.map(((e,n)=>e>t.dims[i[n]]-1?t.dims[i[n]]:o.ShapeUtil.normalizeAxis(e,t.dims[i[n]]))),l=n.ends.map(((e,n)=>e>t.dims[i[n]]-1?t.dims[i[n]]:o.ShapeUtil.normalizeAxis(e,t.dims[i[n]]))),c=t.dims.slice(),d=[];for(let e=0;e<i.length;e++)c[i[e]]=l[e]-u[e],u[e]>0&&d.push(`outputIdx[${i[e]}] += ${u[e]};`);const h=`\n float process(int outputIdx[${c.length}]) {\n ${d.join("\n ")}\n return _A(outputIdx);\n }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:t.type,textureType:s.TextureType.unpacked},shaderSource:h})},l=e=>{if(!e||1!==e.length)throw new Error("Slice requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.")};t.sliceV10=(e,t)=>{d(t);const n=c(e,t);return[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(e,t[0],n)}),[t[0]])]};const c=(e,t)=>{if(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)||t.length>=4&&!e.session.isInitializer(t[3].dataId)||t.length>=5&&!e.session.isInitializer(t[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(t.length>=5&&t[4].integerData.some((e=>1!==e)))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(t[1].integerData),r=Array.from(t[2].integerData),i=t.length>=4?Array.from(t[3].integerData):[];return{starts:n,ends:r,axes:i,cacheKey:`${i};${n};${r}`}},d=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if("int32"!==e[1].type||1!==e[1].dims.length)throw new Error("Invalid input type.");if("int32"!==e[2].type||1!==e[2].dims.length)throw new Error("Invalid input type.");if(e.length>=4&&("int32"!==e[3].type||1!==e[3].dims.length))throw new Error("Invalid input type.");if(e.length>=5&&("int32"!==e[4].type||1!==e[4].dims.length))throw new Error("Invalid input type.")}},815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.softmaxV13=t.parseSoftmaxAttributesV13=t.parseSoftmaxAttributes=t.softmax=void 0;const r=n(4910),i=n(7273),o=n(6757),s=n(5639),a=n(5707),u={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},l={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},c={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};t.softmax=(e,t,n)=>{g(t);const r=t[0].dims.slice(),o=i.ShapeUtil.normalizeAxis(n.axis,r.length),s=i.ShapeUtil.sizeToDimension(r,o),a=i.ShapeUtil.sizeFromDimension(r,o);return d(e,t,n,s,a)},t.parseSoftmaxAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",1)}),t.parseSoftmaxAttributesV13=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",-1)}),t.softmaxV13=(e,t,n)=>{g(t);const o=t[0].dims.slice(),s=i.ShapeUtil.normalizeAxis(n.axis,o.length),u=o.length,l=s!==u-1,c=[];let h,p=[],f=[];l&&(p=Array.from({length:u}).map(((e,t)=>t)),p[s]=u-1,p[u-1]=s,p.map((e=>c.push(o[e]))),h=(0,r.createAttributeWithCacheKey)({perm:p}),f=(0,a.transpose)(e,t,h));const m=l?i.ShapeUtil.sizeToDimension(c,u-1):i.ShapeUtil.sizeToDimension(o,u-1),b=l?i.ShapeUtil.sizeFromDimension(c,u-1):i.ShapeUtil.sizeFromDimension(o,u-1),y=d(e,l?f:t,n,m,b);return l?(0,a.transpose)(e,y,h):y};const d=(e,t,n,r,i)=>{const o=h(e,t[0],r,i,[r]),s=e.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>o}),t),a=p(e,t[0],r,i,o.output.dims,[r]),d=e.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>a}),[t[0],s]),g=f(e,t[0],r,i,o.output.dims,a.output.dims);return[e.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>g}),[t[0],s,d])]},h=(e,t,n,r,i)=>{const[a,l]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),c=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const d=(0,o.getGlsl)(e.session.backend.glContext.version),h=`\n float process(int[${c}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float max = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset, ${a},\n ${l} )));\n for(int i=1; i<${r}; ++i)\n {\n float current = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${a}, ${l})));\n if(current > max)\n max = current;\n }\n\n return max;\n }`;return Object.assign(Object.assign({},u),{output:{dims:i,type:t.type,textureType:s.TextureType.unpacked},shaderSource:h})},p=(e,t,n,r,i,a)=>{const[u,c]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),d=a.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==a.length)throw new Error("Dimensionality of the output should be 1");if(a[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const h=`\n float process(int[${d}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float norm_factor = 0.0;\n float max = _Max(indices);\n for(int i=0; i<${r}; ++i)\n {\n norm_factor += exp(getColorAsFloat(${(0,o.getGlsl)(e.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${u}, ${c}))) - max);\n }\n\n return norm_factor;\n }`;return Object.assign(Object.assign({},l),{output:{dims:a,type:t.type,textureType:s.TextureType.unpacked},shaderSource:h})},f=(e,t,n,r,i,o)=>{const[a,u]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),l=t.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length||1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n||o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const d=`\n float process(int[${l}] indices) {\n\n // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n int offset = coordsToOffset(TexCoords, ${a}, ${u});\n\n //determine the logical row for this index\n int logical_row_index[1];\n logical_row_index[0] = offset / ${r};\n\n float norm_factor = _Norm(logical_row_index);\n\n // avoid possible division by 0\n // if norm_facor is 0, all elements are zero\n // if so, return 0\n if(norm_factor == 0.0)\n return 0.0;\n\n return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n }`;return Object.assign(Object.assign({},c),{output:{dims:t.dims,type:t.type,textureType:s.TextureType.unpacked},shaderSource:d})},g=e=>{if(!e||1!==e.length)throw new Error("Softmax requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type")}},564:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseSplitAttributes=t.split=void 0;const r=n(4910),i=n(7273),o=n(5639),s={name:"Split",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};t.split=(e,t,n)=>{l(t);const r=i.ShapeUtil.normalizeAxis(n.axis,t[0].dims.length),o=a(e,t,r,n),c=[];for(let i=0;i<o;++i)c.push(e.run(Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey};${i}`,get:()=>u(e,t[0],n,r,i)}),t));return c},t.parseSplitAttributes=e=>{const t=e.attributes.getInt("axis",0),n=e.attributes.getInts("split",[]),i=e.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:t,split:n,numOutputs:i})};const a=(e,t,n,r)=>{const[,o]=i.SplitUtil.splitShape(t[0].dims,n,r.split,r.numOutputs);return o.length},u=(e,t,n,r,a)=>{const[u,l]=i.SplitUtil.splitShape(t.dims,r,n.split,n.numOutputs),c=l[a],d=u[a],h=`\n float process(int indices[${d.length}]) {\n indices[${r}] += ${c};\n return _A(indices);\n }\n `;return Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey}:${a}`,output:{dims:d,type:t.type,textureType:o.TextureType.unpacked},shaderSource:h})},l=e=>{if(!e||1!==e.length)throw new Error("Split requires one input.");if("int8"!==e[0].type&&"uint8"!==e[0].type&&"int16"!==e[0].type&&"uint16"!==e[0].type&&"int32"!==e[0].type&&"uint32"!==e[0].type&&"float32"!==e[0].type&&"float64"!==e[0].type&&"bool"!==e[0].type)throw new Error("Invalid input type.")}},5416:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseSqueezeAttributes=t.squeezeV13=t.squeeze=void 0;const r=n(7273);t.squeeze=(e,t,n)=>{i(t);const o=r.ShapeUtil.squeezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],o)]},t.squeezeV13=(e,n)=>(o(n),(0,t.squeeze)(e,[n[0]],Array.from(n[1].integerData))),t.parseSqueezeAttributes=e=>e.attributes.getInts("axes");const i=e=>{if(!e||1!==e.length)throw new Error("Squeeze requires 1 input.");if("string"===e[0].type)throw new Error("invalid input tensor types.")},o=e=>{if(!e||2!==e.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==e[1].type)throw new Error("Invalid input type.")}},1240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sum=void 0;const r=n(6757),i=n(5639);t.sum=(e,t)=>{s(t);const n={name:"Sum",inputNames:t.map(((e,t)=>`X${t}`)),inputTypes:new Array(t.length).fill(i.TextureType.unpacked)};return[e.run(Object.assign(Object.assign({},n),{get:()=>o(e,t,n)}),t)]};const o=(e,t,n)=>{const o=(0,r.getGlsl)(e.session.backend.glContext.version),s=t[0].dims.slice(),a=`\n void main() {\n vec4 result = ${t.map(((e,t)=>`${o.texture2D}(X${t},TexCoords)`)).join(" + ")};\n ${o.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:s,type:t[0].type,textureType:i.TextureType.unpacked},hasMain:!0,shaderSource:a})},s=e=>{if(!e||0===e.length)throw new Error("Sum requires inputs.");const t=e[0].dims.length;for(let n=1;n<e.length;n++){if(t!==e[n].dims.length)throw new Error("Input shapes are mismatched.");for(let r=0;r<t;r++)if(e[0].dims[r]!==e[n].dims[r])throw new Error("Input shapes are not matched.")}if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.");for(let t=1;t<e.length;t++)if(e[0].type!==e[t].type)throw new Error("Input types are not matched.")}},5944:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tile=void 0;const r=n(6145),i=n(5639);t.tile=(e,t)=>{s(t);const n={name:"Tile",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};return[e.run(Object.assign(Object.assign({},n),{get:()=>o(e,t,n)}),t)]};const o=(e,t,n)=>{const r=t[0].dims.slice(),o=new Array(r.length),s=[];for(let e=0;e<r.length;e++)o[e]=r[e]*t[1].numberData[e],s.push(`inputIdx[${e}] = int(mod(float(outputIdx[${e}]), ${r[e]}.));`);const a=o.length,u=`\n float process(int outputIdx[${a}]) {\n int inputIdx[${a}];\n ${s.join("\n")}\n return _A(inputIdx);\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:o,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:u})},s=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 input.");if(1!==e[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(e[1].dims[0]!==e[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.");if("int32"!==e[1].type&&"int16"!==e[1].type)throw new Error("Invalid repeat type.")}},5707:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseTransposeAttributes=t.transpose=void 0;const r=n(4910),i=n(7273),o=n(5639),s={name:"Transpose",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};t.transpose=(e,t,n)=>(d(t),[e.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(e,t[0],n.perm)}),t)]),t.parseTransposeAttributes=e=>(0,r.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const a=(e,t,n)=>{const r=t.dims;n=u(r,n);const i=l(r,n),a=r.length,d=`\n ${c("perm",n,a)}\n float process(int indices[${a}]) {\n int a[${a}];\n perm(a, indices);\n return _A(a);\n }`;return Object.assign(Object.assign({},s),{output:{dims:i,type:t.type,textureType:o.TextureType.unpacked},shaderSource:d})},u=(e,t)=>(t&&t.length!==e.length&&(t=[...e.keys()].reverse()),t),l=(e,t)=>(t=u(e,t),i.ShapeUtil.sortBasedOnPerm(e,t)),c=(e,t,n)=>{const r=[];r.push(`void ${e}(out int a[${n}], int src[${n}]) {`);for(let e=0;e<n;++e)r.push(`\ta[${t[e]}]=src[${e}];`);return r.push("\t}"),r.join("\n")},d=e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("input should be float tensor")}},2488:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeAsUint8=void 0;const r=n(6757),i=n(5639);t.encodeAsUint8=(e,t)=>{const n=t.shape,o=(0,r.getGlsl)(e.session.backend.glContext.version),s=`\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n highp vec4 encodeAsUint8(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float value = ${o.texture2D}(X,TexCoords).r;\n ${o.output} = encodeAsUint8(value);\n }`,a={name:"Uint8Encode",inputTypes:[i.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:t.tensor.type,textureType:i.TextureType.downloadUint8AsFloat},shaderSource:s,hasMain:!0};return e.executeProgram(a,[t.tensor])}},9087:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tanh=t.tan=t.sqrt=t.sin=t.sigmoid=t.relu=t.not=t.neg=t.log=t.parseLeakyReluAttributes=t.leakyRelu=t.identity=t.floor=t.exp=t.parseEluAttributes=t.elu=t.cos=t.ceil=t.clipV11=t.parseClipAttributes=t.clip=t.atan=t.asin=t.acos=t.abs=t.glslTanh=t.glslTan=t.glslSqrt=t.glslSigmoid=t.glslRelu=t.glslSin=t.glslNot=t.glslNeg=t.glslLog=t.glslLeakyRelu=t.glslIdentity=t.glslClip=t.glslFloor=t.glslExp=t.glslElu=t.glslCos=t.glslCeil=t.glslAtan=t.glslAsin=t.glslAcos=t.glslAbs=void 0;const r=n(4910),i=n(7273),o=n(1997),s=n(6757),a=n(5639);function u(){return A("abs")}function l(){return A("acos")}function c(){return A("asin")}function d(){return A("atan")}function h(){return A("ceil")}function p(){return A("cos")}function f(e){const t="elu";return{body:`\n const float alpha = float(${e});\n\n float ${t}_(float a) {\n return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function g(){return A("exp")}function m(){return A("floor")}function b(e,t){const n="clip";return{body:`\n const float min = float(${e});\n const float max = float(${t});\n\n float ${n}_(float a) {\n return clamp(a, min, max);\n }\n vec4 ${n}_(vec4 v) {\n return clamp(v, min, max);\n }\n `,name:n,type:o.FunctionType.ValueBased}}function y(){const e="indentity";return{body:`\n float ${e}_(float a) {\n return a;\n }\n vec4 ${e}_(vec4 v) {\n return v;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function v(e){const t="leakyRelu";return{body:`\n const float alpha = float(${e});\n\n float ${t}_(float a) {\n return a < 0.0 ? a * alpha : a;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function w(){return A("log")}function S(){const e="neg";return{body:`\n float ${e}_(float a) {\n return -a;\n }\n vec4 ${e}_(vec4 v) {\n return -v;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function _(){const e="not";return{body:`\n float ${e}_(float a) {\n return float( ! bool(a) );\n }\n bool ${e}_(bool a) {\n return !a;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n }\n bvec4 ${e}_(bvec4 v) {\n return bvec4(!v.x, !v.y, !v.z, !v.w);\n }\n `,name:e,type:o.FunctionType.ValueBased}}function T(){return A("sin")}function x(){const e="relu";return{body:`\n float ${e}_(float a) {\n return max( a, 0.0 );\n }\n vec4 ${e}_(vec4 v) {\n return max( v, 0.0 );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function E(){const e="sigmoid";return{body:`\n float ${e}_(float a) {\n return 1.0 / (1.0 + exp(-a));\n }\n vec4 ${e}_(vec4 v) {\n return 1.0 / (1.0 + exp(-v));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function C(){return A("sqrt")}function P(){return A("tan")}function O(){const e="tanh";return{body:`\n float ${e}_(float a) {\n a = clamp(a, -10., 10.);\n a = exp(2.*a);\n return (a - 1.) / (a + 1.);\n }\n vec4 ${e}_(vec4 v) {\n v = clamp(v, -10., 10.);\n v = exp(2.*v);\n return (v - 1.) / (v + 1.);\n }\n `,name:e,type:o.FunctionType.ValueBased}}function A(e){return{body:`\n float ${e}_(float a) {\n return ${e}(a);\n }\n vec4 ${e}_(vec4 v) {\n return ${e}(v);\n }\n `,name:e,type:o.FunctionType.ValueBased}}t.glslAbs=u,t.glslAcos=l,t.glslAsin=c,t.glslAtan=d,t.glslCeil=h,t.glslCos=p,t.glslElu=f,t.glslExp=g,t.glslFloor=m,t.glslClip=b,t.glslIdentity=y,t.glslLeakyRelu=v,t.glslLog=w,t.glslNeg=S,t.glslNot=_,t.glslSin=T,t.glslRelu=x,t.glslSigmoid=E,t.glslSqrt=C,t.glslTan=P,t.glslTanh=O;const k=(e,t,n,r)=>{const i=e.session.pack?a.TextureType.packed:a.TextureType.unpacked,o={name:n.name,inputTypes:[i],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},o),{get:()=>((e,t,n,r)=>{const i=e.session.pack?a.TextureType.packed:a.TextureType.unpacked,o=(0,s.getGlsl)(e.session.backend.glContext.version);return Object.assign(Object.assign({},t),{output:{dims:n.dims,type:n.type,textureType:i},shaderSource:`\n ${r.body}\n void main() {\n vec4 v = ${o.texture2D}(A, TexCoords);\n v = ${r.name}_(v);\n ${o.output} = v;\n }\n `,hasMain:!0})})(e,o,t,n)})};t.abs=(e,t)=>[e.run(k(e,t[0],u()),t)],t.acos=(e,t)=>[e.run(k(e,t[0],l()),t)],t.asin=(e,t)=>[e.run(k(e,t[0],c()),t)],t.atan=(e,t)=>[e.run(k(e,t[0],d()),t)],t.clip=(e,t,n)=>[e.run(k(e,t[0],b(n.min,n.max),n.cacheKey),t)],t.parseClipAttributes=e=>(0,r.createAttributeWithCacheKey)({min:e.attributes.getFloat("min",i.MIN_CLIP),max:e.attributes.getFloat("max",i.MAX_CLIP)}),t.clipV11=(e,n)=>{const r=I(e,n);return(0,t.clip)(e,[n[0]],r)};const I=(e,t)=>{if(t.length>=3&&(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=t.length>=3?t[1].numberData[0]:i.MIN_CLIP,o=t.length>=3?t[2].numberData[0]:i.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:o})};t.ceil=(e,t)=>[e.run(k(e,t[0],h()),t)],t.cos=(e,t)=>[e.run(k(e,t[0],p()),t)],t.elu=(e,t,n)=>[e.run(k(e,t[0],f(n.alpha),n.cacheKey),t)],t.parseEluAttributes=e=>(0,r.createAttributeWithCacheKey)({alpha:e.attributes.getFloat("alpha",1)}),t.exp=(e,t)=>[e.run(k(e,t[0],g()),t)],t.floor=(e,t)=>[e.run(k(e,t[0],m()),t)],t.identity=(e,t)=>[e.run(k(e,t[0],y()),t)],t.leakyRelu=(e,t,n)=>[e.run(k(e,t[0],v(n.alpha),n.cacheKey),t)],t.parseLeakyReluAttributes=e=>(0,r.createAttributeWithCacheKey)({alpha:e.attributes.getFloat("alpha",.01)}),t.log=(e,t)=>[e.run(k(e,t[0],w()),t)],t.neg=(e,t)=>[e.run(k(e,t[0],S()),t)],t.not=(e,t)=>[e.run(k(e,t[0],_()),t)],t.relu=(e,t)=>[e.run(k(e,t[0],x()),t)],t.sigmoid=(e,t)=>[e.run(k(e,t[0],E()),t)],t.sin=(e,t)=>[e.run(k(e,t[0],T()),t)],t.sqrt=(e,t)=>[e.run(k(e,t[0],C()),t)],t.tan=(e,t)=>[e.run(k(e,t[0],P()),t)],t.tanh=(e,t)=>[e.run(k(e,t[0],O()),t)]},540:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createUnpackProgramInfoLoader=t.createUnpackProgramInfo=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614),a={name:"unpack",inputNames:["A"],inputTypes:[i.TextureType.packed]};t.createUnpackProgramInfo=(e,t)=>{const n=t.dims.length,u=(0,s.getChannels)("rc",n),l=u.slice(-2),c=(0,o.getCoordsDataType)(n),d=(0,s.unpackFromChannel)(),h=0===t.dims.length?"":function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(n,u),p=n<=1?"rc":`vec2(${l.join(",")})`,f=`\n ${d}\n void main() {\n ${c} rc = getOutputCoords();\n\n // Sample the texture with the coords to get the rgba channel value.\n vec4 packedInput = getA(${h});\n\n ${(0,r.getGlsl)(e.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${p}), 0, 0, 0);\n }\n `;return Object.assign(Object.assign({},a),{hasMain:!0,output:{dims:t.dims,type:t.type,textureType:i.TextureType.unpacked},shaderSource:f})},t.createUnpackProgramInfoLoader=(e,n)=>Object.assign(Object.assign({},a),{get:()=>(0,t.createUnpackProgramInfo)(e,n)})},7862:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseUnsqueezeAttributes=t.unsqueezeV13=t.unsqueeze=void 0;const r=n(7273);t.unsqueeze=(e,t,n)=>{i(t);const o=r.ShapeUtil.unsqueezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],o)]},t.unsqueezeV13=(e,n)=>(o(n),(0,t.unsqueeze)(e,[n[0]],Array.from(n[1].integerData))),t.parseUnsqueezeAttributes=e=>e.attributes.getInts("axes");const i=e=>{if(!e||1!==e.length)throw new Error("Unsqueeze requires 1 input.");if("string"===e[0].type)throw new Error("invalid input tensor types.")},o=e=>{if(!e||2!==e.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==e[1].type)throw new Error("Invalid input type.")}},3980:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scalesValidation=t.validateInputs=t.parseUpsampleAttributes=t.parseUpsampleAttributesV9=t.parseUpsampleAttributesV7=t.upsample=void 0;const r=n(4910),i=n(6757),o=n(5639),s={name:"Upsample",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};t.upsample=(e,n,r)=>((0,t.validateInputs)(n,r),[e.run(Object.assign(Object.assign({},s),{cacheHint:r.cacheKey,get:()=>a(e,n,r)}),n)]),t.parseUpsampleAttributesV7=e=>(0,t.parseUpsampleAttributes)(e,7),t.parseUpsampleAttributesV9=e=>(0,t.parseUpsampleAttributes)(e,9),t.parseUpsampleAttributes=(e,n)=>{const i=n>=10,o=e.attributes.getString("mode","nearest");if("nearest"!==o&&"linear"!==o&&(n<11||"cubic"!==o))throw new Error(`unrecognized mode: ${o}`);let s=[];n<9&&(s=e.attributes.getFloats("scales"),(0,t.scalesValidation)(s,o,i));const a=e.attributes.getFloat("extrapolation_value",0),u=n>10?e.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(u))throw new Error(`coordinate_transform_mode '${u}' is not supported`);const l="tf_crop_and_resize"===u,c=l,d="nearest"===o&&n>=11?e.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(d))throw new Error(`nearest_mode '${d}' is not supported`);const h=e.attributes.getFloat("cubic_coeff_a",-.75),p=0!==e.attributes.getInt("exclude_outside",0);if(p&&"cubic"!==o)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const f=n<11||"nearest"===o&&"asymmetric"===u&&"floor"===d;let g=0,m=0,b=0;return n>10?e.inputs.length>2?(g=1,m=2,b=3):(m=1,b=2):9===n&&(m=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:i,mode:o,scales:s,extrapolationValue:a,coordinateTransformMode:u,useExtrapolation:c,needRoiInput:l,nearestMode:d,cubicCoefficientA:h,excludeOutside:p,useNearest2xOptimization:f,roiInputIdx:g,scalesInputIdx:m,sizesInputIdx:b})};const a=(e,t,n)=>{const r=(0,i.getGlsl)(e.session.backend.glContext.version),[a,u]=e.calculateTextureWidthAndHeight(t[0].dims,o.TextureType.unpacked),l=t[0].dims.map(((e,t)=>Math.floor(e*n.scales[t]))),[c,d]=e.calculateTextureWidthAndHeight(l,o.TextureType.unpacked),h=l.length,p=new Array(h),f=new Array(h);let g=`\n int output_pitches[${h}];\n int input_pitches[${h}];\n `;for(let e=h-1;e>=0;e--)p[e]=e===h-1?1:p[e+1]*l[e+1],f[e]=e===h-1?1:f[e+1]*t[0].dims[e+1],g+=`\n output_pitches[${e}] = ${p[e]};\n input_pitches[${e}] = ${f[e]};\n `;const m=`\n float getInputFloat(int index) {\n vec2 coords = offsetToCoords(index, ${a}, ${u});\n float value = getColorAsFloat(${r.texture2D}(X, coords));\n return value;\n }\n `,b="nearest"===n.mode?`\n ${m}\n float process(int indices[${h}]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int d, m;\n for (int dim = 0; dim < ${h}; ++dim) {\n d = output_index / output_pitches[dim];\n m = output_index - d * output_pitches[dim];\n output_index = m;\n\n if (scales[dim] != 1 && d > 0) {\n int d2 = d / scales[dim];\n m = d - d2 * scales[dim];\n d = d2;\n }\n input_index += input_pitches[dim] * d;\n }\n\n return getInputFloat(input_index);\n }`:4===h?`\n ${m}\n float process(int indices[4]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m / output_pitches[1];\n m = m - index_of_dim1 * output_pitches[1];\n index_of_dim2 = m / output_pitches[2];\n m = m - index_of_dim2 * output_pitches[2];\n index_of_dim3 = m;\n\n int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n index_of_input_dim2 = index_of_dim2 / scales[2];\n y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n index_of_input_dim3 = index_of_dim3 / scales[3];\n x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n input_index = index_of_dim0 * input_pitches[0] +\n index_of_dim1 * input_pitches[1] +\n index_of_input_dim2 * input_pitches[2] +\n index_of_input_dim3;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim2 = false;\n if (index_of_input_dim2 == (${t[0].dims[2]} - 1)) {\n // It's the end in dimension 2\n x01 = x00;\n end_of_dim2 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[2]);\n }\n\n if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n // It's the end in dimension 3\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n }`:`\n ${m}\n float process(int indices[2]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m;\n\n int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n index_of_input_dim0 = index_of_dim0 / scales[0];\n y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n index_of_input_dim1 = index_of_dim1 / scales[1];\n x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim0 = false;\n if (index_of_input_dim0 == (${t[0].dims[0]} - 1)) {\n // It's the end in dimension 0\n x01 = x00;\n end_of_dim0 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[0]);\n }\n\n if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n // It's the end in dimension 1\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n }`;return Object.assign(Object.assign({},s),{output:{dims:l,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:b,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map((e=>Math.ceil(e)))}]})};t.validateInputs=(e,t)=>{if(!e||t.opset<9&&1!==e.length||t.opset>=9&&t.opset<11&&2!==e.length||t.opset>=11&&e.length<2)throw new Error("invalid inputs.");if(t.scales.length>0&&e[0].dims.length!==t.scales.length)throw new Error("Invalid input shape.");if("string"===e[0].type)throw new Error("Invalid input tensor types.")},t.scalesValidation=(e,t,n)=>{if(n){for(const t of e)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(const t of e)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==t&&"cubic"!==t||2===e.length||4===e.length&&1===e[0]&&1===e[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}},2757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgramManager=void 0;const r=n(8453),i=n(1315),o=n(8897),s=n(6757);t.ProgramManager=class{constructor(e,t,n){this.profiler=e,this.glContext=t,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=e.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,(()=>{var r;const o=this.glContext.gl,s=e.program;o.useProgram(s);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(e.attribLocations),this.bindUniforms(e.uniformLocations,null!==(r=e.programInfo.variables)&&void 0!==r?r:[],t)}catch(t){throw i.Logger.error("ProgramManager",e.programInfo.shaderSource),t}this.profiler.event("backend","GlContext.draw()",(()=>{this.glContext.draw()}))}),this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((e=>this.glContext.deleteProgram(e.program)))}build(e,t,n){return this.profiler.event("backend","ProgramManager.build",(()=>{const r=new o.GlslPreprocessor(this.glContext,e,t,n),i=r.preprocess(),s=this.compile(i);return{programInfo:e,program:s,uniformLocations:this.getUniformLocations(s,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(s)}}))}compile(e){if(!this.vertexShader){i.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const e=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(e,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&i.Logger.verbose("ProrgramManager",`FragShader:\n${e}\n`);const t=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,t);return this.glContext.deleteShader(t),n}bindOutput(e){const t=e.width,n=e.height;i.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${t}/${n}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,t,n)}bindAttributes(e){const t=e.position,n=e.textureCoord;this.glContext.setVertexAttributes(t,n),this.attributesBound=!0}bindUniforms(e,t,n){var r;const i=this.glContext.gl;let o=0;for(const{name:s,type:a,location:u,arrayLength:l}of e){const e=null===(r=t.find((e=>e.name===s)))||void 0===r?void 0:r.data;if("sampler2D"!==a&&!e)throw new Error(`variable '${s}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(n[o],u,o),o++;break;case"float":l?i.uniform1fv(u,e):i.uniform1f(u,e);break;case"int":l?i.uniform1iv(u,e):i.uniform1i(u,e);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(e,t,n){this.glContext.bindTextureToUniform(e.texture,n,t)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,t,n){const r=[];if(t)for(const n of t)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(e,n)});if(n)for(const t of n)r.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(e,t.name)}));return r}getUniformLocation(e,t){const n=this.glContext.gl.getUniformLocation(e,t);if(null===n)throw new Error(`Uniform ${t} not found.`);return n}getAttribLocation(e,t){return this.glContext.gl.getAttribLocation(e,t)}}},2171:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLSessionHandler=void 0;const r=n(1315),i=n(5881),o=n(7860),s=n(4110),a=n(2757),u=n(7618),l=n(5243);t.WebGLSessionHandler=class{constructor(e,t){this.backend=e,this.context=t,this.layoutStrategy=new u.PreferLogicalStrategy(e.glContext.maxTextureSize),this.programManager=new a.ProgramManager(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new l.TextureManager(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===e.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new o.WebGLInferenceHandler(this)}onGraphInitialized(e){const t=e.getValues().filter((e=>-1===e.from&&e.tensor)).map((e=>e.tensor.dataId));this.initializers=new Set(t)}isInitializer(e){return!!this.initializers&&this.initializers.has(e)}addInitializer(e){this.initializers.add(e)}getTextureData(e,t){return t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(e,t):this.unpackedTextureDataCache.set(e,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((e=>this.textureManager.releaseTexture(e,!0))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((e=>this.textureManager.releaseTexture(e,!0))),this.unpackedTextureDataCache=new Map}resolve(e,t,n){const r=(0,i.resolveOperator)(e,t,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(e,n):e}}}},9622:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Uint8DataEncoder=t.RGBAFloatDataEncoder=t.RedFloat32DataEncoder=void 0;const r=n(1315);t.RedFloat32DataEncoder=class{constructor(e,t=1){if(1===t)this.internalFormat=e.R32F,this.format=e.RED,this.textureType=e.FLOAT,this.channelSize=t;else{if(4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA32F,this.format=e.RGBA,this.textureType=e.FLOAT,this.channelSize=t}}encode(e,t){let n,i;return e.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(e)),t*this.channelSize>e.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),i=e,n=this.allocate(t*this.channelSize),i.forEach(((e,t)=>n[t]=e))):(i=e,n=i),n}allocate(e){return new Float32Array(4*e)}decode(e,t){return 1===this.channelSize?e.filter(((e,t)=>t%4==0)).subarray(0,t):e.subarray(0,t)}},t.RGBAFloatDataEncoder=class{constructor(e,t=1,n){if(1!==t&&4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.channelSize=t,this.textureType=n||e.FLOAT}encode(e,t){let n=e;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(t),e.forEach(((e,t)=>n[4*t]=e))),n}allocate(e){return new Float32Array(4*e)}decode(e,t){return 1===this.channelSize?e.filter(((e,t)=>t%4==0)).subarray(0,t):e.subarray(0,t)}},t.Uint8DataEncoder=class{constructor(e,t=1){if(this.channelSize=4,1===t)this.internalFormat=e.ALPHA,this.format=e.ALPHA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else{if(4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t}}encode(e,t){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}allocate(e){return new Uint8Array(e*this.channelSize)}decode(e,t){if(e instanceof Uint8Array)return e.subarray(0,t);throw new Error(`Invalid array type: ${e.constructor}`)}}},7618:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getBatchDim=t.sizeToSquarishShape=t.getRowsCols=t.sizeFromShape=t.isInt=t.parseAxisParam=t.squeezeShape=t.PreferLogicalStrategy=t.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(1315),i=n(7273);function o(e,t){const n=[],r=[],i=null!=t&&Array.isArray(t)&&0===t.length,o=null==t||i?null:s(t,e).sort();let a=0;for(let t=0;t<e.length;++t){if(null!=o){if(o[a]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==o[a]||o[a]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),o[a]<=t&&a++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function s(e,t){const n=t.length;return e=null==e?t.map(((e,t)=>t)):[].concat(e),(0,i.assert)(e.every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),(0,i.assert)(e.every(a),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function a(e){return e%1==0}function u(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function l(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}t.AlwaysKeepOriginalSizeStrategy=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){if(0===e.length)return[1,1];const n=this.maxTextureSize;if(t&&void 0!==t.breakAxis){const i=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce(((e,t)=>e*t)),o=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce(((e,t)=>e*t));if(!(i>n||o>n))return[i,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`)}const i=e.reduce(((e,t)=>e*t));let o=Math.floor(Math.sqrt(i));for(;o<n&&o<i&&i%o!=0;o++);if(o>=n||i%o!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${e}`);return[o,i/o]}},t.PreferLogicalStrategy=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){const n=this.computeTexture(e,t);return t&&t.isPacked&&(n[0]/=2,n[1]/=2),t&&t.reverseWH?[n[1],n[0]]:n}computeTexture(e,t){const n=t&&t.isPacked;if(0===e.length)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(t&&void 0!==t.breakAxis){const n=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce(((e,t)=>e*t)),o=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce(((e,t)=>e*t));if(!(n>i||o>i))return[n,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`)}let s=e.slice(0);if(n&&(i*=2,s=s.map(((e,t)=>t>=s.length-2?s[t]%2==0?s[t]:s[t]+1:s[t])),1===s.length&&(s=[2,s[0]])),2!==s.length){const e=o(s);s=e.newShape}const a=u(s);return s.length<=1&&a<=i?[1,a]:2===s.length&&s[0]<=i&&s[1]<=i?s:3===s.length&&s[0]*s[1]<=i&&s[2]<=i?[s[0]*s[1],s[2]]:3===s.length&&s[0]<=i&&s[1]*s[2]<=i?[s[0],s[1]*s[2]]:4===s.length&&s[0]*s[1]*s[2]<=i&&s[3]<=i?[s[0]*s[1]*s[2],s[3]]:4===s.length&&s[0]<=i&&s[1]*s[2]*s[3]<=i?[s[0],s[1]*s[2]*s[3]]:n?l(a/4).map((e=>2*e)):l(a)}},t.squeezeShape=o,t.parseAxisParam=s,t.isInt=a,t.sizeFromShape=u,t.getRowsCols=function(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]},t.sizeToSquarishShape=l,t.getBatchDim=function(e,t=2){return u(e.slice(0,e.length-t))}},3314:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createTextureLayoutFromShape=t.calculateTextureWidthAndHeight=t.createTextureLayoutFromTextureType=void 0;const r=n(7273),i=n(5639);t.createTextureLayoutFromTextureType=(e,n,r)=>{const o=r===i.TextureType.unpacked||r===i.TextureType.unpackedReversed?1:4,s=r===i.TextureType.packed,a=r===i.TextureType.unpackedReversed||r===i.TextureType.packed,u=r===i.TextureType.packedLastDimension?n.length-1:void 0,l=r===i.TextureType.packedLastDimension?n.map(((e,t)=>t===n.length-1?4*e:e)):void 0;return(0,t.createTextureLayoutFromShape)(e,n,o,l,{isPacked:s,reverseWH:a,breakAxis:u})},t.calculateTextureWidthAndHeight=(e,n,r)=>{const i=(0,t.createTextureLayoutFromTextureType)(e,n,r);return[i.width,i.height]},t.createTextureLayoutFromShape=(e,t,n=1,i,o)=>{const s=!(!o||!o.isPacked),[a,u]=e.computeTextureWH(s&&i||t,o),l=t.length;let c=t.slice(0);if(0===l&&(c=[1]),1===n)i=t;else if(s){if(4!==n)throw new Error("a packed texture must be 4-channel");i=t,l>0&&(c[l-1]=Math.ceil(c[l-1]/2)),l>1&&(c[l-2]=Math.ceil(c[l-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:a,height:u,channels:n,isPacked:s,shape:c,strides:r.ShapeUtil.computeStrides(c),unpackedShape:i,reversedWH:o&&o.reverseWH}}},5243:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TextureManager=void 0;const r=n(1315);t.TextureManager=class{constructor(e,t,n,r){this.glContext=e,this.layoutStrategy=t,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,t,n,i){const o=this.toEncoderType(e),s=this.glContext.getEncoder(o,t.channels||1,i);if(t.isPacked&&1===i)throw new Error("not implemented");const a=t.width,u=t.height;let l,c;if(this.config.reuseTextures){l=`${a}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`,c=this.inUseTextures.get(l),c||(c=[],this.inUseTextures.set(l,c));const t=this.idleTextures.get(l);if(t&&t.length>0){const r=t.pop();return c.push(r),1===i&&this.glContext.updateTexture(r,a,u,s,this.toTextureData(e,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${t.width}x${t.height}`);const d=this.glContext.allocateTexture(a,u,s,this.toTextureData(e,n));return this.config.reuseTextures&&(c.push(d),this.textureLookup.set(d,l)),d}readTexture(e,t,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",(()=>{const r=e.shape.reduce(((e,t)=>e*t))*n,i=this.glContext.readTexture(e.texture,e.width,e.height,r,this.toEncoderType(t),n);return this.toTensorData(t,i)}))}async readTextureAsync(e,t,n){const r=e.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const e=this.pendingRead.get(r);return new Promise((t=>null==e?void 0:e.push(t)))}return this.profiler.event("backend","TextureManager.readTextureAsync",(async()=>{this.pendingRead.set(r,[]);const i=e.shape.reduce(((e,t)=>e*t))*n;await this.glContext.createAndWaitForFence();const o=this.glContext.readTexture(e.texture,e.width,e.height,i,this.toEncoderType(t),n),s=this.toTensorData(t,o),a=this.pendingRead.get(r);return this.pendingRead.delete(r),null==a||a.forEach((e=>e(s))),s}))}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",(()=>{const t=e.shape.reduce(((e,t)=>e*t)),n=this.glContext.readTexture(e.texture,e.width,e.height,4*t,"byte",4);return new Float32Array(n.buffer,n.byteOffset,t)}))}releaseTexture(e,t){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(e.texture),n)){t&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const t=r.indexOf(e.texture);if(-1!==t){r.splice(t,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(e.texture)}}}n&&!t||(r.Logger.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,t){switch(e){case"int16":return t instanceof Int16Array?t:Int16Array.from(t);case"int32":return t instanceof Int32Array?t:Int32Array.from(t);case"int8":return t instanceof Int8Array?t:Int8Array.from(t);case"uint16":return t instanceof Uint16Array?t:Uint16Array.from(t);case"uint32":return t instanceof Uint32Array?t:Uint32Array.from(t);case"uint8":case"bool":return t instanceof Uint8Array?t:Uint8Array.from(t);case"float32":return t instanceof Float32Array?t:Float32Array.from(t);case"float64":return t instanceof Float64Array?t:Float64Array.from(t);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,t){if(t)return t instanceof Float32Array?t:new Float32Array(t)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},5639:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TextureType=void 0,(n=t.TextureType||(t.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},432:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getGlChannels=t.getCoordsDataType=t.getSqueezedParams=t.squeezeInputShape=t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=t.generateShaderFuncNameFromInputSamplerName=t.repeatedTry=t.getPackedShape=void 0;const r=n(7273);t.getPackedShape=function(e){const t=e.length;return e.slice(0,t-1).concat(e[t-1]/4)},t.repeatedTry=async function(e,t=(e=>0),n){return new Promise(((r,i)=>{let o=0;const s=()=>{if(e())return void r();o++;const a=t(o);null!=n&&o>=n?i():setTimeout(s,a)};s()}))},t.generateShaderFuncNameFromInputSamplerName=function(e){return(0,r.assert)(void 0!==e&&0!==e.length,(()=>"empty string found for sampler name")),"get"+e.charAt(0).toUpperCase()+e.slice(1)},t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(e){return(0,r.assert)(void 0!==e&&0!==e.length,(()=>"empty string found for sampler name")),"get"+e.charAt(0).toUpperCase()+e.slice(1)+"AtOutCoords"},t.squeezeInputShape=function(e,t){let n=JSON.parse(JSON.stringify(e));return n=t,n},t.getSqueezedParams=function(e,t){return t.map((t=>e[t])).join(", ")},t.getCoordsDataType=function(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)},t.getGlChannels=function(e=6){return["x","y","z","w","u","v"].slice(0,e)}},3389:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createNewWebGLContext=t.createWebGLContext=void 0;const r=n(1315),i=n(3524),o={};function s(e){const t=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const e=document.createElement("canvas");return e.width=1,e.height=1,e}();let n;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!e||"webgl2"===e)&&(n=t.getContext("webgl2",o),n))try{return new i.WebGLContext(n,2)}catch(e){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${e}`)}if((!e||"webgl"===e)&&(n=t.getContext("webgl",o)||t.getContext("experimental-webgl",o),n))try{return new i.WebGLContext(n,1)}catch(e){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${e}`)}throw new Error("WebGL is not supported")}t.createWebGLContext=function e(t){let n;t&&"webgl2"!==t||!("webgl2"in o)?t&&"webgl"!==t||!("webgl"in o)||(n=o.webgl):n=o.webgl2,n=n||s(t),t=t||1===n.version?"webgl":"webgl2";const r=n.gl;return o[t]=n,r.isContextLost()?(delete o[t],e(t)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},t.createNewWebGLContext=s},3524:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLContext=t.linearSearchLastTrue=void 0;const s=n(8453),a=o(n(9622)),u=n(432);function l(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}t.linearSearchLastTrue=l,t.WebGLContext=class{constructor(e,t){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=e,this.version=t,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,t,n,r){const i=this.gl,o=i.createTexture();i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE);const s=r?n.encode(r,e*t):null;return i.texImage2D(i.TEXTURE_2D,0,n.internalFormat,e,t,0,n.format,n.textureType,s),this.checkError(),o}updateTexture(e,t,n,r,i){const o=this.gl;o.bindTexture(o.TEXTURE_2D,e);const s=r.encode(i,t*n);o.texSubImage2D(o.TEXTURE_2D,0,0,0,t,n,r.format,r.textureType,s),this.checkError()}attachFramebuffer(e,t,n){const r=this.gl;r.bindTexture(r.TEXTURE_2D,e),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),this.checkError(),r.viewport(0,0,t,n),r.scissor(0,0,t,n)}readTexture(e,t,n,r,i,o){const s=this.gl;o||(o=1),this.frameBufferBound||this.attachFramebuffer(e,t,n);const a=this.getEncoder(i,o),u=a.allocate(t*n);return s.bindTexture(s.TEXTURE_2D,e),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e,0),s.readPixels(0,0,t,n,s.RGBA,a.textureType,u),this.checkError(),a.decode(u,r)}isFramebufferReady(){return!0}getActiveTexture(){const e=this.gl;return"TEXTURE"+(e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0)}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,t){const n=this.gl;n.vertexAttribPointer(e,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(e),-1!==t&&(n.vertexAttribPointer(t,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(t)),this.checkError()}createProgram(e,t){const n=this.gl,r=n.createProgram();return n.attachShader(r,e),n.attachShader(r,t),n.linkProgram(r),r}compileShader(e,t){const n=this.gl,r=n.createShader(t);if(!r)throw new Error(`createShader() returned null with type ${t}`);if(n.shaderSource(r,e),n.compileShader(r),!1===n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(r)}\nShader source:\n${e}`);return r}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,t,n){const r=this.gl;r.activeTexture(r.TEXTURE0+t),this.checkError(),r.bindTexture(r.TEXTURE_2D,e),this.checkError(),r.uniform1i(n,t),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(s.env.debug){const e=this.gl,t=e.getError();let n="";switch(t){case e.NO_ERROR:return;case e.INVALID_ENUM:n="INVALID_ENUM";break;case e.INVALID_VALUE:n="INVALID_VALUE";break;case e.INVALID_OPERATION:n="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${t.toString(16)}`}throw new Error(n)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,t,n=0){if(2===this.version)return new a.RedFloat32DataEncoder(this.gl,t);switch(e){case"float":return 1===n||this.isRenderFloat32Supported?new a.RGBAFloatDataEncoder(this.gl,t):new a.RGBAFloatDataEncoder(this.gl,t,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new a.Uint8DataEncoder(this.gl,t);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){const e=this.gl;for(let t=0;t<this.maxTextureImageUnits;++t)e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,null)}dispose(){if(this.disposed)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(this.framebuffer),e.bindBuffer(e.ARRAY_BUFFER,null),e.deleteBuffer(this.vertexbuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.finish(),this.disposed=!0}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){const e=this.gl,t=e.createBuffer();if(!t)throw new Error("createBuffer() returned null");const n=this.createDefaultGeometry();return e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW),this.checkError(),t}createFramebuffer(){const e=this.gl.createFramebuffer();if(!e)throw new Error("createFramebuffer returned null");return e}queryVitalParameters(){const e=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),1===this.version&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw new Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.version}getExtensions(){2===this.version?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){const e=this.gl,t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);const n=2===this.version?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,n,1,1,0,e.RGBA,e.FLOAT,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0);const i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(t),e.deleteFramebuffer(r),i}checkRenderFloat32(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension)return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else{if(!this.textureFloatExtension)return!1;if(!this.gl.getExtension("WEBGL_color_buffer_float"))return!1}return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){const e=this.gl;let t,n,r,i,o;try{t=e.createTexture(),n=e.createFramebuffer(),e.bindTexture(e.TEXTURE_2D,t);const s=2===this.version?e.RGBA32F:e.RGBA;return e.texImage2D(e.TEXTURE_2D,0,s,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.enable(e.BLEND),r=e.createShader(e.VERTEX_SHADER),!!r&&(e.shaderSource(r,"void main(){}"),e.compileShader(r),i=e.createShader(e.FRAGMENT_SHADER),!!i&&(e.shaderSource(i,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),e.compileShader(i),o=e.createProgram(),!!o&&(e.attachShader(o,r),e.attachShader(o,i),e.linkProgram(o),e.useProgram(o),e.drawArrays(e.POINTS,0,1),e.getError()===e.NO_ERROR)))}finally{e.disable(e.BLEND),o&&e.deleteProgram(o),r&&e.deleteShader(r),i&&e.deleteShader(i),n&&(e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(n)),t&&(e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(t))}}beginTimer(){if(2===this.version&&this.disjointTimerQueryWebgl2Extension){const e=this.gl,t=this.disjointTimerQueryWebgl2Extension,n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}throw new Error("WebGL1 profiling currently not supported.")}endTimer(){if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const e=this.gl,t=this.disjointTimerQueryWebgl2Extension;e.endQuery(t.TIME_ELAPSED_EXT)}}isTimerResultAvailable(e){let t=!1,n=!1;if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const r=this.gl,i=this.disjointTimerQueryWebgl2Extension;t=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE),n=r.getParameter(i.GPU_DISJOINT_EXT)}return t&&!n}getTimerResult(e){let t=0;if(2!==this.version)throw new Error("WebGL1 profiling currently not supported");{const n=this.gl;t=n.getQueryParameter(e,n.QUERY_RESULT),n.deleteQuery(e)}return t/1e6}async waitForQueryAndGetTime(e){return await(0,u.repeatedTry)((()=>this.isTimerResultAvailable(e))),this.getTimerResult(e)}async createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t;const n=e,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),t=null===r?()=>!0:()=>{const e=n.clientWaitSync(r,0,0);return e===n.ALREADY_SIGNALED||e===n.CONDITION_SATISFIED},{query:r,isFencePassed:t}}async pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=l(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||await(0,u.repeatedTry)((()=>(this.pollItems(),0===this.itemsToPoll.length)))}}},6496:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExecutionPlan=void 0;const r=n(1315);class i{constructor(e,t){this.op=e,this.node=t}}t.ExecutionPlan=class{constructor(e,t,n){this.graph=e,this.profiler=n,this.initialize(t)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",(()=>{const t=this.graph.getNodes();if(t.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map(((e,n)=>new i(e,t[n]))),this.reset(),this._starter=[],this._ops.forEach(((e,t)=>{let n=!0;for(const t of e.node.inputs)if(!this._values[t]&&-1===this.graph.getInputIndices().indexOf(t)){n=!1;break}n&&this._starter.push(t)}))}))}reset(){this._values=this.graph.getValues().map((e=>e.tensor))}async execute(e,t){return this.profiler.event("session","ExecutionPlan.execute",(async()=>{this.reset();const n=e.createInferenceHandler(),i=this.graph.getInputIndices();if(t.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${t.length} expected: ${i.length}`);t.forEach(((e,t)=>{const n=i[t];this._values[n]=e}));const o=this._starter.slice(0),s=this.graph.getValues(),a=this.graph.getNodes();let u=0;for(;u<o.length;){const e=o[u++],t=this._ops[e],i=t.node.inputs.map((e=>this._values[e]));if(-1!==i.indexOf(void 0))throw new Error(`unresolved input detected: op: ${t.node}`);const l=i;r.Logger.verbose("ExecPlan",`Runing op:${t.node.name} (${l.map(((e,n)=>`'${t.node.inputs[n]}': ${e.type}[${e.dims.join(",")}]`)).join(", ")})`);const c=await this.profiler.event("node",t.node.name,(async()=>t.op.impl(n,l,t.op.context)));if(c.length!==t.node.outputs.length)throw new Error("the size of output does not match model definition.");c.forEach(((e,n)=>{const r=t.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${t.node.name}`);this._values[r]=e}));const d=new Set;c.forEach(((e,n)=>{const r=t.node.outputs[n];for(const e of s[r].to){const t=a[e];let n=!0;for(const e of t.inputs)if(!this._values[e]){n=!1;break}n&&d.add(e)}})),o.push(...d)}const l=[];for(let e=0;e<this.graph.getOutputIndices().length;e++){const t=this.graph.getOutputIndices()[e],n=this._values[t];if(void 0===n)throw new Error(`required output [${t}] does not have value`);0===t?await n.getData():n.data,l.push(n)}return r.Logger.verbose("ExecPlan","disposing of inferenceHandler"),n.dispose(),l}))}}},4662:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Graph=void 0;const r=n(1446),i=n(6874),o=n(1287),s=n(9240),a=n(7273);var u=o.onnxruntime.experimental.fbs;t.Graph={from:(e,t)=>new d(e,t)};class l{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=a.ProtoUtil.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}}class c{constructor(e,t){e instanceof r.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new i.Attribute(e.attribute)):e instanceof u.Node&&(this.name=null!=t?t:e.name(),this.opType=e.opType(),this.attributes=new i.Attribute(a.ProtoUtil.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class d{constructor(e,t){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(t),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else{if(!(e instanceof u.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(e)}}buildGraphFromOnnxFormat(e){const t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!e.input)throw new Error("missing information in graph: input");const r=[];for(const n of e.input){if(t.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const e=this._allData.push(new l(n))-1;t.set(n.name,e),r.push(n.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(const n of e.initializer){let e=t.get(n.name);if(void 0===e){const r=new l;r.type={shape:{dims:a.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:a.ProtoUtil.tensorDataTypeFromProto(n.dataType)},e=this._allData.push(r)-1,t.set(n.name,e)}this._allData[e]._from=-1,this._allData[e].tensor=s.Tensor.fromProto(n)}for(let e=0;e<this._allData.length;e++)this._allData[e].tensor||(this._allInputIndices.push(e),this._allInputNames.push(r[e]));if(!e.output)throw new Error("missing information in graph: output");for(const n of e.output){if(t.has(n.name))throw new Error(`duplicated output name: ${n.name}`);const e=this._allData.push(new l(n))-1;t.set(n.name,e),this._allOutputIndices.push(e),this._allOutputNames.push(n.name)}if(!e.node)throw new Error("missing information in graph: node");for(const t of e.node){if(!t.name)for(let e=0;;e++){const r=`unnamed_${t.opType}_${e}`;if(!n.has(r)){t.name=r;break}}if(n.has(t.name))throw new Error(`duplicated node name: ${t.name}`);const e=this._nodes.push(new c(t))-1;n.set(t.name,e)}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=e.node[n];if(!i.output)throw new Error(`missing output for node: ${i.name}`);for(const e of i.output){let o=t.get(e);if(void 0===o&&(o=this._allData.push(new l)-1,t.set(e,o)),r.outputs.push(o),void 0!==this._allData[o]._from)throw new Error(`multiple nodes output to one data value: ${o}`);if(this._allData[o]._from=n,"Constant"===i.opType){if(!i.attribute||1!==i.attribute.length||!i.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!i.output||1!==i.output.length)throw new Error("missing output or incorrect number of outputs for this Constant operator");r.outputs.pop(),r.executeNode=!1,this._allData[o]._from=-1,this._allData[o].tensor=s.Tensor.fromProto(i.attribute[0].t)}}}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=e.node[n];if(!i.input)throw new Error(`missing input for node: ${i.name}`);for(const e of i.input){const o=t.get(e);if(void 0===o){if(""===e&&3===i.input.length&&"Resize"===i.opType)continue;throw new Error(`unrecognized input '${e}' for node: ${i.name}`)}r.inputs.push(o),this._allData[o]._to.push(n)}}return!0}buildGraphFromOrtFormat(e){var t,n,r;const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const o=new Map,d=[];for(let o=0;o<e.inputsLength();o++){const s=e.inputs(o);if(i.has(s))throw new Error(`duplicated input name: ${s}`);for(let o=0;o<e.nodeArgsLength();o++)if((null===(t=e.nodeArgs(o))||void 0===t?void 0:t.name())===s){const t=new l;if((null===(r=null===(n=e.nodeArgs(o))||void 0===n?void 0:n.type())||void 0===r?void 0:r.valueType())!==u.TypeInfoValue.tensor_type)throw new Error("Unexpected value type for the nodeArg.");const c=e.nodeArgs(o).type().value(new u.TensorTypeAndShape),h=a.ProtoUtil.tensorDataTypeFromProto(c.elemType()),p=c.shape(),f=[];for(let e=0;e<p.dimLength();e++)f.push(a.LongUtil.longToNumber(p.dim(e).value().dimValue()));t.type={shape:{dims:f},tensorType:h};const g=this._allData.push(t)-1;i.set(s,g),d.push(s)}}for(let t=0;t<e.initializersLength();t++){const n=e.initializers(t);let r=i.get(n.name());if(void 0===r){const e=new l,t=a.ProtoUtil.tensorDimsFromORTFormat(n),o=a.ProtoUtil.tensorDataTypeFromProto(n.dataType());e.type={shape:{dims:t},tensorType:o},r=this._allData.push(e)-1,i.set(n.name(),r)}this._allData[r]._from=-1,this._allData[r].tensor=s.Tensor.fromOrtTensor(n)}for(let e=0;e<this._allData.length;e++)this._allData[e].tensor||(this._allInputIndices.push(e),this._allInputNames.push(d[e]));for(let t=0;t<e.outputsLength();t++){const n=e.outputs(t);if(i.has(n))throw new Error(`duplicated output name: ${n}`);const r=this._allData.push(new l)-1;i.set(n,r),this._allOutputIndices.push(r),this._allOutputNames.push(n)}if(!e.nodes)throw new Error("missing information in graph: node");for(let t=0;t<e.nodesLength();t++){const n=e.nodes(t);let r=n.name();if(!r)for(let e=0;r=`unnamed_${n.opType()}_${e}`,o.has(r);e++);if(o.has(r))throw new Error(`duplicated node name: ${r}`);const i=this._nodes.push(new c(n,r))-1;o.set(r,i)}for(let t=0;t<this._nodes.length;t++){const n=this._nodes[t],r=e.nodes(t);if(null==r)throw new Error(`No node exists at index ${t}`);if(0===(null==r?void 0:r.outputsLength()))throw new Error(`missing output for node: ${r.name}`);for(let e=0;e<(null==r?void 0:r.outputsLength());e++){const o=null==r?void 0:r.outputs(e);let a=i.get(o);if(void 0===a&&(a=this._allData.push(new l)-1,i.set(o,a)),n.outputs.push(a),void 0!==this._allData[a]._from)throw new Error(`multiple nodes output to one data value: ${a}`);if(this._allData[a]._from=t,"Constant"===r.opType()){if(1!==r.attributesLength()||!r.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(1!==r.outputsLength())throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=!1,this._allData[a]._from=-1,this._allData[a].tensor=s.Tensor.fromOrtTensor(r.attributes(0).t())}}}for(let t=0;t<this._nodes.length;t++){const n=this._nodes[t],r=e.nodes(t);if(0===r.inputsLength())throw new Error(`missing input for node: ${r.name}`);for(let e=0;e<r.inputsLength();e++){const o=r.inputs(e),s=i.get(o);if(void 0===s)throw new Error(`unrecognized input '${o}' for node: ${r.name()}`);n.inputs.push(s),this._allData[s]._to.push(t)}}}checkIsAcyclic(){const e=new Set;this._allInputIndices.forEach((t=>{this._allData[t]._to.forEach((t=>{e.add(t)}))}));const t=Array.from(e),n=new Array(this._nodes.length).fill("white");for(;t.length>0;){const e=t.pop();"gray"===n[e]?n[e]="black":(t.push(e),n[e]="gray",this._nodes[e].outputs.forEach((r=>{const i=this._allData[r];if(void 0!==i.tensor)throw new Error("node outputs should not be initialized");if(i._from!==e)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach((e=>{if("gray"===n[e])throw new Error("model graph is cyclic");"white"===n[e]&&t.push(e)}))})))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0;const t=new Array(this._nodes.length,0);let n=0;for(let e=0;e<this._nodes.length;e++)t[e]=n,this._nodes[e].executeNode?(n!==e&&(this._nodes[n]=this._nodes[e]),n++):this._nodes[e].outputs.forEach((e=>{this._allData[e]._from=-2}));this._nodes.splice(n,this._nodes.length-n);for(let e=0;e<this._allData.length;e++){const n=this._allData[e];void 0!==n._from&&-1!==n._from&&-2!==n._from&&(n._from=t[n._from]);for(let e=0;e<n._to.length;e++){if(!(n._to[e]>=0))throw new Error("Trying to update a removed node");n._to[e]=t[n._to[e]]}}e=0;for(let t=0;t<this._allData.length;t++)if(-2!==this._allData[t].from||-1!==this._allOutputIndices.indexOf(t+e)){if(e>0){let n=-1;void 0!==this._allData[t].from&&-1!==this._allData[t].from?(n=this._nodes[this._allData[t].from].outputs.indexOf(t+e),-1!==n&&(this._nodes[this._allData[t].from].outputs[n]=t)):(n=this._allInputIndices.indexOf(t+e),-1!==n&&(this._allInputIndices[n]=t)),this._allData[t].to.forEach((r=>{n=this._nodes[r].inputs.indexOf(t+e),-1!==n&&(this._nodes[r].inputs[n]=t)})),0===this._allData[t].to.length&&(n=this._allOutputIndices.indexOf(t+e),-1!==n&&(this._allOutputIndices[n]=t))}}else e++,this._allData.splice(t,1),t--}deleteNode(e){const t=this._nodes[e];if(t.outputs.length>1)for(let e=1;e<t.outputs.length;e++)if(this._allData[t.outputs[e]].to.length>0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");t.executeNode=!1;const n=t.inputs[0],r=t.outputs[0],i=this._allData[r].to;for(let n=0;n<t.inputs.length;n++){const r=this._allData[t.inputs[n]].to.indexOf(e);if(-1===r)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[t.inputs[n]].to.splice(r,1)}this._allData[r]._to=[];const o=this._allOutputIndices.indexOf(r);if(-1!==o&&(this._allOutputIndices[o]=n),i&&i.length>0)for(const e of i){const t=this._nodes[e].inputs.indexOf(r);if(-1===t)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[e].inputs[t]=n,this._allData[n].to.push(e)}}removeAllDropoutNodes(){let e=0;for(const t of this._nodes){if("Dropout"===t.opType){if(1!==t.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==t.outputs.length&&2!==t.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===t.outputs.length&&0!==this._allData[t.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(const t of this._nodes)"Identity"===t.opType&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const e of this._nodes)if("Conv"===e.opType){const t=this._allData[e.outputs[0]]._to;if(1===t.length&&this.isActivation(this._nodes[t[0]])){const n=this._nodes[t[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{e.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(t){e.attributes.set("activation_params","floats",[a.MIN_CLIP,a.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;e.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}e.attributes.set("activation","string",n.opType),this.deleteNode(t[0])}}}}},1315:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.now=t.Profiler=t.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(e,t,n){}},console:new class{log(e,t,n){console.log(`${this.color(e)} ${n?""+n+" ":""}${t}`)}color(e){switch(e){case"verbose":return"v";case"info":return"i";case"warning":return"w";case"error":return"e";case"fatal":return"f";default:throw new Error(`unsupported severity: ${e}`)}}}},i={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let o={"":i};function s(e,t,n,r){if(void 0===t)return i=e,{verbose:s.verbose.bind(null,i),info:s.info.bind(null,i),warning:s.warning.bind(null,i),error:s.error.bind(null,i),fatal:s.fatal.bind(null,i)};if(void 0===n)a(e,t);else if("number"==typeof n&&void 0===r)a(e,t);else if("string"==typeof n&&void 0===r)a(e,n,0,t);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");a(e,n,0,t)}var i}function a(e,t,i,s){const a=o[s||""]||o[""];n[e]<n[a.minimalSeverity]||(a.logDateTime&&(t=`${(new Date).toISOString()}|${t}`),a.logSourceLocation,r[a.provider].log(e,t,s))}!function(e){function t(e){o={},n("",e||{})}function n(e,n){if("*"===e)t(n);else{const t=o[e]||i;o[e]={provider:n.provider||t.provider,minimalSeverity:n.minimalSeverity||t.minimalSeverity,logDateTime:void 0===n.logDateTime?t.logDateTime:n.logDateTime,logSourceLocation:void 0===n.logSourceLocation?t.logSourceLocation:n.logSourceLocation}}}e.verbose=function(t,n){e("verbose",t,n)},e.info=function(t,n){e("info",t,n)},e.warning=function(t,n){e("warning",t,n)},e.error=function(t,n){e("error",t,n)},e.fatal=function(t,n){e("fatal",t,n)},e.reset=t,e.set=n,e.setWithEnv=function(e){const t={};e.logLevel&&(t.minimalSeverity=e.logLevel),n("",t)}}(s||(s={})),t.Logger=s;class u{constructor(e,t,n,r,i,o){this.category=e,this.name=t,this.startTime=n,this.endCallback=r,this.timer=i,this.ctx=o}async end(){return this.endCallback(this)}async checkTimer(){if(void 0===this.ctx||void 0===this.timer)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}}class l{constructor(e,t,n,r){this.category=e,this.name=t,this.startTime=n,this.endTime=r}}t.Profiler=class{static create(e){return void 0===e?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}constructor(e,t,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=void 0===e?1e4:e,this._flushBatchSize=void 0===t?10:t,this._flushIntervalInMilliseconds=void 0===n?5e3:n}start(){this._started=!0,this._timingEvents=[],this._flushTime=(0,t.now)(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer])}event(e,t,n,r){const i=this._started?this.begin(e,t,r):void 0;let o=!1;const s=n();if(s&&"function"==typeof s.then)return o=!0,new Promise(((e,t)=>{s.then((async t=>{i&&await i.end(),e(t)}),(async e=>{i&&await i.end(),t(e)}))}));if(!o&&i){const e=i.end();if(e&&"function"==typeof e.then)return new Promise(((t,n)=>{e.then((()=>{t(s)}),(e=>{n(e)}))}))}return s}begin(e,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,t.now)();return this.flush(r),new u(e,n,r,(e=>this.endSync(e)))}{const t=r.beginTimer();return new u(e,n,0,(async e=>this.end(e)),t,r)}}async end(e){const t=await e.checkTimer();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new l(e.category,e.name,e.startTime,t)),this.flush(t))}endSync(e){const n=(0,t.now)();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new l(e.category,e.name,e.startTime,n)),this.flush(n))}logOneEvent(e){t.Logger.verbose(`Profiler.${e.category}`,`${(e.endTime-e.startTime).toFixed(2)}ms on event '${e.name}' at ${e.endTime.toFixed(2)}`)}flush(e){if(this._timingEvents.length-this._flushPointer>=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(const e=this._flushPointer;this._flushPointer<e+this._flushBatchSize&&this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer]);this._flushTime=(0,t.now)()}}get started(){return this._started}},t.now="undefined"!=typeof performance&&performance.now?()=>performance.now():Date.now},1745:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const r=n(5686),i=n(1446),o=n(4662),s=n(1287),a=n(7273);var u=s.onnxruntime.experimental.fbs;t.Model=class{constructor(){}load(e,t,n){if(!n)try{return void this.loadFromOnnxFormat(e,t)}catch(e){if(void 0!==n)throw e}this.loadFromOrtFormat(e,t)}loadFromOnnxFormat(e,t){const n=i.onnx.ModelProto.decode(e);if(a.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map((e=>({domain:e.domain,version:a.LongUtil.longToNumber(e.version)}))),this._graph=o.Graph.from(n.graph,t)}loadFromOrtFormat(e,t){const n=new r.flatbuffers.ByteBuffer(e),i=u.InferenceSession.getRootAsInferenceSession(n).model();if(a.LongUtil.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let e=0;e<i.opsetImportLength();e++){const t=i.opsetImport(e);this._opsets.push({domain:null==t?void 0:t.domain(),version:a.LongUtil.longToNumber(t.version())})}this._graph=o.Graph.from(i.graph(),t)}get graph(){return this._graph}get opsets(){return this._opsets}}},6145:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FLOAT_TYPES=t.INT_TYPES=t.NUMBER_TYPES=void 0,t.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],t.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],t.FLOAT_TYPES=["float32","float64"]},5881:(e,t)=>{"use strict";function n(e,t){if(t.endsWith("+")){const n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}if(2===t.split("-").length){const n=t.split("-"),r=Number.parseInt(n[0],10),i=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(i)&&r<=e&&e<=i}return Number.parseInt(t,10)===e}Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOperator=void 0,t.resolveOperator=function(e,t,r){for(const i of r){const r=i[0],o=i[1],s=i[2],a=i[3],u=i[4];if(e.opType===r)for(const e of t)if((e.domain===o||"ai.onnx"===e.domain&&""===o)&&n(e.version,s))return{opImpl:a,opInit:u}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map((e=>`${e.domain||"ai.onnx"} v${e.version}`)).join(", ")}`)}},1287:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onnxruntime=void 0;const r=n(5686);var i,o;(function(e){let t;!function(e){e[e.UNDEFINED=0]="UNDEFINED",e[e.FLOAT=1]="FLOAT",e[e.INT=2]="INT",e[e.STRING=3]="STRING",e[e.TENSOR=4]="TENSOR",e[e.GRAPH=5]="GRAPH",e[e.FLOATS=6]="FLOATS",e[e.INTS=7]="INTS",e[e.STRINGS=8]="STRINGS",e[e.TENSORS=9]="TENSORS",e[e.GRAPHS=10]="GRAPHS",e[e.SPARSE_TENSOR=11]="SPARSE_TENSOR",e[e.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(t=e.AttributeType||(e.AttributeType={}))})((o=(i=t.onnxruntime||(t.onnxruntime={})).experimental||(i.experimental={})).fbs||(o.fbs={})),function(e){!function(e){!function(e){let t;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VALUE=1]="VALUE",e[e.PARAM=2]="PARAM"}(t=e.DimensionValueType||(e.DimensionValueType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){let t;!function(e){e[e.UNDEFINED=0]="UNDEFINED",e[e.FLOAT=1]="FLOAT",e[e.UINT8=2]="UINT8",e[e.INT8=3]="INT8",e[e.UINT16=4]="UINT16",e[e.INT16=5]="INT16",e[e.INT32=6]="INT32",e[e.INT64=7]="INT64",e[e.STRING=8]="STRING",e[e.BOOL=9]="BOOL",e[e.FLOAT16=10]="FLOAT16",e[e.DOUBLE=11]="DOUBLE",e[e.UINT32=12]="UINT32",e[e.UINT64=13]="UINT64",e[e.COMPLEX64=14]="COMPLEX64",e[e.COMPLEX128=15]="COMPLEX128",e[e.BFLOAT16=16]="BFLOAT16"}(t=e.TensorDataType||(e.TensorDataType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){let t;!function(e){e[e.Primitive=0]="Primitive",e[e.Fused=1]="Fused"}(t=e.NodeType||(e.NodeType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){let t;!function(e){e[e.NONE=0]="NONE",e[e.tensor_type=1]="tensor_type",e[e.sequence_type=2]="sequence_type",e[e.map_type=3]="map_type"}(t=e.TypeInfoValue||(e.TypeInfoValue={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsShape(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsShape(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}dim(t,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new e.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}dimLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}static startShape(e){e.startObject(1)}static addDim(e,t){e.addFieldOffset(0,t,0)}static createDimVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startDimVector(e,t){e.startVector(4,t,4)}static endShape(e){return e.endObject()}static createShape(e,t){return n.startShape(e),n.addDim(e,t),n.endShape(e)}}t.Shape=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDimension(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsDimension(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}value(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}denotation(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startDimension(e){e.startObject(2)}static addValue(e,t){e.addFieldOffset(0,t,0)}static addDenotation(e,t){e.addFieldOffset(1,t,0)}static endDimension(e){return e.endObject()}static createDimension(e,t,r){return n.startDimension(e),n.addValue(e,t),n.addDenotation(e,r),n.endDimension(e)}}t.Dimension=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDimensionValue(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsDimensionValue(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):e.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}dimParam(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}static startDimensionValue(e){e.startObject(3)}static addDimType(t,n){t.addFieldInt8(0,n,e.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addDimParam(e,t){e.addFieldOffset(2,t,0)}static endDimensionValue(e){return e.endObject()}static createDimensionValue(e,t,r,i){return n.startDimensionValue(e),n.addDimType(e,t),n.addDimValue(e,r),n.addDimParam(e,i),n.endDimensionValue(e)}}t.DimensionValue=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTensorTypeAndShape(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTensorTypeAndShape(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(e){e.startObject(2)}static addElemType(t,n){t.addFieldInt32(0,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(e,t){e.addFieldOffset(1,t,0)}static endTensorTypeAndShape(e){return e.endObject()}static createTensorTypeAndShape(e,t,r){return n.startTensorTypeAndShape(e),n.addElemType(e,t),n.addShape(e,r),n.endTensorTypeAndShape(e)}}t.TensorTypeAndShape=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMapType(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMapType(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(e){e.startObject(2)}static addKeyType(t,n){t.addFieldInt32(0,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(e,t){e.addFieldOffset(1,t,0)}static endMapType(e){return e.endObject()}static createMapType(e,t,r){return n.startMapType(e),n.addKeyType(e,t),n.addValueType(e,r),n.endMapType(e)}}t.MapType=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSequenceType(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSequenceType(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}elemType(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSequenceType(e){e.startObject(1)}static addElemType(e,t){e.addFieldOffset(0,t,0)}static endSequenceType(e){return e.endObject()}static createSequenceType(e,t){return n.startSequenceType(e),n.addElemType(e,t),n.endSequenceType(e)}}t.SequenceType=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){(e.fbs||(e.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(e,t,n,r){return e.prep(4,12),e.writeInt32(r),e.writeInt32(n),e.writeInt32(t),e.offset()}}}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNodeEdge(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsNodeEdge(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}nodeIndex(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb_pos+e):0}inputEdges(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}inputEdgesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}outputEdges(t,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}outputEdgesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}static startNodeEdge(e){e.startObject(3)}static addNodeIndex(e,t){e.addFieldInt32(0,t,0)}static addInputEdges(e,t){e.addFieldOffset(1,t,0)}static startInputEdgesVector(e,t){e.startVector(12,t,4)}static addOutputEdges(e,t){e.addFieldOffset(2,t,0)}static startOutputEdgesVector(e,t){e.startVector(12,t,4)}static endNodeEdge(e){return e.endObject()}static createNodeEdge(e,t,r,i){return n.startNodeEdge(e),n.addNodeIndex(e,t),n.addInputEdges(e,r),n.addOutputEdges(e,i),n.endNodeEdge(e)}}t.NodeEdge=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNode(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsNode(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}domain(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}sinceVersion(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):0}index(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint32(this.bb_pos+e):0}opType(e){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__string(this.bb_pos+t,e):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.NodeType.Primitive}executionProviderType(e){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__string(this.bb_pos+t,e):null}inputs(e,t){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}inputsLength(){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__vector_len(this.bb_pos+e):0}outputs(e,t){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}outputsLength(){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.__vector_len(this.bb_pos+e):0}attributes(t,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new e.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}attributesLength(){let e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__vector_len(this.bb_pos+e):0}inputArgCounts(e){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.readInt32(this.bb.__vector(this.bb_pos+t)+4*e):0}inputArgCountsLength(){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__vector_len(this.bb_pos+e):0}inputArgCountsArray(){let e=this.bb.__offset(this.bb_pos,26);return e?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}implicitInputs(e,t){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}implicitInputsLength(){let e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__vector_len(this.bb_pos+e):0}static startNode(e){e.startObject(13)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addDomain(e,t){e.addFieldOffset(2,t,0)}static addSinceVersion(e,t){e.addFieldInt32(3,t,0)}static addIndex(e,t){e.addFieldInt32(4,t,0)}static addOpType(e,t){e.addFieldOffset(5,t,0)}static addType(t,n){t.addFieldInt32(6,n,e.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(e,t){e.addFieldOffset(7,t,0)}static addInputs(e,t){e.addFieldOffset(8,t,0)}static createInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInputsVector(e,t){e.startVector(4,t,4)}static addOutputs(e,t){e.addFieldOffset(9,t,0)}static createOutputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOutputsVector(e,t){e.startVector(4,t,4)}static addAttributes(e,t){e.addFieldOffset(10,t,0)}static createAttributesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startAttributesVector(e,t){e.startVector(4,t,4)}static addInputArgCounts(e,t){e.addFieldOffset(11,t,0)}static createInputArgCountsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startInputArgCountsVector(e,t){e.startVector(4,t,4)}static addImplicitInputs(e,t){e.addFieldOffset(12,t,0)}static createImplicitInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startImplicitInputsVector(e,t){e.startVector(4,t,4)}static endNode(e){return e.endObject()}static createNode(e,t,r,i,o,s,a,u,l,c,d,h,p,f){return n.startNode(e),n.addName(e,t),n.addDocString(e,r),n.addDomain(e,i),n.addSinceVersion(e,o),n.addIndex(e,s),n.addOpType(e,a),n.addType(e,u),n.addExecutionProviderType(e,l),n.addInputs(e,c),n.addOutputs(e,d),n.addAttributes(e,h),n.addInputArgCounts(e,p),n.addImplicitInputs(e,f),n.endNode(e)}}t.Node=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsValueInfo(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsValueInfo(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}type(t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startValueInfo(e){e.startObject(3)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addType(e,t){e.addFieldOffset(2,t,0)}static endValueInfo(e){return e.endObject()}static createValueInfo(e,t,r,i){return n.startValueInfo(e),n.addName(e,t),n.addDocString(e,r),n.addType(e,i),n.endValueInfo(e)}}t.ValueInfo=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTypeInfo(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTypeInfo(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}denotation(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):e.experimental.fbs.TypeInfoValue.NONE}value(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}static startTypeInfo(e){e.startObject(3)}static addDenotation(e,t){e.addFieldOffset(0,t,0)}static addValueType(t,n){t.addFieldInt8(1,n,e.experimental.fbs.TypeInfoValue.NONE)}static addValue(e,t){e.addFieldOffset(2,t,0)}static endTypeInfo(e){return e.endObject()}static createTypeInfo(e,t,r,i){return n.startTypeInfo(e),n.addDenotation(e,t),n.addValueType(e,r),n.addValue(e,i),n.endTypeInfo(e)}}t.TypeInfo=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){class t{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsOperatorSetId(e,n){return(n||new t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsOperatorSetId(e,n){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new t).__init(e.readInt32(e.position())+e.position(),e)}domain(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}version(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}static startOperatorSetId(e){e.startObject(2)}static addDomain(e,t){e.addFieldOffset(0,t,0)}static addVersion(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static endOperatorSetId(e){return e.endObject()}static createOperatorSetId(e,n,r){return t.startOperatorSetId(e),t.addDomain(e,n),t.addVersion(e,r),t.endOperatorSetId(e)}}e.OperatorSetId=t}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTensor(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTensor(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dims(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}dimsLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}rawData(e){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint8(this.bb.__vector(this.bb_pos+t)+e):0}rawDataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}rawDataArray(){let e=this.bb.__offset(this.bb_pos,12);return e?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}stringData(e,t){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}stringDataLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}static startTensor(e){e.startObject(6)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addDims(e,t){e.addFieldOffset(2,t,0)}static createDimsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startDimsVector(e,t){e.startVector(8,t,8)}static addDataType(t,n){t.addFieldInt32(3,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(e,t){e.addFieldOffset(4,t,0)}static createRawDataVector(e,t){e.startVector(1,t.length,1);for(let n=t.length-1;n>=0;n--)e.addInt8(t[n]);return e.endVector()}static startRawDataVector(e,t){e.startVector(1,t,1)}static addStringData(e,t){e.addFieldOffset(5,t,0)}static createStringDataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startStringDataVector(e,t){e.startVector(4,t,4)}static endTensor(e){return e.endObject()}static createTensor(e,t,r,i,o,s,a){return n.startTensor(e),n.addName(e,t),n.addDocString(e,r),n.addDims(e,i),n.addDataType(e,o),n.addRawData(e,s),n.addStringData(e,a),n.endTensor(e)}}t.Tensor=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSparseTensor(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSparseTensor(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}values(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}dims(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}dimsLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSparseTensor(e){e.startObject(3)}static addValues(e,t){e.addFieldOffset(0,t,0)}static addIndices(e,t){e.addFieldOffset(1,t,0)}static addDims(e,t){e.addFieldOffset(2,t,0)}static createDimsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startDimsVector(e,t){e.startVector(8,t,8)}static endSparseTensor(e){return e.endObject()}static createSparseTensor(e,t,r,i){return n.startSparseTensor(e),n.addValues(e,t),n.addIndices(e,r),n.addDims(e,i),n.endSparseTensor(e)}}t.SparseTensor=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsAttribute(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsAttribute(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.AttributeType.UNDEFINED}f(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readFloat32(this.bb_pos+e):0}i(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}s(e){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__string(this.bb_pos+t,e):null}t(t){let n=this.bb.__offset(this.bb_pos,16);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(t){let n=this.bb.__offset(this.bb_pos,18);return n?(t||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}floats(e){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.readFloat32(this.bb.__vector(this.bb_pos+t)+4*e):0}floatsLength(){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__vector_len(this.bb_pos+e):0}floatsArray(){let e=this.bb.__offset(this.bb_pos,20);return e?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}ints(e){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}intsLength(){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.__vector_len(this.bb_pos+e):0}strings(e,t){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}stringsLength(){let e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__vector_len(this.bb_pos+e):0}tensors(t,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}tensorsLength(){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__vector_len(this.bb_pos+e):0}graphs(t,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}graphsLength(){let e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__vector_len(this.bb_pos+e):0}static startAttribute(e){e.startObject(13)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addType(t,n){t.addFieldInt32(2,n,e.experimental.fbs.AttributeType.UNDEFINED)}static addF(e,t){e.addFieldFloat32(3,t,0)}static addI(e,t){e.addFieldInt64(4,t,e.createLong(0,0))}static addS(e,t){e.addFieldOffset(5,t,0)}static addT(e,t){e.addFieldOffset(6,t,0)}static addG(e,t){e.addFieldOffset(7,t,0)}static addFloats(e,t){e.addFieldOffset(8,t,0)}static createFloatsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addFloat32(t[n]);return e.endVector()}static startFloatsVector(e,t){e.startVector(4,t,4)}static addInts(e,t){e.addFieldOffset(9,t,0)}static createIntsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startIntsVector(e,t){e.startVector(8,t,8)}static addStrings(e,t){e.addFieldOffset(10,t,0)}static createStringsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startStringsVector(e,t){e.startVector(4,t,4)}static addTensors(e,t){e.addFieldOffset(11,t,0)}static createTensorsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startTensorsVector(e,t){e.startVector(4,t,4)}static addGraphs(e,t){e.addFieldOffset(12,t,0)}static createGraphsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startGraphsVector(e,t){e.startVector(4,t,4)}static endAttribute(e){return e.endObject()}static createAttribute(e,t,r,i,o,s,a,u,l,c,d,h,p,f){return n.startAttribute(e),n.addName(e,t),n.addDocString(e,r),n.addType(e,i),n.addF(e,o),n.addI(e,s),n.addS(e,a),n.addT(e,u),n.addG(e,l),n.addFloats(e,c),n.addInts(e,d),n.addStrings(e,h),n.addTensors(e,p),n.addGraphs(e,f),n.endAttribute(e)}}t.Attribute=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsGraph(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsGraph(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}initializers(t,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}initializersLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}nodeArgs(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeArgsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}nodes(t,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new e.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}maxNodeIndex(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readUint32(this.bb_pos+e):0}nodeEdges(t,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new e.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeEdgesLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}inputs(e,t){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}inputsLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}outputs(e,t){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}outputsLength(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}sparseInitializers(t,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new e.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}sparseInitializersLength(){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__vector_len(this.bb_pos+e):0}static startGraph(e){e.startObject(8)}static addInitializers(e,t){e.addFieldOffset(0,t,0)}static createInitializersVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInitializersVector(e,t){e.startVector(4,t,4)}static addNodeArgs(e,t){e.addFieldOffset(1,t,0)}static createNodeArgsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodeArgsVector(e,t){e.startVector(4,t,4)}static addNodes(e,t){e.addFieldOffset(2,t,0)}static createNodesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodesVector(e,t){e.startVector(4,t,4)}static addMaxNodeIndex(e,t){e.addFieldInt32(3,t,0)}static addNodeEdges(e,t){e.addFieldOffset(4,t,0)}static createNodeEdgesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodeEdgesVector(e,t){e.startVector(4,t,4)}static addInputs(e,t){e.addFieldOffset(5,t,0)}static createInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInputsVector(e,t){e.startVector(4,t,4)}static addOutputs(e,t){e.addFieldOffset(6,t,0)}static createOutputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOutputsVector(e,t){e.startVector(4,t,4)}static addSparseInitializers(e,t){e.addFieldOffset(7,t,0)}static createSparseInitializersVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startSparseInitializersVector(e,t){e.startVector(4,t,4)}static endGraph(e){return e.endObject()}static createGraph(e,t,r,i,o,s,a,u,l){return n.startGraph(e),n.addInitializers(e,t),n.addNodeArgs(e,r),n.addNodes(e,i),n.addMaxNodeIndex(e,o),n.addNodeEdges(e,s),n.addInputs(e,a),n.addOutputs(e,u),n.addSparseInitializers(e,l),n.endGraph(e)}}t.Graph=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsModel(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsModel(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}irVersion(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}opsetImport(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}opsetImportLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}producerName(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}producerVersion(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__string(this.bb_pos+t,e):null}domain(e){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__string(this.bb_pos+t,e):null}modelVersion(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}docString(e){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__string(this.bb_pos+t,e):null}graph(t){let n=this.bb.__offset(this.bb_pos,18);return n?(t||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}graphDocString(e){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__string(this.bb_pos+t,e):null}static startModel(e){e.startObject(9)}static addIrVersion(e,t){e.addFieldInt64(0,t,e.createLong(0,0))}static addOpsetImport(e,t){e.addFieldOffset(1,t,0)}static createOpsetImportVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOpsetImportVector(e,t){e.startVector(4,t,4)}static addProducerName(e,t){e.addFieldOffset(2,t,0)}static addProducerVersion(e,t){e.addFieldOffset(3,t,0)}static addDomain(e,t){e.addFieldOffset(4,t,0)}static addModelVersion(e,t){e.addFieldInt64(5,t,e.createLong(0,0))}static addDocString(e,t){e.addFieldOffset(6,t,0)}static addGraph(e,t){e.addFieldOffset(7,t,0)}static addGraphDocString(e,t){e.addFieldOffset(8,t,0)}static endModel(e){return e.endObject()}static createModel(e,t,r,i,o,s,a,u,l,c){return n.startModel(e),n.addIrVersion(e,t),n.addOpsetImport(e,r),n.addProducerName(e,i),n.addProducerVersion(e,o),n.addDomain(e,s),n.addModelVersion(e,a),n.addDocString(e,u),n.addGraph(e,l),n.addGraphDocString(e,c),n.endModel(e)}}t.Model=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){class t{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsKernelCreateInfos(e,n){return(n||new t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsKernelCreateInfos(e,n){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new t).__init(e.readInt32(e.position())+e.position(),e)}nodeIndices(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb.__vector(this.bb_pos+t)+4*e):0}nodeIndicesLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}nodeIndicesArray(){let e=this.bb.__offset(this.bb_pos,4);return e?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}kernelDefHashes(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}kernelDefHashesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}static startKernelCreateInfos(e){e.startObject(2)}static addNodeIndices(e,t){e.addFieldOffset(0,t,0)}static createNodeIndicesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startNodeIndicesVector(e,t){e.startVector(4,t,4)}static addKernelDefHashes(e,t){e.addFieldOffset(1,t,0)}static createKernelDefHashesVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startKernelDefHashesVector(e,t){e.startVector(8,t,8)}static endKernelCreateInfos(e){return e.endObject()}static createKernelCreateInfos(e,n,r){return t.startKernelCreateInfos(e),t.addNodeIndices(e,n),t.addKernelDefHashes(e,r),t.endKernelCreateInfos(e)}}e.KernelCreateInfos=t}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSubGraphSessionState(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSubGraphSessionState(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}graphId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}sessionState(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSubGraphSessionState(e){e.startObject(2)}static addGraphId(e,t){e.addFieldOffset(0,t,0)}static addSessionState(e,t){e.addFieldOffset(1,t,0)}static endSubGraphSessionState(e){let t=e.endObject();return e.requiredField(t,4),t}static createSubGraphSessionState(e,t,r){return n.startSubGraphSessionState(e),n.addGraphId(e,t),n.addSessionState(e,r),n.endSubGraphSessionState(e)}}t.SubGraphSessionState=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSessionState(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSessionState(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}kernels(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}subGraphSessionStatesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSessionState(e){e.startObject(2)}static addKernels(e,t){e.addFieldOffset(0,t,0)}static addSubGraphSessionStates(e,t){e.addFieldOffset(1,t,0)}static createSubGraphSessionStatesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startSubGraphSessionStatesVector(e,t){e.startVector(4,t,4)}static endSessionState(e){return e.endObject()}static createSessionState(e,t,r){return n.startSessionState(e),n.addKernels(e,t),n.addSubGraphSessionStates(e,r),n.endSessionState(e)}}t.SessionState=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInferenceSession(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsInferenceSession(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static bufferHasIdentifier(e){return e.__has_identifier("ORTM")}ortVersion(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}model(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startInferenceSession(e){e.startObject(3)}static addOrtVersion(e,t){e.addFieldOffset(0,t,0)}static addModel(e,t){e.addFieldOffset(1,t,0)}static addSessionState(e,t){e.addFieldOffset(2,t,0)}static endInferenceSession(e){return e.endObject()}static finishInferenceSessionBuffer(e,t){e.finish(t,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(e,t){e.finish(t,"ORTM",!0)}static createInferenceSession(e,t,r,i){return n.startInferenceSession(e),n.addOrtVersion(e,t),n.addModel(e,r),n.addSessionState(e,i),n.endInferenceSession(e)}}t.InferenceSession=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={}))},1723:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OnnxjsSessionHandler=void 0;const r=n(8453),i=n(9240);t.OnnxjsSessionHandler=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(e,t,n){const o=new Map;for(const t in e)if(Object.hasOwnProperty.call(e,t)){const n=e[t];o.set(t,new i.Tensor(n.dims,n.type,void 0,void 0,n.data))}const s=await this.session.run(o),a={};return s.forEach(((e,t)=>{a[t]=new r.Tensor(e.type,e.data,e.dims)})),a}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6027:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Session=void 0;const r=n(7067),i=n(1296),o=n(1975),s=n(6496),a=n(1315),u=n(1745);t.Session=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=a.Profiler.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,t,n){await this.profiler.event("session","Session.loadModel",(async()=>{const s=await(0,o.resolveBackend)(this.backendHint);if(this.sessionHandler=s.createSessionHandler(this.context),this._model=new u.Model,"string"==typeof e){const t=e.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(e);this.initialize(n,t)}else{const n=await fetch(e),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),t)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{const r=new Uint8Array(e,t||0,n||e.byteLength);this.initialize(r)}}))}initialize(e,t){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",(()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,n,t),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.ExecutionPlan(this._model.graph,this._ops,this.profiler)})),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",(async()=>{const t=this.normalizeAndValidateInputs(e),n=await this._executionPlan.execute(this.sessionHandler,t);return this.createOutput(n)}))}normalizeAndValidateInputs(e){const t=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==t.length)throw new Error(`incorrect input array length: expected ${t.length} but got ${e.length}`)}else{if(e.size!==t.length)throw new Error(`incorrect input map size: expected ${t.length} but got ${e.size}`);const n=new Array(e.size);let r=0;for(let i=0;i<t.length;++i){const o=e.get(t[i]);if(!o)throw new Error(`missing input tensor for: '${name}'`);n[r++]=o}e=n}if(this.context.graphInputTypes&&0!==this.context.graphInputTypes.length&&this.context.graphInputDims&&0!==this.context.graphInputDims.length)this.validateInputTensorDims(this.context.graphInputDims,e,!1);else{const t=this._model.graph.getInputIndices(),n=this._model.graph.getValues(),r=new Array(t.length);for(let i=0;i<t.length;++i){const o=n[t[i]];r[i]=o.type.shape.dims,this.context.graphInputTypes.push(o.type.tensorType),this.context.graphInputDims.push(e[i].dims)}this.validateInputTensorDims(r,e,!0)}return this.validateInputTensorTypes(this.context.graphInputTypes,e),e}validateInputTensorTypes(e,t){for(let n=0;n<t.length;n++){const r=e[n],i=t[n].type;if(r!==i)throw new Error(`input tensor[${n}] check failed: expected type '${r}' but got ${i}`)}}validateInputTensorDims(e,t,n){for(let r=0;r<t.length;r++){const i=e[r],o=t[r].dims;if(!this.compareTensorDims(i,o,n))throw new Error(`input tensor[${r}] check failed: expected shape '[${i.join(",")}]' but got [${o.join(",")}]`)}}compareTensorDims(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;++r)if(e[r]!==t[r]&&(!n||0!==e[r]))return!1;return!0}createOutput(e){const t=this._model.graph.getOutputNames();if(e.length!==t.length)throw new Error("expected number of outputs do not match number of generated outputs");const n=new Map;for(let r=0;r<t.length;++r)n.set(t[r],e[r]);return n}initializeOps(e){const t=e.getNodes();this._ops=new Array(t.length);for(let n=0;n<t.length;n++)this._ops[n]=this.sessionHandler.resolve(t[n],this._model.opsets,e)}}},9240:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Tensor=void 0;const i=n(3442),o=r(n(3720)),s=n(1446),a=n(1287),u=n(7273);var l=a.onnxruntime.experimental.fbs;class c{get data(){if(void 0===this.cache){const e=this.dataProvider(this.dataId);if(e.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=e}return this.cache}get stringData(){if("string"!==this.type)throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if("string"!==this.type)return this.data;throw new TypeError("type cannot be non-number (string)")}get(e){return this.data[u.ShapeUtil.indicesToOffset(e,this.strides)]}set(e,t){this.data[u.ShapeUtil.indicesToOffset(e,this.strides)]=t}async getData(){return void 0===this.cache&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=u.ShapeUtil.computeStrides(this.dims)),this._strides}constructor(e,t,n,r,o,s=i.Guid.create()){this.dims=e,this.type=t,this.dataProvider=n,this.asyncDataProvider=r,this.cache=o,this.dataId=s,this.size=u.ShapeUtil.validateDimsAndCalcSize(e);const a=this.size,l=void 0===n&&void 0===r&&void 0===o;if(void 0!==o&&o.length!==a)throw new RangeError("Input dims doesn't match data length.");if("string"===t){if(!(void 0===o||Array.isArray(o)&&o.every((e=>"string"==typeof e))))throw new TypeError("cache should be a string array");l&&(this.cache=new Array(a))}else{if(void 0!==o){const e=h(t);if(!(o instanceof e))throw new TypeError(`cache should be type ${e.name}`)}if(l){const e=new ArrayBuffer(a*function(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}(t));this.cache=function(e,t){return new(h(t))(e)}(e,t)}}}static fromProto(e){if(!e)throw new Error("cannot construct Value from an empty tensor");const t=u.ProtoUtil.tensorDataTypeFromProto(e.dataType),n=u.ProtoUtil.tensorDimsFromProto(e.dims),r=new c(n,t);if("string"===t)e.stringData.forEach(((e,t)=>{r.data[t]=(0,u.decodeUtf8String)(e)}));else if(e.rawData&&"number"==typeof e.rawData.byteLength&&e.rawData.byteLength>0){const t=r.data,n=new DataView(e.rawData.buffer,e.rawData.byteOffset,e.rawData.byteLength),i=d(e.dataType),o=e.rawData.byteLength/i;if(e.rawData.byteLength%i!=0)throw new Error("invalid buffer length");if(t.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=f(n,e.dataType,r*i);t[r]=o}}else{let t;switch(e.dataType){case s.onnx.TensorProto.DataType.FLOAT:t=e.floatData;break;case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.INT16:case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.BOOL:t=e.int32Data;break;case s.onnx.TensorProto.DataType.INT64:t=e.int64Data;break;case s.onnx.TensorProto.DataType.DOUBLE:t=e.doubleData;break;case s.onnx.TensorProto.DataType.UINT32:case s.onnx.TensorProto.DataType.UINT64:t=e.uint64Data;break;default:throw new Error("unspecific error")}if(null==t)throw new Error("failed to populate data from a tensorproto value");const n=r.data;if(n.length!==t.length)throw new Error("array length mismatch");for(let r=0;r<t.length;r++){const i=t[r];o.default.isLong(i)?n[r]=p(i,e.dataType):n[r]=i}}return r}static fromData(e,t,n){return new c(t,n,void 0,void 0,e)}static fromOrtTensor(e){if(!e)throw new Error("cannot construct Value from an empty tensor");const t=u.ProtoUtil.tensorDimsFromORTFormat(e),n=u.ProtoUtil.tensorDataTypeFromProto(e.dataType()),r=new c(t,n);if("string"===n)for(let t=0;t<e.stringDataLength();t++)r.data[t]=e.stringData(t);else if(e.rawDataArray()&&"number"==typeof e.rawDataLength()&&e.rawDataLength()>0){const t=r.data,n=new DataView(e.rawDataArray().buffer,e.rawDataArray().byteOffset,e.rawDataLength()),i=d(e.dataType()),o=e.rawDataLength()/i;if(e.rawDataLength()%i!=0)throw new Error("invalid buffer length");if(t.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=f(n,e.dataType(),r*i);t[r]=o}}return r}}function d(e){switch(e){case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.BOOL:return 1;case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT16:return 2;case s.onnx.TensorProto.DataType.FLOAT:case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.UINT32:return 4;case s.onnx.TensorProto.DataType.INT64:case s.onnx.TensorProto.DataType.DOUBLE:case s.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${s.onnx.TensorProto.DataType[e]}`)}}function h(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function p(e,t){if(t===s.onnx.TensorProto.DataType.INT64||t===l.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else{if(t!==s.onnx.TensorProto.DataType.UINT32&&t!==l.TensorDataType.UINT32&&t!==s.onnx.TensorProto.DataType.UINT64&&t!==l.TensorDataType.UINT64)throw new TypeError(`not a LONG type: ${s.onnx.TensorProto.DataType[t]}`);if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}return e.toNumber()}function f(e,t,n){switch(t){case s.onnx.TensorProto.DataType.BOOL:case s.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case s.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case s.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,!0);case s.onnx.TensorProto.DataType.INT16:return e.getInt16(n,!0);case s.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,!0);case s.onnx.TensorProto.DataType.INT32:return e.getInt32(n,!0);case s.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,!0);case s.onnx.TensorProto.DataType.INT64:return p(o.default.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!1),t);case s.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,!0);case s.onnx.TensorProto.DataType.UINT64:return p(o.default.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!0),t);default:throw new Error(`cannot read from DataView for type ${s.onnx.TensorProto.DataType[t]}`)}}t.Tensor=c},7273:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decodeUtf8String=t.MAX_CLIP=t.MIN_CLIP=t.PoolConvUtil=t.ReduceUtil=t.SplitUtil=t.MathUtil=t.ShapeUtil=t.LongUtil=t.ProtoUtil=t.GemmUtil=t.arrayCopyHelper=t.BroadcastUtil=t.MatMulUtil=t.ArrayUtil=t.assert=t.checkInputsShape=void 0;const i=n(5686),o=r(n(3720)),s=n(1446),a=n(9240);t.checkInputsShape=function(e,...t){if(!e||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].dims||e[n].dims.length!==t[n])return!1;return!0},t.assert=function(e,t){if(!e)throw new Error("string"==typeof t?t:t())},t.ArrayUtil=class{static arraysEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}};class u{static preprocessInputShapes(e,t){return[1===e.length?[1,e[0]]:e,1===t.length?[t[0],1]:t]}static postprocessOutputShape(e,t,n){1===t&&e.splice(e.length-2,1),1===n&&e.pop()}static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}}t.MatMulUtil=u;class l{static calcShape(e,t,n=!1){const r=e.length,i=t.length;if(0===r)return t;if(0===i)return e;const o=Math.max(e.length,t.length),s=new Array(o);if(n){if(r<2||i<2)return;const n=u.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(void 0===n)return;[s[o-2],s[o-1]]=n}for(let a=n?3:1;a<=o;a++){const n=r-a<0?1:e[r-a],u=i-a<0?1:t[i-a];if(n!==u&&n>1&&u>1)return;s[o-a]=Math.max(n,u)}return s}static index(e,t){const n=new Array(t.length);return l.fillIndex(e,t,n),n}static fillIndex(e,t,n){const r=e.length-t.length;for(let i=0;i<t.length;i++)n[i]=e[r+i]%t[i]}static calc(e,t,n,r,i){const o=l.calcShape(e.dims,t.dims);if(o){if(r&&!h.areEqual(o,e.dims))return;const s=h.size(o),u=r?e:new a.Tensor(o,i||e.type);if(0===o.length)u.set([],n(e.get([]),t.get([])));else{const r=new Array(o.length),i=new Array(e.dims.length),a=new Array(t.dims.length);let c,d=0,h=0,p=!1,f=!1;0===e.dims.length&&(d=e.get([]),p=!0),0===t.dims.length&&(h=t.get([]),f=!0);for(let g=0;g<s;g++){c=g;for(let e=o.length-1;e>=0;e--)r[e]=c%o[e],c=Math.floor(c/o[e]);p||(l.fillIndex(r,e.dims,i),d=e.get(i)),f||(l.fillIndex(r,t.dims,a),h=t.get(a)),u.set(r,n(d,h))}}return u}}static isValidBroadcast(e,t){const n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==e[n-i]&&e[n-i]!==t[r-i])return!1;return!0}static getBroadcastDims(e,t){const n=e.length,r=[];for(let i=0;i<n;i++){const o=n-1-i,s=e[o]||1;(t[t.length-1-i]||1)>1&&1===s&&r.unshift(o)}return r}}t.BroadcastUtil=l,t.arrayCopyHelper=function(e,t,n,r,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)e[n+o]=t[r+o]},t.GemmUtil=class{static getShapeOfGemmResult(e,t,n,r,i){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let o,s,a;t?(o=e[1],s=e[0]):(o=e[0],s=e[1]);let u=-1;if(r?(a=n[0],u=1):(a=n[1],u=0),n[u]!==s)throw new Error("dimension mismatch");if(o<=0||a<=0||s<=0)throw new Error("invalid shape specified");if(i&&!l.isValidBroadcast(i,[o,a]))throw new Error("gemm: invalid bias shape for broadcast");return[o,a,s]}};class c{static tensorDataTypeFromProto(e){switch(e){case s.onnx.TensorProto.DataType.INT8:return"int8";case s.onnx.TensorProto.DataType.UINT8:return"uint8";case s.onnx.TensorProto.DataType.BOOL:return"bool";case s.onnx.TensorProto.DataType.INT16:return"int16";case s.onnx.TensorProto.DataType.UINT16:return"uint16";case s.onnx.TensorProto.DataType.INT32:return"int32";case s.onnx.TensorProto.DataType.UINT32:return"uint32";case s.onnx.TensorProto.DataType.FLOAT:return"float32";case s.onnx.TensorProto.DataType.DOUBLE:return"float64";case s.onnx.TensorProto.DataType.STRING:return"string";case s.onnx.TensorProto.DataType.INT64:return"int32";case s.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${s.onnx.TensorProto.DataType[e]}`)}}static tensorDataTypeStringToEnum(e){switch(e){case"int8":return s.onnx.TensorProto.DataType.INT8;case"uint8":return s.onnx.TensorProto.DataType.UINT8;case"bool":return s.onnx.TensorProto.DataType.BOOL;case"int16":return s.onnx.TensorProto.DataType.INT16;case"uint16":return s.onnx.TensorProto.DataType.UINT16;case"int32":return s.onnx.TensorProto.DataType.INT32;case"uint32":return s.onnx.TensorProto.DataType.UINT32;case"float32":return s.onnx.TensorProto.DataType.FLOAT;case"float64":return s.onnx.TensorProto.DataType.DOUBLE;case"string":return s.onnx.TensorProto.DataType.STRING;case"int64":return s.onnx.TensorProto.DataType.INT64;case"uint64":return s.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${e}`)}}static tensorDimsFromProto(e){return e.map((e=>o.default.isLong(e)?e.toNumber():e))}static tensorValueTypeFromProto(e){return{tensorType:c.tensorDataTypeFromProto(e.elemType),shape:{dims:c.tensorDimsFromProto(e.shape.dim.map((e=>e.dimValue)))}}}static tensorDimsFromORTFormat(e){const t=[];for(let n=0;n<e.dimsLength();n++)t.push(d.longToNumber(e.dims(n)));return t}static tensorAttributesFromORTFormat(e){const t=[];for(let n=0;n<e.attributesLength();n++)t.push(e.attributes(n));return t}}t.ProtoUtil=c;class d{static longToNumber(e,t){return o.default.isLong(e)?e.toNumber():e instanceof i.flatbuffers.Long?o.default.fromValue({low:e.low,high:e.high,unsigned:null!=t&&t}).toNumber():e}static isLong(e){return o.default.isLong(e)||e instanceof i.flatbuffers.Long}}t.LongUtil=d;class h{static size(e){return h.getSizeFromDimensionRange(e,0,e.length)}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return h.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return h.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=e[i]}return r}static computeStrides(e){const t=e.length;if(0===t)return[];if(1===t)return[1];const n=new Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static transpose(e){return e.slice().reverse()}static indicesToOffset(e,t,n){void 0===n&&(n=e.length);let r=0;for(let i=0;i<n;++i)r+=t[i]*e[i];return r}static offsetToIndices(e,t){const n=t.length;if(0===n)return[];if(1===n)return[e*t[0]];const r=new Array(t.length);for(let n=0;n<r.length-1;++n)r[n]=Math.floor(e/t[n]),e-=r[n]*t[n];return r[r.length-1]=e,r}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((e=>this.normalizeAxis(e,t)))}static incrementIndex(e,t,n){if(0===t.length||0===e.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=t.length;else if(n<=0||n>t.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(e[r]++,!(e[r]<t[r]));--r)e[r]=0}static calculateReshapedDims(e,t){if(0===t.length){if(0===e.length||1===h.size(e))return[];throw new Error("cannot reshape to a scalar Tensor")}const n=t.length,r=new Array(n);let i=-1,o=1;for(let s=0;s<n;s++){if(t[s]<-1)throw new Error("a dimension in shape hints cannot be less than -1");if(-1===t[s]){if(-1!==i)throw new Error("at most one dimension in shape hints can be -1");i=s}else{if(0===t[s]){if(s>=e.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[s]=e[s]}else r[s]=t[s];o*=r[s]}}const s=h.size(e);if(-1!==i){if(s%o!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${t}]`);r[i]=s/o}else if(o!==s)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){const n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}static validateDimsAndCalcSize(e){if(e.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let t=1;for(const n of e){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);t*=n}return t}static flattenShape(e,t){t<0&&(t+=e.length);const n=e.reduce(((e,t)=>e*t),1),r=e.slice(t).reduce(((e,t)=>e*t),1);return[n/r,r]}static squeezeShape(e,t){const n=new Array;t=h.normalizeAxes(t,e.length);for(let r=0;r<e.length;r++){const i=t.indexOf(r)>=0;if(i&&1!==e[r])throw new Error("squeeze an axis of size different than 1");(0===t.length&&e[r]>1||t.length>0&&!i)&&n.push(e[r])}return n}static unsqueezeShape(e,t){const n=new Array(e.length+t.length);n.fill(0);for(let e=0;e<t.length;e++){const r=h.normalizeAxis(t[e],n.length);if(r>=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let t=0;t<n.length;t++)0===n[t]&&(n[t]=e[r++]);if(r!==e.length)throw new Error("the unsqueezed dimension could not be established");return n}}t.ShapeUtil=h,t.MathUtil=class{static sqr(e,t,n,r,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)e[n+o]+=Math.pow(t[r+o],2)}static axpy(e,t,n,r,i,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let s=0;s<i;s++)e[n+s]+=o*t[r+s]}static powx(e,t,n,r,i,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let s=0;s<i;s++)e[n+s]=Math.pow(t[r+s],o)}static mul(e,t,n,r,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)e[n+o]=t[r+o]*e[n+o]}};class p{static splitShape(e,t,n,r){if(0===n.length){if(!r)throw new Error("need to know number of outputs when the 'split' attribute is not specified");p.determineSplit(e[t],r,n)}const i=[],o=[0];for(let r=0;r<n.length;++r){0!==r&&o.push(o[r-1]+n[r-1]);const s=e.slice();s[t]=n[r],i.push(s)}return[i,o]}static determineSplit(e,t,n){if(e%t!=0)throw new Error("cannot split tensor to equal sized parts");for(let r=0;r<t;++r)n.push(e/t)}}t.SplitUtil=p;class f{static calcReduce(e,t,n,r,i){const o=e.dims.slice(0);0===t.length&&o.forEach(((e,n)=>t.push(n)));const s=f.calcReduceShape(o,t,!0),u=h.size(s),c=new a.Tensor(s,e.type),d=h.computeStrides(s),p=h.computeStrides(o),g=new Array(o.length);for(let n=0;n<u;n++){const s=h.offsetToIndices(n,d);l.fillIndex(s,o,g),c.set(s,f.calcReduceByAxis(e.numberData,t,o,0,h.indicesToOffset(g,p),r,i))}return n?c:new a.Tensor(f.calcReduceShape(o,t,n),c.type,void 0,void 0,c.data,c.dataId)}static calcReduceByAxis(e,t,n,r,i,o,s){let a=0;if(r>=t.length)return o(e[i]);const u=t[r],l=u>=n.length?1:h.size(n.slice(u+1));for(let c=0;c<n[u];c++)a=0===c?f.calcReduceByAxis(e,t,n,r+1,i,o,s):s(a,f.calcReduceByAxis(e,t,n,r+1,i,o,s)),i+=l;return a}static calcReduceShape(e,t,n){const r=e.slice();for(let e=0;e<t.length;e++)r[t[e]]=n?1:0;return r.filter((e=>0!==e))}}t.ReduceUtil=f;class g{static adjustPoolAttributes(e,t,n,r,i,o){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw new Error("dilations should be greater than or equal to 1")}else i.push(1);for(let e=0;e<2*n.length;e++)if(e<o.length){if(o[e]<0)throw new Error("pad should be greater than or equal to 1")}else o.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw new Error("kernel shapes need to be greater than 0");if(o[e]>=n[e]||o[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,n,r,i,o){if(o){if(i.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s<e.length-2;s++)g.adjustPadAndReturnShape(e[s+2],t[s],n[s],r[s],i,s,s+e.length-2,o)}}static computePoolOutputShape(e,t,n,r,i,o,s){if(t.length<=0)throw new Error("input shape must be of size greater than 0");const a=[t[0],t[1]];return g.computeShapeHelper(e,t,a,n,r,i,o,s),a}static computeConvOutputShape(e,t,n,r,i,o,s){if(e.length<=0||t.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const a=[e[0],t[0]];return g.computeShapeHelper(!1,e,a,n,r,i,o,s),a}static computeShapeHelper(e,t,n,r,i,o,s,a){if(e)for(let e=0;e<t.length-2;e++)n.push(1);else for(let e=0;e<t.length-2;e++)n.push(g.adjustPadAndReturnShape(t[e+2],r[e],i[e],o[e],s,e,e+t.length-2,a))}static adjustPadAndReturnShape(e,t,n,r,i,o,s,a){const u=n*(r-1)+1;if(!a||"NOTSET"===a)return Math.floor((e+i[o]+i[s]-u)/t+1);switch(a){case"VALID":return i[o]=0,i[s]=0,Math.floor((e-u)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((e+t-1)/t-1)*t+r-e;return i[o]="SAME_LOWER"===a?Math.floor((n+1)/2):Math.floor(n/2),i[s]=n-i[o],Math.floor((e+n-r)/t+1)}default:throw new Error("Unsupported AutoPad type")}}}t.PoolConvUtil=g,t.MIN_CLIP=-34028234663852886e22,t.MAX_CLIP=34028234663852886e22,t.decodeUtf8String=function(e){return(new TextDecoder).decode(e)}},3838:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGpuBackend=void 0;const r=n(8453),i=n(4955),o=n(7771),s=n(8510),a=n(8305);t.WebGpuBackend=class{constructor(){this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.pendingDispatchNumber=0,this.profilingEnabled=!1}get currentKernelCustomData(){if(null===this.currentKernelId)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(){if(!navigator.gpu)throw new Error("WebGpuBackend: WebGPU is not available.");const e=await navigator.gpu.requestAdapter();if(!e)throw new Error("WebGpuBackend: Failed to get GPU adapter.");const t={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize}};e.features.has("timestamp-query-inside-passes")&&"default"===r.env.webgpu.profilingMode&&(this.profilingEnabled=!0,t.requiredFeatures=["timestamp-query-inside-passes"]),this.device=await e.requestDevice(t),this.gpuDataManager=(0,o.createGpuDataManager)(this),this.programManager=new a.ProgramManager(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},this.profilingEnabled&&(this.profilingQuerySet=this.device.createQuerySet({type:"timestamp",count:2}))}dispose(){}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){return this.computePassEncoder||(this.computePassEncoder=this.getCommandEncoder().beginComputePass()),this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){this.endComputePass(),this.device.queue.submit([this.getCommandEncoder().finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0}run(e,t,n,r,o){if(t.length!==e.inputTypes.length)throw new Error(`Input size must be equal to ${e.inputTypes.length}.`);const s=[];for(let e=0;e<t.length;++e){const n=this.gpuDataManager.get(t[e].data);if(!n)throw new Error(`no GPU data for input: ${t[e].data}`);s[e]=n}const a=((e,t,n)=>{const r=t.map((e=>`${e.join(",")}`)).join("_"),i=n.join("_");let o=e.name;return e.cacheHint&&(o+="["+e.cacheHint+"]"),o+=":"+r+";"+i,o})(e,t.map((e=>e.dims)),s.map((e=>e.type)));let u=this.programManager.getArtifact(a);const l=u?u.programInfo:"function"==typeof e.get?e.get():e,c=0===n.length?l.outputs.map(((e,t)=>t)):n;if(c.length!==l.outputs.length)throw new Error(`Output size ${c.length} must be equal to ${l.outputs.length}.`);const d=[],h=[];for(let e=0;e<l.outputs.length;++e){if(!Number.isInteger(c[e])||c[e]<-2||c[e]>=l.outputs.length)throw new Error(`Invalid output index: ${c[e]}`);const t=-1===c[e],n=-2===c[e],i=t||n?o(l.outputs[e].dataType,l.outputs[e].dims):r(c[e],l.outputs[e].dataType,l.outputs[e].dims),s=this.gpuDataManager.get(i.data);if(!s)throw new Error(`no GPU data for output: ${i.data}`);if(t&&this.temporaryData.push(s),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(s)}d.push(i),h.push(s)}const p=this.programManager.normalizeDispatchGroupSize(l.dispatchGroup(t));return u||(u=this.programManager.build(l,p),this.programManager.setArtifact(a,u)),(0,i.LOG_DEBUG)("info",(()=>`[ProgramManager] run "${l.name}" (key=${a}) with ${p[0]}x${p[1]}x${p[2]}`)),this.programManager.run(u,s,h,p),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){const n=await this.gpuDataManager.download(e);t().set(new Uint8Array(n))}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n){const r=s.WEBGPU_OP_RESOLVE_RULES.get(e);if(!r)throw new Error(`kernel not implemented: ${e}`);this.kernels.set(t,[e,r[0],[r[1],n]])}releaseKernel(e){const t=this.kernelPersistentData.get(e);if(t){for(const e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t){const n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);const[r,o,s]=n;if(null!==this.currentKernelId)throw new Error(`kernel "${r}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&(s[1]=s[0](s[1]),s[0]=void 0),(0,i.LOG_DEBUG)("info",(()=>`[WebGPU] Start to run kernel "${r}"...`)),this.temporaryData=[];try{return o(t,s[1]),0}catch(e){return(0,i.LOG_DEBUG)("warning",`[WebGPU] Kernel "${r}" failed. Error: ${e}`),1}finally{for(const e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}}},7675:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const r=n(7917),i=n(3838),o=n(4955),s=n(6952);class a{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){return new Float32Array(this.module.HEAP8.buffer,this.data,s.ShapeUtil.size(this.dims))}reshape(e){if(s.ShapeUtil.size(e)!==s.ShapeUtil.size(this.dims))throw new Error("Invalid new shape");return new a(this.module,this.dataType,this.data,e)}}class u{get customData(){return this.backend.currentKernelCustomData}constructor(e,t,n){this.module=e,this.backend=t;const r=e.HEAPU32;let i=n>>2;this.opKernelContext=r[i++];const o=r[i++],s=[];for(let t=0;t<o;t++){const t=r[i++],n=r[i++],o=r[i++],u=[];for(let e=0;e<o;e++)u.push(r[i++]);s.push(new a(e,t,n,u))}this.inputs=s}compute(e,t){var n,i,o;const u=null!==(i=null===(n=null==t?void 0:t.inputs)||void 0===n?void 0:n.map((e=>"number"==typeof e?this.inputs[e]:e)))&&void 0!==i?i:this.inputs,l=null!==(o=null==t?void 0:t.outputs)&&void 0!==o?o:[];return this.backend.run(e,u,l,((e,t,n)=>new a(this.module,t,this.output(e,n),n)),((e,t)=>{const n=(0,r.getTensorElementSize)(e);if(!n)throw new Error(`Unsupported data type: ${e}`);const i=n*s.ShapeUtil.size(t);return new a(this.module,e,this.backend.gpuDataManager.create(i).id,t)}))}output(e,t){const n=this.module.stackSave();try{const n=this.module.stackAlloc(4*(1+t.length));let r=n>>2;this.module.HEAPU32[r++]=t.length;for(let e=0;e<t.length;e++)this.module.HEAPU32[r++]=t[e];return this.module._JsepOutput(this.opKernelContext,e,n)}finally{this.module.stackRestore(n)}}}t.init=async e=>{const t=e.jsepInit;if(t&&navigator.gpu){const n=new i.WebGpuBackend;await n.initialize(),t({backend:n},(e=>n.alloc(e)),(e=>n.free(e)),((t,r,i,s=!1)=>{if(s)(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepCopyGpuToGpu: src=${t}, dst=${r}, size=${i}`)),n.memcpy(t,r);else{(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${t}, gpuDataId=${r}, size=${i}`));const s=e.HEAPU8.subarray(t,t+i);n.upload(r,s)}}),(async(t,r,i)=>{(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${t}, dataOffset=${r}, size=${i}`)),await n.download(t,(()=>e.HEAPU8.subarray(r,r+i)))}),((e,t,r)=>n.createKernel(e,t,r)),(e=>n.releaseKernel(e)),((t,r)=>{(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepRun: kernel=${t}, contextDataOffset=${r}`));const i=new u(e,n,r);return n.computeKernel(t,i)}))}}},4955:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LOG_DEBUG=t.LOG=void 0;const r=n(8453),i=n(7917),o=["V","I","W","E","F"];t.LOG=(e,t)=>{const n=(0,i.logLevelStringToEnum)(e);var s,a;n>=(0,i.logLevelStringToEnum)(r.env.logLevel)&&(s=n,a="function"==typeof t?t():t,console.log(`[${o[s]},${(new Date).toISOString()}]${a}`))},t.LOG_DEBUG=(...e)=>{r.env.debug&&(0,t.LOG)(...e)}},6952:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_CLIP=t.MIN_CLIP=t.GemmUtil=t.PoolConvUtil=t.ShapeUtil=t.BroadcastUtil=t.MatMulUtil=void 0;class n{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}}t.MatMulUtil=n;class r{static calcShape(e,t,r=!1){const i=e.length,o=t.length;if(0===i)return t;if(0===o)return e;const s=Math.max(e.length,t.length),a=new Array(s);if(r){if(i<2||o<2)return;const r=n.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(void 0===r)return;[a[s-2],a[s-1]]=r}for(let n=r?3:1;n<=s;n++){const r=i-n<0?1:e[i-n],u=o-n<0?1:t[o-n];if(r!==u&&r>1&&u>1)return;a[s-n]=Math.max(r,u)}return a}static isValidBroadcast(e,t){const n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==e[n-i]&&e[n-i]!==t[r-i])return!1;return!0}}t.BroadcastUtil=r;class i{static size(e){return i.getSizeFromDimensionRange(e,0,e.length)}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return i.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return i.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=e[i]}return r}static computeStrides(e){const t=e.length;if(0===t)return[];if(1===t)return[1];const n=new Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((n=>this.normalizeAxis(n,null!=t?t:e.length)))}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){const n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}}t.ShapeUtil=i;class o{static adjustPoolAttributes(e,t,n,r,i,o){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw new Error("dilations should be greater than or equal to 1")}else i.push(1);for(let e=0;e<2*n.length;e++)if(e<o.length){if(o[e]<0)throw new Error("pad should be greater than or equal to 1")}else o.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw new Error("kernel shapes need to be greater than 0");if(o[e]>=n[e]||o[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,n,r,i,s,a){if(a){if(i.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let u=0;u<e.length-2;u++)o.adjustPadAndReturnShape(e[u+(s?1:2)],t[u],n[u],r[u],i,u,u+e.length-2,a)}}static computePoolOutputShape(e,t,n,r,i,s,a){if(t.length<=0)throw new Error("input shape must be of size greater than 0");const u=[t[0],t[1]];return o.computeShapeHelper(e,t,u,n,r,i,s,a),u}static computeConvOutputShape(e,t,n,r,i,s,a){if(e.length<=0||t.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const u=[e[0],t[0]];return o.computeShapeHelper(!1,e,u,n,r,i,s,a),u}static computeShapeHelper(e,t,n,r,i,s,a,u){if(e)for(let e=0;e<t.length-2;e++)n.push(1);else for(let e=0;e<t.length-2;e++)n.push(o.adjustPadAndReturnShape(t[e+2],r[e],i[e],s[e],a,e,e+t.length-2,u))}static adjustPadAndReturnShape(e,t,n,r,i,o,s,a){const u=n*(r-1)+1;if(!a||"NOTSET"===a)return Math.floor((e+i[o]+i[s]-u)/t+1);switch(a){case"VALID":return i[o]=0,i[s]=0,Math.floor((e-u)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((e+t-1)/t-1)*t+r-e;return i[o]="SAME_LOWER"===a?Math.floor((n+1)/2):Math.floor(n/2),i[s]=n-i[o],Math.floor((e+n-r)/t+1)}default:throw new Error("Unsupported AutoPad type")}}}t.PoolConvUtil=o,t.GemmUtil=class{static getShapeOfGemmResult(e,t,n,i,o){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let s,a,u;t?(s=e[1],a=e[0]):(s=e[0],a=e[1]);let l=-1;if(i?(u=n[0],l=1):(u=n[1],l=0),n[l]!==a)throw new Error("dimension mismatch");if(s<=0||u<=0||a<=0)throw new Error("invalid shape specified");if(o&&!r.isValidBroadcast(o,[s,u]))throw new Error("gemm: invalid bias shape for broadcast");return[s,u,a]}},t.MIN_CLIP=-34028234663852886e22,t.MAX_CLIP=34028234663852886e22},387:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAttributeWithCacheKey=void 0;class n{constructor(e){Object.assign(this,e)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this._cacheKey}}t.createAttributeWithCacheKey=e=>new n(e)},7771:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createGpuDataManager=void 0;const r=n(4955),i=n(1163),o=e=>16*Math.ceil(e/16);let s=0;class a{constructor(e){this.backend=e,this.storageCache=new Map,this.downloadCache=new Map,this.buffersForUploadingPending=[],this.buffersPending=[]}upload(e,t){const n=t.buffer,i=t.byteOffset,s=t.byteLength,a=o(s),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(u.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${s}`);const l=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=l.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,i,s)),l.unmap();const d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(l,0,u.gpuData.buffer,0,a),(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] GpuDataManager.upload(id=${e})`)),this.buffersForUploadingPending.push(l)}memcpy(e,t){const n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");const r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");const i=o(n.originalSize);this.backend.getCommandEncoder().copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){const n=o(e),a=this.backend.device.createBuffer({size:n,usage:t}),u={id:s++,type:i.GpuDataType.default,buffer:a};return this.storageCache.set(u.id,{gpuData:u,originalSize:e}),(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${u.id}`)),u}get(e){var t;return null===(t=this.storageCache.get(e))||void 0===t?void 0:t.gpuData}release(e){const t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`)),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),this.downloadCache.get(e)&&this.downloadCache.delete(e),t.originalSize}async download(e){const t=this.downloadCache.get(e);if(t)return t.data;const n=this.storageCache.get(e);if(!n)throw new Error("data does not exist");const r=this.backend.getCommandEncoder();this.backend.endComputePass();const i=this.backend.device.createBuffer({size:n.originalSize,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});r.copyBufferToBuffer(n.gpuData.buffer,0,i,0,n.originalSize),this.backend.flush();const o=new Promise((e=>{i.mapAsync(GPUMapMode.READ).then((()=>{const t=i.getMappedRange().slice(0);i.destroy(),e(t)}))}));return this.downloadCache.set(e,{data:o}),o}refreshPendingBuffers(){for(const e of this.buffersForUploadingPending)e.destroy();for(const e of this.buffersPending)e.destroy()}}t.createGpuDataManager=(...e)=>new a(...e)},8510:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WEBGPU_OP_RESOLVE_RULES=void 0;const s=o(n(504)),a=n(9770),u=n(4271),l=n(1522),c=o(n(5262)),d=n(2625),h=o(n(9302));t.WEBGPU_OP_RESOLVE_RULES=new Map([["Abs",[h.abs]],["Acos",[h.acos]],["Acosh",[h.acosh]],["Add",[s.add]],["Asin",[h.asin]],["Asinh",[h.asinh]],["Atan",[h.atan]],["Atanh",[h.atanh]],["AveragePool",[c.averagePool,c.parseAveragePoolAttributes]],["Ceil",[h.ceil]],["ClipV10",[h.clipV10]],["Clip",[h.clip]],["Conv",[a.conv,a.parseConvAttributes]],["Cos",[h.cos]],["Cosh",[h.cosh]],["Div",[s.div]],["Elu",[h.elu,h.parseAlphaAttributes]],["Erf",[h.erf]],["Exp",[h.exp]],["Floor",[h.floor]],["Gemm",[u.gemm,u.parseGemmAttributes]],["GlobalAveragePool",[c.globalAveragePool,c.parseGlobalAveragePoolAttributes]],["GlobalMaxPool",[c.globalMaxPool,c.parseGlobalMaxPoolAttributes]],["LeakyRelu",[h.leakyRelu,h.parseAlphaAttributes]],["MatMul",[l.matMul]],["MaxPool",[c.maxPool,c.parseMaxPoolAttributes]],["Mul",[s.mul]],["Neg",[h.neg]],["Pow",[s.pow]],["Reciprocal",[h.reciprocal]],["Relu",[h.relu]],["Sigmoid",[h.sigmoid]],["Sin",[h.sin]],["Sinh",[h.sinh]],["Sqrt",[h.sqrt]],["Sub",[s.sub]],["Tan",[h.tan]],["Tanh",[h.tanh]],["ThresholdedRelu",[h.thresholdedRelu,h.parseAlphaAttributes]],["Transpose",[d.transpose,d.parseTransposeAttributes]]])},1427:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.biasActivationSnippet=t.activationFnSnippet=t.typeSnippet=void 0,t.typeSnippet=e=>{switch(e){case 1:return"f32";case 2:return"vec2<f32>";case 3:return"vec3<f32>";case 4:return"vec4<f32>";default:throw new Error(`${e}-component is not supported.`)}},t.activationFnSnippet=(e,t=!1,n=!1,r=3)=>"",t.biasActivationSnippet=(e,t)=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n ${t?"value = activation(value, coords);":""}\n `},9456:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createConv2DMatMulProgramInfo=void 0;const r=n(4955),i=n(6952),o=n(1163),s=n(1427),a=n(4085),u=n(158);t.createConv2DMatMulProgramInfo=(e,t,n,l,c,d,h,p,f)=>{const g="NHWC"===n.format,m=g?e[0].dims[3]:e[0].dims[1],b=l[0],y=g?l[2]:l[3],v=g?l[1]:l[2],w=g?l[3]:l[1],S=((m%4==0||m%3==0)&&g||y%4==0&&!g)&&w%4==0,_=g?w:y*v,T=g?y*v:w,x=S?[8,8,1]:[_<=4?4:16,_>4&&T<=4?4:16,1],E=S?[4,4,1]:[_<=4?1:2,_>4&&T<=4?1:2,1],C=[Math.ceil(_/x[0]/E[0]),Math.ceil(T/x[1]/E[1]),Math.ceil(b/x[2]/E[1])];(0,r.LOG_DEBUG)("verbose",(()=>`[conv2d_mm_webgpu] dispatch = ${C}`));const P=S?g&&m%4!=0?3:4:E[0],O=x[1]*E[1],A=x[0]*E[0],k=Math.max(x[0]*P,x[1]),I=c%O==0,M=d%A==0,R=h%k==0,D=S?[P,4,4]:[1,1,1],$=[`@group(0) @binding(0) var<storage, read> x: array<${S&&4===P?"vec4<f32>":"f32"}>;`,`@group(0) @binding(1) var<storage, read> w: array<${S?"vec4<f32>":"f32"}>;`];let L=`\n fn setOutputAtIndex(flatIndex : i32, value : ${S?"vec4<f32>":"f32"}) {\n result[flatIndex] = ${S?"vec4<f32>":"f32"}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${S?"vec4<f32>":"f32"}) {\n let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${S?"/ 4":""}, value);\n }`;return p&&($.push(`@group(0) @binding(2) var<storage, read> bias: array<${S?"vec4<f32>":"f32"}>;`),L+=`\n fn getBiasByOutputCoords(coords : vec4<i32>) -> ${S?"vec4<f32>":"f32"} {\n return bias[coords.${g?"w":"y"}${S?"/ 4":""}];\n }`),Object.assign(Object.assign({},t),{outputs:[{dims:l,dataType:e[0].dataType,gpuDataType:o.GpuDataType.default}],dispatchGroup:()=>({x:C[0],y:C[1],z:C[2]}),getShaderSource:()=>`\n ${a.utilFunctions}\n //struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,\n // outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,\n // dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${$.join("")}\n @group(0) @binding(${$.length}) var<storage, read_write> result: array<${S?"vec4<f32>":"f32"}>;\n //@group(0) @binding(${$.length+1}) var<uniform> uniforms: Uniforms;\n\n const xShape : vec4<i32> = vec4<i32>(${e[0].dims.join(",")});\n const wShape : vec4<i32> = vec4<i32>(${e[1].dims.join(",")});\n const outShape : vec4<i32> = vec4<i32>(${l.join(",")});\n const outShapeStrides : vec3<i32> = vec3<i32>(${i.ShapeUtil.computeStrides(l).slice(0,3).join(",")});\n const filterDims : vec2<i32> = vec2<i32>(${n.kernelShape[0]}, ${n.kernelShape[1]});\n const pad : vec2<i32> = vec2<i32>(${n.pads[0]}, ${n.pads[1]});\n const stride : vec2<i32> = vec2<i32>(${n.strides[0]}, ${n.strides[1]});\n const dilation : vec2<i32> = vec2<i32>(${n.dilations[0]}, ${n.dilations[1]});\n const dimAOuter : i32 = ${c};\n const dimBOuter : i32 = ${d};\n const dimInner : i32 = ${h};\n ${L}\n ${((e,t,n,r,i=!1,o,a=!1,u=4,l=4,c=4)=>{const d=e?"\n let coord = vec4<i32>(batch, xRow, xCol, xCh);\n ":"\n let coord = vec4<i32>(batch, xCh, xRow, xCol);\n ",h=e?"\n let coords = vec4<i32>(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4<i32>(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",p=e?"xShape[1]":"xShape[2]",f=e?"xShape[2]":"xShape[3]",g=e?"row":"col",m=e?"col":"row",b=`\n let inChannels = wShape[2];\n let outWidth = ${e?"outShape[2]":"outShape[3]"};\n let outRow = ${g} / outWidth;\n let outCol = ${g} % outWidth;\n\n let WRow = ${m} / (filterDims[1] * inChannels);\n let WCol = ${m} / inChannels % filterDims[1];\n let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0];\n let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1];\n let xCh = ${m} % inChannels;\n var resData = ${(0,s.typeSnippet)(u)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${p} && xCol >= 0 && xCol < ${f}) {\n ${d}\n let xIndex = getIndexFromCoords4D(coord, xShape);\n ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return"resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(u)}\n }\n return resData;`,y=e?t&&r?`\n let col = colIn * ${u};\n ${b}`:`\n let col = colIn * ${u};\n if (row < dimAOuter && col < dimInner) {\n ${b}\n }\n return ${(0,s.typeSnippet)(u)}(0.0);`:r&&n?`\n let col = colIn * ${u};\n ${b}`:`\n let col = colIn * ${u};\n if (row < dimInner && col < dimBOuter) {\n ${b}\n }\n return ${(0,s.typeSnippet)(u)}(0.0);`,v=`${(e=>{switch(e){case 1:return"return w[row * wShape[3] + colIn];";case 4:return"return w[row * wShape[3] / 4 + colIn];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(l)}`,w=(0,s.typeSnippet)(c),S=e?(0,s.typeSnippet)(u):(0,s.typeSnippet)(l),_=e?(0,s.typeSnippet)(l):(0,s.typeSnippet)(u);return`\n ${(0,s.activationFnSnippet)(o,a,4===c,4)}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${S} {\n ${e?y:v}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${_} {\n ${e?v:y}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${w}) {\n let col = colIn * ${c};\n if (row < dimAOuter && col < dimBOuter)\n {\n var value = valueIn;\n let outWidth = ${e?"outShape[2]":"outShape[3]"};\n ${h}\n ${(0,s.biasActivationSnippet)(i,o)}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`})(g,I,M,R,p,void 0,!1,D[0],D[1],D[2])}\n ${S?(0,u.makeMatMulPackedVec4Source)(E,x,!g,k):(0,u.makeMatMulPackedSource)(E,x,!g,k,!1,void 0,f)}`})}},4085:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utilFunctions=void 0,t.utilFunctions="\nfn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n outShapeStrides.x, outShapeStrides.y, outShapeStrides.z, 1));\n}\n"},158:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.makeMatMulPackedSource=t.makeMatMulPackedVec4Source=void 0,t.makeMatMulPackedVec4Source=(e,t,n=!1,r=32,i=!1,o=32,s=!1)=>{const a=t[1]*e[1],u=t[0]*e[0],l=n?a:r,c=n?r:a,d=l/t[0],h=r/t[1];if((!n||4!==d||4!==e[1])&&(n||3!==d&&4!==d)||l%t[0]!=0||r%t[1]!=0||4!==e[0])throw new Error(`If transposeA ${n} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${d} must be 3 or 4.\n tileAWidth ${l} must be divisible by workgroupSize[0]${t[0]}. tileInner ${r} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar<workgroup> mm_Asub : array<array<vec${d}<f32>, ${l/d}>, ${c}>;\nvar<workgroup> mm_Bsub : array<array<vec4<f32>, ${u/e[0]}>, ${r}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${d};\nconst tileInner = ${r};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n @builtin(global_invocation_id) globalId : vec3<u32>,\n @builtin(workgroup_id) workgroupId : vec3<u32>) {\n let localRow = i32(localId.y);\n let tileRow = ${s?"0":"localRow * rowPerThread"};\n let tileCol = i32(localId.x);\n\n let globalRow = ${s?"0":"i32(globalId.y) * rowPerThread"};\n let globalCol = i32(globalId.x);\n let batch = ${i?"0":"i32(globalId.z)"};\n let globalRowStart = i32(workgroupId.y) * ${a};\n\n let numTiles = ${i?`${Math.ceil(o/r)}`:"(dimInner - 1) / tileInner + 1"};\n var kStart = ${i?`i32(globalId.z) * ${o}`:"0"};\n\n var acc: array<vec4<f32>, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${h};\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${p=n,p?"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol);\n ":"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol);\n "}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol);\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${3===d?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${((e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`)(n,d)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`;var p};const n=e=>e?"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol);\n ":"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol);\n ";t.makeMatMulPackedSource=(e,t,r=!1,i=32,o=!1,s=32,a=!1)=>{const u=e[1]*t[1],l=e[0]*t[0],c=r?u:i,d=r?i:u;if(d%t[1]!=0||c%t[0]!=0||i%t[1]!=0)throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);const h=d/t[1],p=c/t[0],f=i/t[1],g=a?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${u};\n let globalColStart = i32(workgroupId.x) * ${l};\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) {\n ${n(r)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${l}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol);\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<f32, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${r?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${u};\n\nlet tileRowA = i32(localId.y) * ${h};\nlet tileColA = i32(localId.x) * ${p};\nlet tileRowB = i32(localId.y) * ${f};\n// Loop over shared dimension.\nfor (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${p}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${n(r)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol);\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<f32, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${(e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];")(r)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var<workgroup> mm_Asub : array<array<f32, ${c}>, ${d}>;\n var<workgroup> mm_Bsub : array<array<f32, ${l}>, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n @builtin(global_invocation_id) globalId : vec3<u32>,\n @builtin(workgroup_id) workgroupId : vec3<u32>) {\n let batch = ${o?"0":"i32(globalId.z)"};\n let numTiles = ${o?`${Math.ceil(s/i)}`:"(dimInner - 1) / tileInner + 1"};\n var kStart = ${o?`i32(globalId.z) * ${s}`:"0"};\n\n var acc : array<array<f32, colPerThread>, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${g}\n }\n`}},504:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sub=t.pow=t.mul=t.div=t.add=void 0;const r=n(6952),i=n(1163),o=n(2075),s=(e,t,n,s,a)=>{const u={name:t,inputTypes:[i.GpuDataType.default,i.GpuDataType.default],cacheHint:a};return Object.assign(Object.assign({},u),{get:()=>((e,t,n,s,a,u=t.dataType)=>{var l,c;const d=!r.ShapeUtil.areEqual(t.dims,n.dims);let h=t.dims,p=r.ShapeUtil.size(t.dims),f=!1;if(d){const e=r.BroadcastUtil.calcShape(t.dims,n.dims,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");h=e,p=r.ShapeUtil.size(h);let i=1;for(let e=0;e<h.length;e++){const r=null!==(l=t.dims[t.dims.length-e])&&void 0!==l?l:1;if(r!==(null!==(c=n.dims[n.dims.length-e])&&void 0!==c?c:1))break;i*=r}i%4==0&&(f=!0)}else f=!0;return Object.assign(Object.assign({},e),{getShaderSource:e=>((e,t,n,i,s,a,u,l,c="f32",d="f32",h="f32")=>{const p=r.ShapeUtil.size(i),f=Math.ceil(p/4);let g,m;"string"==typeof u?g=m=(e,t)=>`${u}((${e}),(${t}))`:"function"==typeof u?g=m=u:(g=u.scalar,m=u.vector);let b="";const y=(0,o.createIndicesHelper)("output",i);if(a){const e=e=>{const t=r.ShapeUtil.computeStrides(e),n=[];for(let r=e.length-1;r>=0;r--){const o=0===i.length?"0u":1===i.length?"(*outputIndices)":`(*outputIndices)[${r+i.length-e.length}]`;n.push(`${t[r]}u * (${o} % ${e[r]}u)`)}return n.length>0?n.join("+"):"0u"};b=`\n ${y.o2iImpl}\n\n fn calcOffsetA(outputIndices: ptr<function, ${y.iType}>) -> u32 {\n return ${e(t)};\n }\n\n fn calcOffsetB(outputIndices: ptr<function, ${y.iType}>) -> u32 {\n return ${e(n)};\n }\n `}let v;if(s)v=a?`\n ${y.indicesVariableDeclaration("outputIndices")}\n ${y.o2iCall("global_idx * 4u","outputIndices")}\n let offsetA = calcOffsetA(&outputIndices);\n let offsetB = calcOffsetB(&outputIndices);\n outputData[global_idx] = ${m("aData[offsetA / 4u]","bData[offsetB / 4u]")};`:`outputData[global_idx] = ${m("aData[global_idx]","bData[global_idx]")};`;else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");const e=e=>{const t=`aData[indexA${e}][componentA${e}]`,n=`bData[indexB${e}][componentB${e}]`;return`\n ${y.o2iCall(`global_idx * 4u + ${e}u`,"outputIndices")}\n let offsetA${e} = calcOffsetA(&outputIndices);\n let offsetB${e} = calcOffsetB(&outputIndices);\n let indexA${e} = offsetA${e} / 4u;\n let indexB${e} = offsetB${e} / 4u;\n let componentA${e} = offsetA${e} % 4u;\n let componentB${e} = offsetB${e} % 4u;\n outputData[global_idx][${e}] = ${g(t,n)};`};v=`\n ${y.indicesVariableDeclaration("outputIndices")}\n ${e(0)}\n ${e(1)}\n ${e(2)}\n ${e(3)}`}return`\n @group(0) @binding(0) var<storage, read> aData : array<vec4<${c}>>;\n @group(0) @binding(1) var<storage, read> bData : array<vec4<${d}>>;\n @group(0) @binding(2) var<storage, read_write> outputData : array<vec4<${h}>>;\n\n ${null!=l?l:""}\n ${b}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(f)}\n ${v}\n }`})(e,t.dims,n.dims,h,f,d,s,a),outputs:[{dims:h,dataType:u,gpuDataType:i.GpuDataType.default}],dispatchGroup:()=>({x:Math.ceil(p/64/(f?4:1))})})})(u,e[0],e[1],n,s)})};t.add=e=>{e.compute(s(e.inputs,"Add",((e,t)=>`${e}+${t}`)))},t.div=e=>{e.compute(s(e.inputs,"Div",((e,t)=>`${e}/${t}`)))},t.mul=e=>{e.compute(s(e.inputs,"Mul",((e,t)=>`${e}*${t}`)))},t.pow=e=>{e.compute(s(e.inputs,"Pow",{scalar:(e,t)=>`pow_f32(${e},${t})`,vector:(e,t)=>`pow_vf32(${e},${t})`},"\n fn pow_f32(a : f32, b : f32) -> f32 {\n if (b == 0.0) {\n return 1.0;\n } else if (a < 0.0 && b != floor(b)) {\n return pow(a, b); // NaN\n }\n return select(sign(a), 1.0, round(abs(b) % 2.0) != 1.0) * pow(abs(a), b);\n }\n fn pow_vf32(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {\n // TODO: implement vectorized pow\n return vec4<f32>(pow_f32(a.x, b.x), pow_f32(a.y, b.y), pow_f32(a.z, b.z), pow_f32(a.w, b.w));\n }\n "))},t.sub=e=>{e.compute(s(e.inputs,"Sub",((e,t)=>`${e}-${t}`)))}},2075:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createShaderHelper=t.createIndicesHelper=t.WORKGROUP_SIZE=void 0;const r=n(6952);t.WORKGROUP_SIZE=64,t.createIndicesHelper=(e,t)=>{const n=t.length<2?"u32":`array<u32, ${t.length}>`,i=r.ShapeUtil.computeStrides(t);let o="";for(let e=0;e<t.length-1;e++)o+=`\n let dim${e} = current / ${i[e]}u;\n let rest${e} = current % ${i[e]}u;\n (*indices)[${e}] = dim${e};\n current = rest${e};\n `;o+=`(*indices)[${t.length-1}] = current;`;const s=t.length<2?"":`\n fn ih_o2i_${e}(offset: u32, indices: ptr<function, ${n}>) {\n var current = offset;\n ${o}\n }`,a=[];if(0===t.length)a.push("0u");else if(t.length<2)a.push("(*indices)");else for(let e=t.length-1;e>=0;e--)a.push(`${i[e]}u * ((*indices)[${e}])`);return{o2iImpl:s,o2iCall:(n,r)=>t.length<2?`${r}=${n};`:`ih_o2i_${e}(${n}, &${r});`,i2oImpl:t.length<2?"":`\n fn ih_i2o_${e}(indices: ptr<function, ${n}>) -> u32 {\n return ${a.join("+")};\n }`,i2oExpression:(n,r)=>t.length<2?`(${r?"*":""}${n})`:`ih_i2o_${e}(${r?"":"&"}${n})`,indicesVariableDeclaration:(e,t)=>`var ${e}:${n}${t?`=${n}(${t.join(",")})`:""};`,iType:n}};class i{constructor(e){this.normalizedDispatchGroup=e}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=t.WORKGROUP_SIZE){const n="number"==typeof e?e:e[0],r="number"==typeof e?1:e[1],i="number"==typeof e?1:e[2],o=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${n}, ${r}, ${i})\n fn main(${o?"@builtin(global_invocation_id) global_id : vec3<u32>":"@builtin(local_invocation_index) local_index : u32,\n @builtin(workgroup_id) workgroup_id : vec3<u32>"}) {\n ${o?"let global_idx = global_id.x;":`let global_idx = (workgroup_id.z * ${this.normalizedDispatchGroup[0]*this.normalizedDispatchGroup[1]}u +\n workgroup_id.y * ${this.normalizedDispatchGroup[0]}u + workgroup_id.x) * ${n*r*i}u + local_index;`}\n `}}t.createShaderHelper=e=>new i(e)},9192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createGroupedConvProgramInfoLoader=void 0;const r=n(6952),i=n(1163),o=n(2075),s=n(9770),a=n(3997);t.createGroupedConvProgramInfoLoader=(e,t,n)=>{const u=(l=e.length>2,c=t.cacheKey,{name:"GroupedConv",inputTypes:l?[i.GpuDataType.default,i.GpuDataType.default,i.GpuDataType.default]:[i.GpuDataType.default,i.GpuDataType.default],cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=e.length>2,c=l?"value += b[output_channel];":"",d=e[0].dims,h=e[1].dims,p=h[0]/n.group,f="f32",{activationFunction:g,applyActivation:m}=(0,a.getActicationSnippet)(n),b=[`@group(0) @binding(0) var<storage, read> x : array<${f}>;`,`@group(0) @binding(1) var<storage, read> w : array<${f}>;`];l&&b.push(`@group(0) @binding(2) var<storage, read> b : array<${f}>;`);const y="NHWC"===n.format,v=(0,s.calculateOutputShape)(d,h,n.dilations,n.pads,n.strides,y),w=r.ShapeUtil.size(v),S=(0,o.createIndicesHelper)("output",v),_=(0,o.createIndicesHelper)("x",d),T=(0,o.createIndicesHelper)("w",h);return Object.assign(Object.assign({},t),{outputs:[{dims:u?u(v):v,dataType:e[0].dataType,gpuDataType:i.GpuDataType.default}],getShaderSource:e=>`\n const strides: vec2<u32> = vec2(${n.strides[0]}u, ${n.strides[1]}u);\n const pads: vec2<u32> = vec2(${n.pads[0]}u, ${n.pads[1]}u);\n\n ${b.join("\n")}\n @group(0) @binding(${b.length}) var<storage, read_write> output : array<${f}>;\n\n ${g}\n ${S.o2iImpl}\n ${_.i2oImpl}\n ${T.i2oImpl}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(w)}\n\n ${S.indicesVariableDeclaration("outputIndices")}\n ${S.o2iCall("global_idx","outputIndices")}\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${y?3:1}];\n let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${y?1:2}], outputIndices[${y?2:3}]) * strides - pads;\n let group_id: u32 = output_channel / ${p}u;\n\n var value: ${f} = ${f}(0);\n for (var wInChannel: u32 = 0u; wInChannel < ${h[1]}u; wInChannel++) {\n let input_channel = group_id * ${h[1]}u + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < ${h[2]}u; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * ${n.dilations[0]}u;\n\n if (xHeight < 0u || xHeight >= ${d[y?1:2]}u) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < ${h[3]}u; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * ${n.dilations[1]}u;\n if (xWidth < 0u || xWidth >= ${d[y?2:3]}u) {\n continue;\n }\n\n ${_.indicesVariableDeclaration("xIndices",y?["batch","xHeight","xWidth","input_channel"]:["batch","input_channel","xHeight","xWidth"])}\n let xVal = x[${_.i2oExpression("xIndices")}];\n ${T.indicesVariableDeclaration("wIndices",["output_channel","wInChannel","wHeight","wWidth"])}\n let wVal = w[${T.i2oExpression("wIndices")}];\n value += xVal*wVal;\n }\n }\n }\n ${c}\n ${m}\n output[global_idx] = value;\n }`,dispatchGroup:()=>({x:Math.ceil(w/64)})})})(e,u,t,n)})}},9770:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.conv=t.parseConvAttributes=t.calculateOutputShape=void 0;const r=n(6952),i=n(387),o=n(9192),s=n(3822),a=n(3997),u=n(2625);t.calculateOutputShape=(e,t,n,r,i,o)=>{const s=e[0],a=e.slice(o?1:2,o?3:4),u=a.length,l=t[0],c=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),d=a.map(((e,t)=>e+r[t]+r[t+u])).map(((e,t)=>Math.floor((e-c[t]+i[t])/i[t])));return d.splice(0,0,s),d.splice(o?3:1,0,l),d};const l=(0,i.createAttributeWithCacheKey)({perm:[2,3,1,0]}),c=(e,t)=>{const n=e.kernelShape.slice();for(let e=2;e<t[1].dims.length;++e)0===n[e-2]&&(n[e-2]=t[1].dims[e]);const i=e.pads.slice();r.PoolConvUtil.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,i,"NHWC"===e.format,e.autoPad);const o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:i,cacheKey:e.cacheKey}),o};t.parseConvAttributes=e=>{const t=(0,a.parseInternalActivationAttributes)(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,s=e.group,u=e.kernel_shape,l=e.pads,c=e.strides,d=e.w_is_const();return(0,i.createAttributeWithCacheKey)(Object.assign({autoPad:r,format:n,dilations:o,group:s,kernelShape:u,pads:l,strides:c,wIsConst:d},t))},t.conv=(e,n)=>{((e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");const n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(1!==e[0].dataType||1!==e[1].dataType)throw new Error("Conv input(X,W) should be float tensor");if(3===e.length&&1!==e[2].dataType)throw new Error("Conv input(bias) should be float tensor")})(e.inputs,n),3===e.inputs[0].dims.length?((e,t)=>{const n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);const i=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),a=[1].concat(t.dilations),u=[1].concat(t.kernelShape),l=c(Object.assign(Object.assign({},t),{pads:i,strides:s,dilations:a,kernelShape:u}),r);e.compute((0,o.createGroupedConvProgramInfoLoader)(r,l,(e=>n?[e[0],e[2],e[3]]:[])))})(e,n):((e,n,r)=>{var i;const a=c(r,n),d=3===n.length,h="NHWC"===r.format,p=n[0].dims[h?1:2],f=n[0].dims[h?2:3],g=n[0].dims[h?3:1],m=n[1].dims[2],b=n[1].dims[3],y=(0,t.calculateOutputShape)(n[0].dims,n[1].dims,r.dilations,a.pads,r.strides,h),v=y[h?1:2],w=y[h?2:3],S=y[h?3:1];if(h&&m===p&&b===f&&"VALID"===r.autoPad||1===m&&1===b&&1===r.dilations[0]&&1===r.dilations[1]&&1===r.strides[0]&&1===r.strides[1]&&("SAME_UPPER"===r.autoPad||"SAME_LOWER"===r.autoPad||"VALID"===r.autoPad))return void e.compute((0,o.createGroupedConvProgramInfoLoader)(n,a));if(!h||1!==r.group)return void e.compute((0,o.createGroupedConvProgramInfoLoader)(n,a));const _=h?v*w:S,T=h?S:v*w,x=m*b*g,E=null!==(i=e.customData.wT)&&void 0!==i?i:e.compute(Object.assign(Object.assign({},u.transposeProgramMetadata),{cacheHint:l.cacheKey,get:()=>(0,u.createTransposeProgramInfo)(n[1],l.perm)}),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.customData.wT&&(e.customData.wT=E);const C=[n[0],E];d&&(h||1!==n[2].dims.length?C.push(n[2]):C.push(n[2].reshape([n[2].dims[0],1,1]))),e.compute((0,s.createConv2DMatMulProgramInfoLoader)(C,a,y,_,T,x,d,!0),{inputs:C})})(e,e.inputs,n)}},3822:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createConv2DMatMulProgramInfoLoader=void 0;const r=n(1163),i=n(9456);t.createConv2DMatMulProgramInfoLoader=(e,t,n,o,s,a,u,l)=>{const c=((e,t)=>({name:"Conv2DMatMul",inputTypes:e?[r.GpuDataType.default,r.GpuDataType.default,r.GpuDataType.default]:[r.GpuDataType.default,r.GpuDataType.default],cacheHint:t}))(u,t.cacheKey);return Object.assign(Object.assign({},c),{get:()=>(0,i.createConv2DMatMulProgramInfo)(e,c,t,n,o,s,a,u,l)})}},3997:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseInternalActivationAttributes=t.getActicationSnippet=void 0;const r=n(6952);t.getActicationSnippet=e=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:"value = max(value, 0.0);"};case"Sigmoid":return{activationFunction:"",applyActivation:"value = (1.0 / (1.0 + exp(-value)));"};case"Clip":return{activationFunction:`const clip_min_=f32(${e.clipMin});const clip_max_=f32(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},t.parseInternalActivationAttributes=e=>{const t=(null==e?void 0:e.activation)||"";if("Clip"===t){const[n,i]=(null==e?void 0:e.activation_params)||[r.MIN_CLIP,r.MAX_CLIP];return{activation:t,clipMax:i,clipMin:n,activationCacheKey:`${t}:${n},${i}`}}return{activation:t,activationCacheKey:t}}},4271:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseGemmAttributes=t.gemm=void 0;const r=n(6952),i=n(387),o=n(1163);t.gemm=(e,t)=>{(e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(1!==e[0].dataType||1!==e[1].dataType||3===e.length&&1!==e[2].dataType)throw new Error("Invalid input type.");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")})(e.inputs),e.compute(((e,t)=>{const n={name:"Gemm",inputTypes:3===e.length?[o.GpuDataType.default,o.GpuDataType.default,o.GpuDataType.default]:[o.GpuDataType.default,o.GpuDataType.default],cacheHint:t.cacheKey};return Object.assign(Object.assign({},n),{get:()=>((e,t,n)=>{const i=t[0].dims.slice(),s=t[1].dims.slice(),[a,u,l]=r.GemmUtil.getShapeOfGemmResult(i,n.transA,s,n.transB,3===t.length?t[2].dims:void 0),c=[a,u];if(!c)throw new Error("Can't use gemm on the given tensors");const d=r.ShapeUtil.size(c);let h="";n.transA&&n.transB?h="value += a[k * M + m] * b[n * K + k];":n.transA&&!n.transB?h="value += a[k * M + m] * b[k * N + n];":!n.transA&&n.transB?h="value += a[m * K + k] * b[n * K + k];":n.transA||n.transB||(h="value += a[m * K + k] * b[k * N + n];");const p="f32",f=1===n.alpha?"":"value *= alpha;",g=3===t.length?`value += beta * c[${((e,t,n)=>{if(0===n.length)return"0u";const r=1===n.length&&1!==e||2===n.length&&n[0]!==e,i=n[n.length-1]!==t;let o="0u";return r||(o+=`+ m * ${n[n.length-1]}u`),i||(o+="+n"),o})(a,u,t[2].dims)}];`:"",m=[`@group(0) @binding(0) var<storage, read> a : array<${p}>;`,`@group(0) @binding(1) var<storage, read> b : array<${p}>;`];return 3===t.length&&m.push(`@group(0) @binding(2) var<storage, read> c : array<${p}>;`),Object.assign(Object.assign({},e),{outputs:[{dims:c,dataType:t[0].dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:e=>`\n const M: u32 = ${a}u;\n const N: u32 = ${u}u;\n const K: u32 = ${l}u;\n const alpha = ${p}(${n.alpha});\n const beta = ${p}(${n.beta});\n\n ${m.join("\n")}\n @group(0) @binding(${t.length}) var<storage, read_write> output : array<${p}>;\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(d)}\n\n let m = global_id.x / N;\n let n = global_id.x % N;\n\n var value = ${p}(0);\n for (var k: u32 = 0u; k<${l}u; k++) {\n ${h}\n }\n\n ${f}\n ${g}\n output[global_id.x] = value;\n\n }`,dispatchGroup:()=>({x:Math.ceil(d/64)})})})(n,e,t)})})(e.inputs,t))},t.parseGemmAttributes=e=>(0,i.createAttributeWithCacheKey)(e)},1522:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matMul=t.createMatmulProgramInfoLoader=void 0;const r=n(6952),i=n(1163),o=n(3997);t.createMatmulProgramInfoLoader=(e,t)=>{const n=(s=e.length>2,a=t.activationCacheKey,{name:"MatMul",inputTypes:s?[i.GpuDataType.default,i.GpuDataType.default,i.GpuDataType.default]:[i.GpuDataType.default,i.GpuDataType.default],cacheHint:a});var s,a;return Object.assign(Object.assign({},n),{get:()=>((e,t,n)=>{const s=t[0].dims,a=t[1].dims,u=r.BroadcastUtil.calcShape(s,a,!0);if(!u)throw new Error("Can't use matmul on the given tensors");const l=r.ShapeUtil.size(u),c="f32",{activationFunction:d,applyActivation:h}=(0,o.getActicationSnippet)(n),p=u[u.length-2],f=s[s.length-1],g=u[u.length-1];return Object.assign(Object.assign({},e),{outputs:[{dims:u,dataType:t[0].dataType,gpuDataType:i.GpuDataType.default}],getShaderSource:e=>`\n const M: u32 = ${p}u;\n const N: u32 = ${g}u;\n const K: u32 = ${f}u;\n\n @group(0) @binding(0) var<storage, read> a : array<${c}>;\n @group(0) @binding(1) var<storage, read> b : array<${c}>;\n @group(0) @binding(2) var<storage, read_write> output : array<${c}>;\n\n ${d}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(l)}\n\n let stack = global_idx / (M * N);\n let mn = global_idx % (M * N);\n let n = global_idx % N;\n let m = mn / N;\n\n let offsetA = stack * (M * K);\n let offsetB = stack * (K * N);\n\n var value = ${c}(0);\n for (var k: u32 = 0u; k<${f}u; k++) {\n value += a[offsetA + m * K + k] * b[offsetB + k * N + n];\n }\n ${h}\n output[global_idx] = value;\n }`,dispatchGroup:()=>({x:Math.ceil(l/64)})})})(n,e,t)})},t.matMul=e=>{(e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.");if(1!==e[0].dataType||1!==e[1].dataType)throw new Error("inputs should be float type")})(e.inputs),e.compute((0,t.createMatmulProgramInfoLoader)(e.inputs,{activation:"",activationCacheKey:""}))}},5262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.globalMaxPool=t.parseGlobalMaxPoolAttributes=t.parseMaxPoolAttributes=t.maxPool=t.globalAveragePool=t.parseGlobalAveragePoolAttributes=t.averagePool=t.parseAveragePoolAttributes=void 0;const r=n(6952),i=n(387),o=n(1163),s=n(2075),a=e=>{if(!e||1!==e.length)throw new Error("Pool ops requires 1 input.");if(4!==e[0].dims.length)throw new Error("Pool ops supports 2-D inputs only for now.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},u=(e,t,n)=>{const i="NHWC"===t.format,o=i?[e[0].dims[0],e[0].dims[3],e[0].dims[1],e[0].dims[2]]:e[0].dims.slice(),s=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),u=t.strides.slice(),l=s?t.dilations.slice():[],c=t.pads.slice();r.PoolConvUtil.adjustPoolAttributes(n,o,a,u,l,c);const d=r.PoolConvUtil.computePoolOutputShape(n,o,u,l,a,c,t.autoPad),h=Object.assign({},t);return s?Object.assign(h,{kernelShape:a,strides:u,pads:c,dilations:l,cacheKey:t.cacheKey}):Object.assign(h,{kernelShape:a,strides:u,pads:c,cacheKey:t.cacheKey}),[h,i?[d[0],d[2],d[3],d[1]]:d]},l=(e,t,n,i,o,a,u,l)=>{const c="NHWC"===i.format,d=t.length,h=r.ShapeUtil.size(n),p=(0,s.createIndicesHelper)("output",n),f=(0,s.createIndicesHelper)("x",t);if(i.kernelShape.length<=2){const n=i.kernelShape[i.kernelShape.length-1],r=i.strides[i.strides.length-1],s=i.pads[i.pads.length/2-1],g=d-(c?2:1);let m="",b="",y="";if(m=s+i.pads[i.pads.length-1]!==0?`\n for (var i: u32 = 0u; i < ${n}u; i++) {\n xIndices[${g}] = indices[${g}] * ${r} - ${s} + i;\n if (xIndices[${g}] < 0 || xIndices[${g}] >= ${t[g]}) {\n pad++;\n continue;\n }\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n }`:`\n for (var i: u32 = 0u; i < ${n}u; i++) {\n xIndices[${g}] = indices[${g}] * ${r} - ${s} + i;\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n }`,2===i.kernelShape.length){const e=i.kernelShape[i.kernelShape.length-2],r=i.strides[i.strides.length-2],o=i.pads[i.pads.length/2-2],s=i.pads[i.pads.length-2],a=d-(c?3:2),u=t[a];b=o+s!==0?`\n for (var j: u32 = 0u; j < ${e}u; j++) {\n xIndices[${a}] = indices[${a}] * ${r} - ${o} + j;\n if (xIndices[${a}] < 0 || xIndices[${a}] >= ${u}) {\n pad+= ${n};\n continue;\n }\n `:`\n for (var j: u32 = 0u; j < ${e}u; j++) {\n xIndices[${a}] = indices[${a}] * ${r} - ${o} + j;\n `,y="\n }\n "}return`\n @group(0) @binding(0) var<storage, read> x : array<${u}>;\n @group(0) @binding(1) var<storage, read_write> output : array<${u}>;\n\n ${p.o2iImpl}\n ${f.i2oImpl}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n ${p.indicesVariableDeclaration("indices")}\n ${p.o2iCall("global_idx","indices")}\n ${p.indicesVariableDeclaration("xIndices")}\n ${p.o2iCall("global_idx","xIndices")}\n\n var value: ${u} = ${u}(${l});\n var pad = 0;\n ${b}\n ${m}\n ${y}\n ${a}\n\n output[global_idx] = value;\n }`}{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");const n=r.ShapeUtil.size(i.kernelShape),s=r.ShapeUtil.computeStrides(i.kernelShape),g=s.length,m=i.pads.length;let b="";return b=i.pads.reduce(((e,t)=>e+t))?`\n if (xIndices[j] >= inputDims[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n }`:`\n }\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n `,`\n @group(0) @binding(0) var<storage, read> x : array<${u}>;\n @group(0) @binding(1) var<storage, read_write> output : array<${u}>;\n\n ${p.o2iImpl}\n ${f.i2oImpl}\n\n const pads = array<u32, ${m}>(${i.pads.map((e=>`${e}u`)).join(",")});\n const inputDims = array<u32, ${d}>(${t.map((e=>`${e}u`)).join(",")});\n const kernelStrides = array<u32, ${g}>(${s.map((e=>`${e}u`)).join(",")});\n const strides = array<u32, ${g}>(${i.strides.map((e=>`${e}u`)).join(",")});\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n ${p.indicesVariableDeclaration("indices")}\n ${p.o2iCall("global_idx","indices")}\n ${p.indicesVariableDeclaration("xIndices")}\n ${p.o2iCall("global_idx","xIndices")}\n\n var offsets: array<u32, ${g}>;\n\n var value = ${u}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < ${n}u; i++) {\n var offset = i;\n for (var j = 0u; j < ${g-1}u; j++) {\n offsets[j] = offset / kernelStrides[j];\n offset -= offsets[j] * kernelStrides[j];\n }\n offsets[${g-1}] = offset;\n\n isPad = false;\n for (var j = ${d-g}u; j < ${d}u; j++) {\n xIndices[j] = indices[j] * strides[j - ${d-g}u]\n + offsets[j - ${d-g}u] - pads[j - 2u];\n ${b}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},c=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),d=(e,t,n,i)=>{const[s,a]=u(e,i,n),c=r.ShapeUtil.size(s.kernelShape),d="f32";let h="";return s.countIncludePad?h+=`value /= ${d}(${c});`:h+=`value /= ${d}(${c} - pad);`,Object.assign(Object.assign({},t),{outputs:[{dims:a,dataType:e[0].dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:t=>l(t,e[0].dims,a,s,"value += x_val;",h,d,"0.0"),dispatchGroup:()=>({x:Math.ceil(r.ShapeUtil.size(a)/64)})})};t.parseAveragePoolAttributes=e=>{const t=0!==e.count_include_pad,n=c(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,i.createAttributeWithCacheKey)(Object.assign({countIncludePad:t},n))},t.averagePool=(e,t)=>{a(e.inputs);const n={name:"AveragePool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>d(e.inputs,n,!1,t)}))};const h={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""};t.parseGlobalAveragePoolAttributes=e=>{const t=e.format;return Object.assign(Object.assign({format:t},h),{cacheKey:t})},t.globalAveragePool=(e,t)=>{a(e.inputs);const n={name:"GlobalAveragePool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>d(e.inputs,n,!0,t)}))};const p=(e,t,n,i)=>{const[s,a]=u(e,i,n);return Object.assign(Object.assign({},t),{outputs:[{dims:a,dataType:e[0].dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:t=>l(t,e[0].dims,a,s,"\n value = max(x_val, value);\n ","","f32","-1e5"),dispatchGroup:()=>({x:Math.ceil(r.ShapeUtil.size(a)/64)})})};t.maxPool=(e,t)=>{a(e.inputs);const n={name:"MaxPool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>p(e.inputs,n,!1,t)}))},t.parseMaxPoolAttributes=e=>{const t=e.storage_order,n=e.dilations,r=c(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==r.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,i.createAttributeWithCacheKey)(Object.assign({storageOrder:t,dilations:n},r))},t.parseGlobalMaxPoolAttributes=e=>{const t=e.format;return Object.assign(Object.assign({format:t},h),{cacheKey:t})},t.globalMaxPool=(e,t)=>{a(e.inputs);const n={name:"GlobalMaxPool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>p(e.inputs,n,!0,t)}))}},2625:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseTransposeAttributes=t.transpose=t.createTransposeProgramInfo=t.transposeProgramMetadata=void 0;const r=n(6952),i=n(387),o=n(1163),s=n(2075);t.transposeProgramMetadata={name:"Transpose",inputTypes:[o.GpuDataType.default]};const a=(e,t)=>t&&t.length!==e.length?[...e.keys()].reverse():t;t.createTransposeProgramInfo=(e,n)=>{const i=e.dims,u=a(i,n),l=((e,t)=>r.ShapeUtil.sortBasedOnPerm(e,a(e,t)))(i,u),c=i.length,d=r.ShapeUtil.size(l),h=(0,s.createIndicesHelper)("output",l),p=(0,s.createIndicesHelper)("a",i);return Object.assign(Object.assign({},t.transposeProgramMetadata),{outputs:[{dims:l,dataType:e.dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:e=>`\n @group(0) @binding(0) var<storage, read> a : array<f32>;\n @group(0) @binding(1) var<storage, read_write> output : array<f32>;\n\n ${((e,t)=>{const n=[];n.push(`fn perm(a: ptr<function, array<u32, ${t}>>, i: ptr<function, array<u32, ${t}>>) {`);for(let r=0;r<t;++r)n.push(`\t(*a)[${e[r]}]=(*i)[${r}];`);return n.push("\t}"),n.join("\n")})(u,c)}\n ${h.o2iImpl}\n ${p.i2oImpl}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(d)}\n\n ${h.indicesVariableDeclaration("indices")}\n ${h.o2iCall("global_idx","indices")}\n ${p.indicesVariableDeclaration("aIndices")}\n perm(&aIndices, &indices);\n\n output[global_idx] = a[${p.i2oExpression("aIndices")}];\n }`,dispatchGroup:()=>({x:Math.ceil(d/64)})})},t.transpose=(e,n)=>{(e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if(1!==e[0].dataType)throw new Error("input should be float tensor")})(e.inputs),e.compute(Object.assign(Object.assign({},t.transposeProgramMetadata),{cacheHint:n.cacheKey,get:()=>(0,t.createTransposeProgramInfo)(e.inputs[0],n.perm)}))},t.parseTransposeAttributes=e=>(0,i.createAttributeWithCacheKey)({perm:e.perm})},9302:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thresholdedRelu=t.tanh=t.tan=t.sqrt=t.sinh=t.sin=t.sigmoid=t.relu=t.reciprocal=t.neg=t.leakyRelu=t.floor=t.exp=t.erf=t.elu=t.parseAlphaAttributes=t.cosh=t.cos=t.ceil=t.clip=t.clipV10=t.atanh=t.atan=t.asinh=t.asin=t.acosh=t.acos=t.abs=void 0;const r=n(6952),i=n(387),o=n(1163),s=(e,t,n,i,s)=>{const a={name:t,inputTypes:[o.GpuDataType.default],cacheHint:s};return Object.assign(Object.assign({},a),{get:()=>((e,t,n,i)=>Object.assign(Object.assign({},e),{getShaderSource:e=>((e,t,n,r)=>{const i=Math.ceil(t/4);let o="";return o="string"==typeof n?`${n}(a)`:n("a"),`\n @group(0) @binding(0) var<storage, read> inputData : array<vec4<f32>>;\n @group(0) @binding(1) var<storage, read_write> outputData : array<vec4<f32>>;\n\n ${null!=r?r:""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n\n let a = inputData[global_idx];\n outputData[global_idx] = ${o};\n }`})(e,r.ShapeUtil.size(t.dims),n,i),outputs:[{dims:t.dims,dataType:t.dataType,gpuDataType:o.GpuDataType.default}],dispatchGroup:e=>({x:Math.ceil(r.ShapeUtil.size(e[0].dims)/64/4)})}))(a,e,n,i)})};t.abs=e=>{e.compute(s(e.inputs[0],"Abs","abs"))},t.acos=e=>{e.compute(s(e.inputs[0],"Acos","acos"))},t.acosh=e=>{e.compute(s(e.inputs[0],"Acosh","acosh"))},t.asin=e=>{e.compute(s(e.inputs[0],"Asin","asin"))},t.asinh=e=>{e.compute(s(e.inputs[0],"Asinh","asinh"))},t.atan=e=>{e.compute(s(e.inputs[0],"Atan","atan"))},t.atanh=e=>{e.compute(s(e.inputs[0],"Atanh","atanh"))},t.clipV10=(e,t)=>{e.compute(s(e.inputs[0],"Clip",(e=>`clamp(${e}, clip_min_, clip_max_)`),`\n const clip_min_: vec4<f32> = vec4(f32(${t.min}));\n const clip_max_: vec4<f32> = vec4(f32(${t.max}));\n`,t.cacheKey),{inputs:[0]})},t.clip=e=>{const n=(e=>{const t=e.length>=2?e[1].getFloat32Array()[0]:r.MIN_CLIP,n=e.length>=3?e[2].getFloat32Array()[0]:r.MAX_CLIP;return(0,i.createAttributeWithCacheKey)({min:t,max:n})})(e.inputs);(0,t.clipV10)(e,n)},t.ceil=e=>{e.compute(s(e.inputs[0],"Ceil","ceil"))},t.cos=e=>{e.compute(s(e.inputs[0],"Cos","cos"))},t.cosh=e=>{e.compute(s(e.inputs[0],"Cosh","cosh"))},t.parseAlphaAttributes=e=>(0,i.createAttributeWithCacheKey)(e),t.elu=(e,t)=>{e.compute(s(e.inputs[0],"Elu",(e=>`elu_vf32(${e})`),`\n const elu_alpha_: f32 = f32(${t.alpha});\n\n fn elu_f32(a: f32) -> f32 {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<f32>) -> vec4<f32> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},t.erf=e=>{e.compute(s(e.inputs[0],"Erf",(e=>`erf_vf32(${e})`),"\n const r0: f32 = 0.3275911;\n const r1: f32 = 0.254829592;\n const r2: f32 = -0.284496736;\n const r3: f32 = 1.421413741;\n const r4: f32 = -1.453152027;\n const r5: f32 = 1.061405429;\n\n fn erf_vf32(v: vec4<f32>) -> vec4<f32> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n }"))},t.exp=e=>{e.compute(s(e.inputs[0],"Exp","exp"))},t.floor=e=>{e.compute(s(e.inputs[0],"Floor","floor"))},t.leakyRelu=(e,t)=>{e.compute(s(e.inputs[0],"LeakyRelu",(e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<f32>(0.0))`),`const leaky_relu_alpha_: f32 = f32(${t.alpha});`,t.cacheKey))},t.neg=e=>{e.compute(s(e.inputs[0],"Neg",(e=>`-${e}`)))},t.reciprocal=e=>{e.compute(s(e.inputs[0],"Reciprocal",(e=>`1.0/${e}`)))},t.relu=e=>{e.compute(s(e.inputs[0],"Relu",(e=>`select(vec4<f32>(0.0), ${e}, ${e} > vec4<f32>(0.0))`)))},t.sigmoid=e=>{e.compute(s(e.inputs[0],"Sigmoid",(e=>`(1.0 / (1.0 + exp(-${e})))`)))},t.sin=e=>{e.compute(s(e.inputs[0],"Sin","sin"))},t.sinh=e=>{e.compute(s(e.inputs[0],"Sinh","sinh"))},t.sqrt=e=>{e.compute(s(e.inputs[0],"Sqrt","sqrt"))},t.tan=e=>{e.compute(s(e.inputs[0],"Tan","tan"))},t.tanh=e=>{e.compute(s(e.inputs[0],"Tanh","tanh"))},t.thresholdedRelu=(e,t)=>(e.compute(s(e.inputs[0],"ThresholdedRelu",(e=>`select(vec4<f32>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`),`const thresholded_relu_alpha_: vec4<f32> = vec4<f32>(${t.alpha});`,t.cacheKey)),0)},8305:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgramManager=void 0;const r=n(4955),i=n(2075);t.ProgramManager=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r){const i=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.profilingEnabled&&o.writeTimestamp(this.backend.profilingQuerySet,0),o.setPipeline(e.computePipeline);const s=[];for(const e of t)s.push({binding:s.length,resource:{buffer:e.buffer}});for(const e of n)s.push({binding:s.length,resource:{buffer:e.buffer}});const a=i.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:s});if(o.setBindGroup(0,a),o.dispatchWorkgroups(...r),this.backend.pendingDispatchNumber++,this.backend.profilingEnabled){o.writeTimestamp(this.backend.profilingQuerySet,1);const e=this.backend.gpuDataManager.create(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),t=this.backend.gpuDataManager.create(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.backend.endComputePass(),this.backend.getCommandEncoder().resolveQuerySet(this.backend.profilingQuerySet,0,2,e.buffer,0),this.backend.getCommandEncoder().copyBufferToBuffer(e.buffer,0,t.buffer,0,16),this.backend.flush();const n=this.backend.currentKernelId,r=this.backend.kernels.get(n)[0];t.buffer.mapAsync(GPUMapMode.READ).then((()=>{const i=new BigUint64Array(t.buffer.getMappedRange()),o=i[0],s=i[1];t.buffer.unmap(),void 0===this.backend.profilingTimeBase&&(this.backend.profilingTimeBase=o);const a=Number(o-this.backend.profilingTimeBase),u=Number(s-this.backend.profilingTimeBase);if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u))throw new RangeError("incorrect timestamp range");this.backend.gpuDataManager.release(e.id),this.backend.gpuDataManager.release(t.id),console.log(`[profiling] kernel "${n}|${r}" execution time: ${u-a} ns`)}))}this.backend.pendingDispatchNumber>=16&&this.backend.flush()}dispose(){}build(e,t){const n=this.backend.device,o=e.getShaderSource((0,i.createShaderHelper)(t)),s=n.createShaderModule({code:o});return(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] shader code: ${o}`)),{programInfo:e,computePipeline:n.createComputePipeline({compute:{module:s,entryPoint:"main"},layout:"auto"})}}normalizeDispatchGroupSize(e){const t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,r="number"==typeof e?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];const o=t*n*r;let s=Math.ceil(Math.sqrt(o));if(s>i){if(s=Math.ceil(Math.cbrt(o)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}return[s,s,1]}}},1163:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.GpuDataType=void 0,(n=t.GpuDataType||(t.GpuDataType={}))[n.default=0]="default",n[n.upload=1]="upload",n[n.profile=2]="profile"},3899:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.iterateExtraOptions=void 0,t.iterateExtraOptions=(e,n,r,i)=>{if("object"==typeof e&&null!==e){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach((([e,o])=>{const s=n?n+e:e;if("object"==typeof o)(0,t.iterateExtraOptions)(o,s+".",r,i);else if("string"==typeof o||"number"==typeof o)i(s,o.toString());else{if("boolean"!=typeof o)throw new Error("Can't handle extra config type: "+typeof o);i(s,o?"1":"0")}}))}},9544:function(e,t,n){"use strict";var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=t.initWasm=void 0;const a=n(8453),u=n(7675),l=s(n(1259)),c=n(263),d=()=>!!a.env.wasm.proxy&&"undefined"!=typeof document;let h,p,f,g=!1,m=!1,b=!1;const y=[],v=[],w=[],S=[],_=[],T=[],x=()=>{if(g||!m||b||!h)throw new Error("worker not ready")},E=e=>{switch(e.data.type){case"init-wasm":g=!1,e.data.err?(b=!0,p[1](e.data.err)):(m=!0,p[0]());break;case"init-ort":e.data.err?f[1](e.data.err):f[0]();break;case"create_allocate":e.data.err?y.shift()[1](e.data.err):y.shift()[0](e.data.out);break;case"create_finalize":e.data.err?v.shift()[1](e.data.err):v.shift()[0](e.data.out);break;case"create":e.data.err?w.shift()[1](e.data.err):w.shift()[0](e.data.out);break;case"release":e.data.err?S.shift()[1](e.data.err):S.shift()[0]();break;case"run":e.data.err?_.shift()[1](e.data.err):_.shift()[0](e.data.out);break;case"end-profiling":e.data.err?T.shift()[1](e.data.err):T.shift()[0]()}},C="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;t.initWasm=async()=>{if(d()){if(m)return;if(g)throw new Error("multiple calls to 'initWasm()' detected.");if(b)throw new Error("previous call to 'initWasm()' failed.");return g=!0,void 0===a.env.wasm.wasmPaths&&C&&0!==C.indexOf("blob:")&&(a.env.wasm.wasmPaths=C.substr(0,+C.lastIndexOf("/")+1)),new Promise(((e,t)=>{null==h||h.terminate(),h=n(8050).Z(),h.onmessage=E,p=[e,t];const r={type:"init-wasm",in:a.env.wasm};h.postMessage(r)}))}return(0,c.initializeWebAssembly)(a.env.wasm)},t.initOrt=async(e,t)=>{if(d())return x(),new Promise(((n,r)=>{f=[n,r];const i={type:"init-ort",in:{numThreads:e,loggingLevel:t}};h.postMessage(i)}));l.initOrt(e,t),await(0,u.init)((0,c.getInstance)())},t.createSessionAllocate=async e=>d()?(x(),new Promise(((t,n)=>{y.push([t,n]);const r={type:"create_allocate",in:{model:e}};h.postMessage(r,[e.buffer])}))):l.createSessionAllocate(e),t.createSessionFinalize=async(e,t)=>d()?(x(),new Promise(((n,r)=>{v.push([n,r]);const i={type:"create_finalize",in:{modeldata:e,options:t}};h.postMessage(i)}))):l.createSessionFinalize(e,t),t.createSession=async(e,t)=>d()?(x(),new Promise(((n,r)=>{w.push([n,r]);const i={type:"create",in:{model:e,options:t}};h.postMessage(i,[e.buffer])}))):l.createSession(e,t),t.releaseSession=async e=>{if(d())return x(),new Promise(((t,n)=>{S.push([t,n]);const r={type:"release",in:e};h.postMessage(r)}));l.releaseSession(e)},t.run=async(e,t,n,r,i)=>d()?(x(),new Promise(((o,s)=>{_.push([o,s]);const a={type:"run",in:{sessionId:e,inputIndices:t,inputs:n,outputIndices:r,options:i}};h.postMessage(a,l.extractTransferableBuffers(n))}))):l.run(e,t,n,r,i),t.endProfiling=async e=>{if(d())return x(),new Promise(((t,n)=>{T.push([t,n]);const r={type:"end-profiling",in:e};h.postMessage(r)}));l.endProfiling(e)}},7918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setRunOptions=void 0;const r=n(3899),i=n(9444),o=n(263);t.setRunOptions=e=>{const t=(0,o.getInstance)();let n=0;const s=[],a=e||{};try{if(void 0===(null==e?void 0:e.logSeverityLevel))a.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===(null==e?void 0:e.logVerbosityLevel))a.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===(null==e?void 0:e.terminate)&&(a.terminate=!1);let o=0;if(void 0!==(null==e?void 0:e.tag)&&(o=(0,i.allocWasmString)(e.tag,s)),n=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),0===n)throw new Error("Can't create run options");return void 0!==(null==e?void 0:e.extra)&&(0,r.iterateExtraOptions)(e.extra,"",new WeakSet,((e,r)=>{const o=(0,i.allocWasmString)(e,s),a=(0,i.allocWasmString)(r,s);if(0!==t._OrtAddRunConfigEntry(n,o,a))throw new Error(`Can't set a run config entry: ${e} - ${r}`)})),[n,s]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),s.forEach(t._free),e}}},6640:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),i=n(8453),o=n(2850),s=n(9544),a=n(7917);let u;t.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(e){const t=await fetch(e),n=await t.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(n))}async loadModel(e,t){if(u||(await(0,s.initOrt)(i.env.wasm.numThreads,(0,a.logLevelStringToEnum)(i.env.logLevel)),u=!0),"string"==typeof e)if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(e);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(n,t)}else{const n=await this.createSessionAllocate(e);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(n,t)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(e,t)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(e,t,n){const r=[],o=[];Object.entries(e).forEach((e=>{const t=e[0],n=e[1],i=this.inputNames.indexOf(t);if(-1===i)throw new Error(`invalid input '${t}'`);r.push(n),o.push(i)}));const a=[];Object.entries(t).forEach((e=>{const t=e[0],n=this.outputNames.indexOf(t);if(-1===n)throw new Error(`invalid output '${t}'`);a.push(n)}));const u=await(0,s.run)(this.sessionId,o,r.map((e=>[e.type,e.dims,e.data])),a,n),l={};for(let e=0;e<u.length;e++)l[this.outputNames[a[e]]]=new i.Tensor(u[e][0],u[e][2],u[e][1]);return l}startProfiling(){}endProfiling(){(0,s.endProfiling)(this.sessionId)}}},7622:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSessionOptions=void 0;const r=n(3899),i=n(9444),o=n(263);t.setSessionOptions=e=>{var t,n,s,a;const u=(0,o.getInstance)();let l=0;const c=[],d=e||{};(e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});const t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)})(d);try{const e=(e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}})(null!==(t=d.graphOptimizationLevel)&&void 0!==t?t:"all"),h=(e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}})(null!==(n=d.executionMode)&&void 0!==n?n:"sequential"),p="string"==typeof d.logId?(0,i.allocWasmString)(d.logId,c):0,f=null!==(s=d.logSeverityLevel)&&void 0!==s?s:2;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log serverity level is not valid: ${f}`);const g=null!==(a=d.logVerbosityLevel)&&void 0!==a?a:0;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log verbosity level is not valid: ${g}`);const m="string"==typeof d.optimizedModelFilePath?(0,i.allocWasmString)(d.optimizedModelFilePath,c):0;if(l=u._OrtCreateSessionOptions(e,!!d.enableCpuMemArena,!!d.enableMemPattern,h,!!d.enableProfiling,0,p,f,g,m),0===l)throw new Error("Can't create session options");return d.executionProviders&&((e,t,n)=>{for(const r of t){let t="string"==typeof r?r:r.name;switch(t){case"xnnpack":t="XNNPACK";break;case"webgpu":t="JS";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${t}`)}const s=(0,i.allocWasmString)(t,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(e,s))throw new Error(`Can't append execution provider: ${t}`)}})(l,d.executionProviders,c),void 0!==d.extra&&(0,r.iterateExtraOptions)(d.extra,"",new WeakSet,((e,t)=>{const n=(0,i.allocWasmString)(e,c),r=(0,i.allocWasmString)(t,c);if(0!==u._OrtAddSessionConfigEntry(l,n,r))throw new Error(`Can't set a session config entry: ${e} - ${t}`)})),[l,c]}catch(e){throw 0!==l&&u._OrtReleaseSessionOptions(l),c.forEach(u._free),e}}},9444:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allocWasmString=void 0;const r=n(263);t.allocWasmString=(e,t)=>{const n=(0,r.getInstance)(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o}},7917:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelStringToEnum=t.tensorTypeToTypedArrayConstructor=t.getTensorElementSize=t.tensorDataTypeEnumToString=t.tensorDataTypeStringToEnum=void 0,t.tensorDataTypeStringToEnum=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},t.tensorDataTypeEnumToString=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},t.getTensorElementSize=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],t.tensorTypeToTypedArrayConstructor=e=>{switch(e){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},t.logLevelStringToEnum=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}}},1259:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTransferableBuffers=t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=void 0;const r=n(7918),i=n(7622),o=n(9444),s=n(7917),a=n(263);t.initOrt=(e,t)=>{const n=(0,a.getInstance)()._OrtInit(e,t);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const u=new Map;t.createSessionAllocate=e=>{const t=(0,a.getInstance)(),n=t._malloc(e.byteLength);return t.HEAPU8.set(e,n),[n,e.byteLength]},t.createSessionFinalize=(e,t)=>{const n=(0,a.getInstance)();let r=0,o=0,s=[];try{if([o,s]=(0,i.setSessionOptions)(t),r=n._OrtCreateSession(e[0],e[1],o),0===r)throw new Error("Can't create a session")}finally{n._free(e[0]),0!==o&&n._OrtReleaseSessionOptions(o),s.forEach(n._free)}const l=n._OrtGetInputCount(r),c=n._OrtGetOutputCount(r),d=[],h=[],p=[],f=[];for(let e=0;e<l;e++){const t=n._OrtGetInputName(r,e);if(0===t)throw new Error("Can't get an input name");h.push(t),d.push(n.UTF8ToString(t))}for(let e=0;e<c;e++){const t=n._OrtGetOutputName(r,e);if(0===t)throw new Error("Can't get an output name");f.push(t),p.push(n.UTF8ToString(t))}return u.set(r,[r,h,f]),[r,d,p]},t.createSession=(e,n)=>{const r=(0,t.createSessionAllocate)(e);return(0,t.createSessionFinalize)(r,n)},t.releaseSession=e=>{const t=(0,a.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],i=n[1],o=n[2];i.forEach(t._OrtFree),o.forEach(t._OrtFree),t._OrtReleaseSession(r),u.delete(e)},t.run=async(e,t,n,i,l)=>{const c=(0,a.getInstance)(),d=u.get(e);if(!d)throw new Error("invalid session id");const h=d[0],p=d[1],f=d[2],g=t.length,m=i.length;let b=0,y=[];const v=[],w=[];try{[b,y]=(0,r.setRunOptions)(l);for(let e=0;e<g;e++){const t=n[e][0],r=n[e][1],i=n[e][2];let a,u;if(Array.isArray(i)){u=4*i.length,a=c._malloc(u),w.push(a);let e=a/4;for(let t=0;t<i.length;t++){if("string"!=typeof i[t])throw new TypeError(`tensor data at index ${t} is not a string`);c.HEAPU32[e++]=(0,o.allocWasmString)(i[t],w)}}else u=i.byteLength,a=c._malloc(u),w.push(a),c.HEAPU8.set(new Uint8Array(i.buffer,i.byteOffset,u),a);const l=c.stackSave(),d=c.stackAlloc(4*r.length);try{let e=d/4;r.forEach((t=>c.HEAP32[e++]=t));const n=c._OrtCreateTensor((0,s.tensorDataTypeStringToEnum)(t),a,u,d,r.length);if(0===n)throw new Error("Can't create a tensor");v.push(n)}finally{c.stackRestore(l)}}const e=c.stackSave(),a=c.stackAlloc(4*g),u=c.stackAlloc(4*g),d=c.stackAlloc(4*m),S=c.stackAlloc(4*m);try{let e=a/4,n=u/4,r=d/4,o=S/4;for(let r=0;r<g;r++)c.HEAPU32[e++]=v[r],c.HEAPU32[n++]=p[t[r]];for(let e=0;e<m;e++)c.HEAPU32[r++]=0,c.HEAPU32[o++]=f[i[e]];let l=c._OrtRun(h,u,a,g,S,m,d,b);const y=c.jsepRunPromise;y&&void 0!==y.then&&(l=await y);const w=[];if(0===l)for(let e=0;e<m;e++){const t=c.HEAPU32[d/4+e],n=c.stackSave(),r=c.stackAlloc(16);let i,o=0;try{if(l=c._OrtGetTensorData(t,r,r+4,r+8,r+12),0!==l)throw new Error(`Can't access output tensor data. error code = ${l}`);let e=r/4;const n=c.HEAPU32[e++];o=c.HEAPU32[e++];const a=c.HEAPU32[e++],u=c.HEAPU32[e++],d=[];for(let e=0;e<u;e++)d.push(c.HEAPU32[a/4+e]);c._OrtFree(a);const h=0===d.length?1:d.reduce(((e,t)=>e*t));if(i=(0,s.tensorDataTypeEnumToString)(n),"string"===i){const e=[];let t=o/4;for(let n=0;n<h;n++){const r=c.HEAPU32[t++],i=n===h-1?void 0:c.HEAPU32[t]-r;e.push(c.UTF8ToString(r,i))}w.push([i,d,e])}else{const e=new((0,s.tensorTypeToTypedArrayConstructor)(i))(h);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(c.HEAPU8.subarray(o,o+e.byteLength)),w.push([i,d,e])}}finally{c.stackRestore(n),"string"===i&&o&&c._free(o),c._OrtReleaseTensor(t)}}if(0===l)return w;throw new Error(`failed to call OrtRun(). error code = ${l}.`)}finally{c.stackRestore(e)}}finally{v.forEach(c._OrtReleaseTensor),w.forEach(c._free),c._OrtReleaseRunOptions(b),y.forEach(c._free)}},t.endProfiling=e=>{const t=(0,a.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],i=t._OrtEndProfiling(r);if(0===i)throw new Error("Can't get an profile file name");t._OrtFree(i)},t.extractTransferableBuffers=e=>{const t=[];for(const n of e){const e=n[2];!Array.isArray(e)&&e.buffer&&t.push(e.buffer)}return t}},263:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.dispose=t.getInstance=t.initializeWebAssembly=void 0;const s=o(n(6449)),a=n(932),u=n(3474);let l,c=!1,d=!1,h=!1;t.initializeWebAssembly=async e=>{if(c)return Promise.resolve();if(d)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(h)throw new Error("previous call to 'initializeWebAssembly()' failed.");d=!0;const t=e.initTimeout,r=e.numThreads,i=e.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(e){return!1}})(),p=i&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(e){return!1}})(),f=e.wasmPaths,g="string"==typeof f?f:void 0,m=((e,t)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":e?"ort-wasm-simd.wasm":"ort-wasm.wasm")(p,o),b="object"==typeof f?f[m]:void 0;let y=!1;const v=[];if(t>0&&v.push(new Promise((e=>{setTimeout((()=>{y=!0,e()}),t)}))),v.push(new Promise(((e,t)=>{const r=o?u:a,i={locateFile:(e,t)=>o&&e.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):e.endsWith(".wasm")?b||(null!=g?g:t)+m:t+e};if(o)if("undefined"==typeof Blob)i.mainScriptUrlOrBlob=s.join("/","ort-wasm-threaded.js");else{const e=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;i.mainScriptUrlOrBlob=new Blob([e],{type:"text/javascript"})}r(i).then((t=>{d=!1,c=!0,l=t,e()}),(e=>{d=!1,h=!0,t(e)}))}))),await Promise.race(v),y)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},t.getInstance=()=>{if(c&&l)return l;throw new Error("WebAssembly is not initialized yet.")},t.dispose=()=>{var e;!c||d||h||(d=!0,null===(e=l.PThread)||void 0===e||e.terminateAllThreads(),l=void 0,d=!1,c=!1,h=!0)}},8050:(e,t,n)=>{"use strict";n.d(t,{Z:()=>o});var r=n(6614),i=n.n(r);function o(){return i()('/*!\n* ONNX Runtime Web v1.15.1\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var e={899:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.iterateExtraOptions=void 0,t.iterateExtraOptions=(e,n,r,a)=>{if("object"==typeof e&&null!==e){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach((([e,o])=>{const i=n?n+e:e;if("object"==typeof o)(0,t.iterateExtraOptions)(o,i+".",r,a);else if("string"==typeof o||"number"==typeof o)a(i,o.toString());else{if("boolean"!=typeof o)throw new Error("Can\'t handle extra config type: "+typeof o);a(i,o?"1":"0")}}))}},918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setRunOptions=void 0;const r=n(899),a=n(444),o=n(263);t.setRunOptions=e=>{const t=(0,o.getInstance)();let n=0;const i=[],s=e||{};try{if(void 0===(null==e?void 0:e.logSeverityLevel))s.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===(null==e?void 0:e.logVerbosityLevel))s.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===(null==e?void 0:e.terminate)&&(s.terminate=!1);let o=0;if(void 0!==(null==e?void 0:e.tag)&&(o=(0,a.allocWasmString)(e.tag,i)),n=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,o),0===n)throw new Error("Can\'t create run options");return void 0!==(null==e?void 0:e.extra)&&(0,r.iterateExtraOptions)(e.extra,"",new WeakSet,((e,r)=>{const o=(0,a.allocWasmString)(e,i),s=(0,a.allocWasmString)(r,i);if(0!==t._OrtAddRunConfigEntry(n,o,s))throw new Error(`Can\'t set a run config entry: ${e} - ${r}`)})),[n,i]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),i.forEach(t._free),e}}},622:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSessionOptions=void 0;const r=n(899),a=n(444),o=n(263);t.setSessionOptions=e=>{var t,n,i,s;const u=(0,o.getInstance)();let c=0;const l=[],f=e||{};(e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});const t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)})(f);try{const e=(e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}})(null!==(t=f.graphOptimizationLevel)&&void 0!==t?t:"all"),p=(e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}})(null!==(n=f.executionMode)&&void 0!==n?n:"sequential"),d="string"==typeof f.logId?(0,a.allocWasmString)(f.logId,l):0,m=null!==(i=f.logSeverityLevel)&&void 0!==i?i:2;if(!Number.isInteger(m)||m<0||m>4)throw new Error(`log serverity level is not valid: ${m}`);const g=null!==(s=f.logVerbosityLevel)&&void 0!==s?s:0;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log verbosity level is not valid: ${g}`);const h="string"==typeof f.optimizedModelFilePath?(0,a.allocWasmString)(f.optimizedModelFilePath,l):0;if(c=u._OrtCreateSessionOptions(e,!!f.enableCpuMemArena,!!f.enableMemPattern,p,!!f.enableProfiling,0,d,m,g,h),0===c)throw new Error("Can\'t create session options");return f.executionProviders&&((e,t,n)=>{for(const r of t){let t="string"==typeof r?r:r.name;switch(t){case"xnnpack":t="XNNPACK";break;case"webgpu":t="JS";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${t}`)}const i=(0,a.allocWasmString)(t,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(e,i))throw new Error(`Can\'t append execution provider: ${t}`)}})(c,f.executionProviders,l),void 0!==f.extra&&(0,r.iterateExtraOptions)(f.extra,"",new WeakSet,((e,t)=>{const n=(0,a.allocWasmString)(e,l),r=(0,a.allocWasmString)(t,l);if(0!==u._OrtAddSessionConfigEntry(c,n,r))throw new Error(`Can\'t set a session config entry: ${e} - ${t}`)})),[c,l]}catch(e){throw 0!==c&&u._OrtReleaseSessionOptions(c),l.forEach(u._free),e}}},444:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allocWasmString=void 0;const r=n(263);t.allocWasmString=(e,t)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(e)+1,o=n._malloc(a);return n.stringToUTF8(e,o,a),t.push(o),o}},917:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelStringToEnum=t.tensorTypeToTypedArrayConstructor=t.getTensorElementSize=t.tensorDataTypeEnumToString=t.tensorDataTypeStringToEnum=void 0,t.tensorDataTypeStringToEnum=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},t.tensorDataTypeEnumToString=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},t.getTensorElementSize=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],t.tensorTypeToTypedArrayConstructor=e=>{switch(e){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},t.logLevelStringToEnum=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}}},259:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTransferableBuffers=t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=void 0;const r=n(918),a=n(622),o=n(444),i=n(917),s=n(263);t.initOrt=(e,t)=>{const n=(0,s.getInstance)()._OrtInit(e,t);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;t.createSessionAllocate=e=>{const t=(0,s.getInstance)(),n=t._malloc(e.byteLength);return t.HEAPU8.set(e,n),[n,e.byteLength]},t.createSessionFinalize=(e,t)=>{const n=(0,s.getInstance)();let r=0,o=0,i=[];try{if([o,i]=(0,a.setSessionOptions)(t),r=n._OrtCreateSession(e[0],e[1],o),0===r)throw new Error("Can\'t create a session")}finally{n._free(e[0]),0!==o&&n._OrtReleaseSessionOptions(o),i.forEach(n._free)}const c=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],d=[],m=[];for(let e=0;e<c;e++){const t=n._OrtGetInputName(r,e);if(0===t)throw new Error("Can\'t get an input name");p.push(t),f.push(n.UTF8ToString(t))}for(let e=0;e<l;e++){const t=n._OrtGetOutputName(r,e);if(0===t)throw new Error("Can\'t get an output name");m.push(t),d.push(n.UTF8ToString(t))}return u.set(r,[r,p,m]),[r,f,d]},t.createSession=(e,n)=>{const r=(0,t.createSessionAllocate)(e);return(0,t.createSessionFinalize)(r,n)},t.releaseSession=e=>{const t=(0,s.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],o=n[2];a.forEach(t._OrtFree),o.forEach(t._OrtFree),t._OrtReleaseSession(r),u.delete(e)},t.run=async(e,t,n,a,c)=>{const l=(0,s.getInstance)(),f=u.get(e);if(!f)throw new Error("invalid session id");const p=f[0],d=f[1],m=f[2],g=t.length,h=a.length;let y=0,v=[];const b=[],w=[];try{[y,v]=(0,r.setRunOptions)(c);for(let e=0;e<g;e++){const t=n[e][0],r=n[e][1],a=n[e][2];let s,u;if(Array.isArray(a)){u=4*a.length,s=l._malloc(u),w.push(s);let e=s/4;for(let t=0;t<a.length;t++){if("string"!=typeof a[t])throw new TypeError(`tensor data at index ${t} is not a string`);l.HEAPU32[e++]=(0,o.allocWasmString)(a[t],w)}}else u=a.byteLength,s=l._malloc(u),w.push(s),l.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),s);const c=l.stackSave(),f=l.stackAlloc(4*r.length);try{let e=f/4;r.forEach((t=>l.HEAP32[e++]=t));const n=l._OrtCreateTensor((0,i.tensorDataTypeStringToEnum)(t),s,u,f,r.length);if(0===n)throw new Error("Can\'t create a tensor");b.push(n)}finally{l.stackRestore(c)}}const e=l.stackSave(),s=l.stackAlloc(4*g),u=l.stackAlloc(4*g),f=l.stackAlloc(4*h),_=l.stackAlloc(4*h);try{let e=s/4,n=u/4,r=f/4,o=_/4;for(let r=0;r<g;r++)l.HEAPU32[e++]=b[r],l.HEAPU32[n++]=d[t[r]];for(let e=0;e<h;e++)l.HEAPU32[r++]=0,l.HEAPU32[o++]=m[a[e]];let c=l._OrtRun(p,u,s,g,_,h,f,y);const v=l.jsepRunPromise;v&&void 0!==v.then&&(c=await v);const w=[];if(0===c)for(let e=0;e<h;e++){const t=l.HEAPU32[f/4+e],n=l.stackSave(),r=l.stackAlloc(16);let a,o=0;try{if(c=l._OrtGetTensorData(t,r,r+4,r+8,r+12),0!==c)throw new Error(`Can\'t access output tensor data. error code = ${c}`);let e=r/4;const n=l.HEAPU32[e++];o=l.HEAPU32[e++];const s=l.HEAPU32[e++],u=l.HEAPU32[e++],f=[];for(let e=0;e<u;e++)f.push(l.HEAPU32[s/4+e]);l._OrtFree(s);const p=0===f.length?1:f.reduce(((e,t)=>e*t));if(a=(0,i.tensorDataTypeEnumToString)(n),"string"===a){const e=[];let t=o/4;for(let n=0;n<p;n++){const r=l.HEAPU32[t++],a=n===p-1?void 0:l.HEAPU32[t]-r;e.push(l.UTF8ToString(r,a))}w.push([a,f,e])}else{const e=new((0,i.tensorTypeToTypedArrayConstructor)(a))(p);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(l.HEAPU8.subarray(o,o+e.byteLength)),w.push([a,f,e])}}finally{l.stackRestore(n),"string"===a&&o&&l._free(o),l._OrtReleaseTensor(t)}}if(0===c)return w;throw new Error(`failed to call OrtRun(). error code = ${c}.`)}finally{l.stackRestore(e)}}finally{b.forEach(l._OrtReleaseTensor),w.forEach(l._free),l._OrtReleaseRunOptions(y),v.forEach(l._free)}},t.endProfiling=e=>{const t=(0,s.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],a=t._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");t._OrtFree(a)},t.extractTransferableBuffers=e=>{const t=[];for(const n of e){const e=n[2];!Array.isArray(e)&&e.buffer&&t.push(e.buffer)}return t}},263:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return a(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.dispose=t.getInstance=t.initializeWebAssembly=void 0;const i=o(n(449)),s=n(932),u=n(474);let c,l=!1,f=!1,p=!1;t.initializeWebAssembly=async e=>{if(l)return Promise.resolve();if(f)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(p)throw new Error("previous call to \'initializeWebAssembly()\' failed.");f=!0;const t=e.initTimeout,r=e.numThreads,a=e.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(e){return!1}})(),d=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(e){return!1}})(),m=e.wasmPaths,g="string"==typeof m?m:void 0,h=((e,t)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":e?"ort-wasm-simd.wasm":"ort-wasm.wasm")(d,o),y="object"==typeof m?m[h]:void 0;let v=!1;const b=[];if(t>0&&b.push(new Promise((e=>{setTimeout((()=>{v=!0,e()}),t)}))),b.push(new Promise(((e,t)=>{const r=o?u:s,a={locateFile:(e,t)=>o&&e.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):e.endsWith(".wasm")?y||(null!=g?g:t)+h:t+e};if(o)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=i.join("/","ort-wasm-threaded.js");else{const e=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([e],{type:"text/javascript"})}r(a).then((t=>{f=!1,l=!0,c=t,e()}),(e=>{f=!1,p=!0,t(e)}))}))),await Promise.race(b),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},t.getInstance=()=>{if(l&&c)return c;throw new Error("WebAssembly is not initialized yet.")},t.dispose=()=>{var e;!l||f||p||(f=!0,null===(e=c.PThread)||void 0===e||e.terminateAllThreads(),c=void 0,f=!1,l=!1,p=!0)}},474:(e,t,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){function t(){return P.buffer!=D&&G(P.buffer),F}function r(){return P.buffer!=D&&G(P.buffer),U}function a(){return P.buffer!=D&&G(P.buffer),I}function o(){return P.buffer!=D&&G(P.buffer),W}function i(){return P.buffer!=D&&G(P.buffer),j}var s,u,c;e=e||{},s||(s=void 0!==e?e:{}),s.ready=new Promise((function(e,t){u=e,c=t}));var l,f,p,d,m,g,h=Object.assign({},s),y="./this.program",v=(e,t)=>{throw t},b="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=s.ENVIRONMENT_IS_PTHREAD||!1,S="";function T(e){return s.locateFile?s.locateFile(e,S):S+e}if(_){let t;S=w?n(908).dirname(S)+"/":"//",g=()=>{m||(d=n(384),m=n(908))},l=function(e,t){return g(),e=m.normalize(e),d.readFileSync(e,t?void 0:"utf8")},p=e=>((e=l(e,!0)).buffer||(e=new Uint8Array(e)),e),f=(e,t,n)=>{g(),e=m.normalize(e),d.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(y=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof ie))throw e})),process.on("unhandledRejection",(function(e){throw e})),v=(e,t)=>{if(C)throw process.exitCode=e,t;t instanceof ie||x("exiting due to exception: "+t),process.exit(e)},s.inspect=function(){return"[Emscripten Module object]"};try{t=n(925)}catch(e){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),e}n.g.Worker=t.Worker}else(b||w)&&(w?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),_scriptDir&&(S=_scriptDir),S=0!==S.indexOf("blob:")?S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},w&&(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),f=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var A=console.log.bind(console),E=console.warn.bind(console);_&&(g(),A=e=>d.writeSync(1,e+"\\n"),E=e=>d.writeSync(2,e+"\\n"));var M,R=s.print||A,x=s.printErr||E;Object.assign(s,h),h=null,s.thisProgram&&(y=s.thisProgram),s.quit&&(v=s.quit),s.wasmBinary&&(M=s.wasmBinary);var C=s.noExitRuntime||!0;"object"!=typeof WebAssembly&&ne("no native wasm support detected");var P,k,D,F,U,I,W,j,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function Y(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&L)return L.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,n):e.subarray(t,n));for(r="";t<n;){var a=e[t++];if(128&a){var o=63&e[t++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|o);else{var i=63&e[t++];65536>(a=224==(240&a)?(15&a)<<12|o<<6|i:(7&a)<<18|o<<12|i<<6|63&e[t++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function z(e,t){return(e>>>=0)?Y(r(),e,t):""}function B(e,t,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var i=e.charCodeAt(o);if(55296<=i&&57343>=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++o)),127>=i){if(n>=r)break;t[n++>>>0]=i}else{if(2047>=i){if(n+1>=r)break;t[n++>>>0]=192|i>>6}else{if(65535>=i){if(n+2>=r)break;t[n++>>>0]=224|i>>12}else{if(n+3>=r)break;t[n++>>>0]=240|i>>18,t[n++>>>0]=128|i>>12&63}t[n++>>>0]=128|i>>6&63}t[n++>>>0]=128|63&i}}return t[n>>>0]=0,n-a}function N(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function G(e){D=e,s.HEAP8=F=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAP32=I=new Int32Array(e),s.HEAPU8=U=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAPU32=W=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=j=new Float64Array(e)}O&&(D=s.buffer);var q=s.INITIAL_MEMORY||16777216;if(O)P=s.wasmMemory,D=s.buffer;else if(s.wasmMemory)P=s.wasmMemory;else if(!((P=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");P&&(D=P.buffer),q=D.byteLength,G(D);var $,V=[],J=[],Q=[];function X(){var e=s.preRun.shift();V.unshift(e)}var K,Z=0,ee=null,te=null;function ne(e){throw O?postMessage({cmd:"onAbort",arg:e}):s.onAbort&&s.onAbort(e),x(e="Aborted("+e+")"),H=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),c(e),e}function re(){return K.startsWith("data:application/octet-stream;base64,")}function ae(){var e=K;try{if(e==K&&M)return new Uint8Array(M);if(p)return p(e);throw"both async and sync fetching of the wasm failed"}catch(e){ne(e)}}K="ort-wasm-threaded.wasm",re()||(K=T(K));var oe={};function ie(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function se(e){(e=fe.La[e])||ne(),fe.Xa(e)}function ue(e){var t=fe.lb();if(!t)return 6;fe.Ra.push(t),fe.La[e.Ka]=t,t.Ka=e.Ka;var n={cmd:"run",start_routine:e.pb,arg:e.ib,pthread_ptr:e.Ka};return t.Qa=()=>{n.time=performance.now(),t.postMessage(n,e.vb)},t.loaded&&(t.Qa(),delete t.Qa),0}function ce(e){if(O)return He(1,1,e);C||(fe.qb(),s.onExit&&s.onExit(e),H=!0),v(e,new ie(e))}function le(e,t){if(!t&&O)throw de(e),"unwind";ce(e)}var fe={Oa:[],Ra:[],$a:[],La:{},Ua:function(){O&&fe.mb()},xb:function(){},mb:function(){fe.receiveObjectTransfer=fe.ob,fe.threadInitTLS=fe.Za,fe.setExitStatus=fe.Ya,C=!1},Ya:function(){},qb:function(){for(var e of Object.values(fe.La))fe.Xa(e);for(e of fe.Oa)e.terminate();fe.Oa=[]},Xa:function(e){var t=e.Ka;delete fe.La[t],fe.Oa.push(e),fe.Ra.splice(fe.Ra.indexOf(e),1),e.Ka=0,ct(t)},ob:function(){},Za:function(){fe.$a.forEach((e=>e()))},nb:function(e,t){e.onmessage=n=>{var r=(n=n.data).cmd;if(e.Ka&&(fe.kb=e.Ka),n.targetThread&&n.targetThread!=rt()){var a=fe.La[n.yb];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?De(n.queue):"spawnThread"===r?ue(n):"cleanupThread"===r?se(n.thread):"killThread"===r?(n=n.thread,r=fe.La[n],delete fe.La[n],r.terminate(),ct(n),fe.Ra.splice(fe.Ra.indexOf(r),1),r.Ka=0):"cancelThread"===r?fe.La[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,t&&t(e),e.Qa&&(e.Qa(),delete e.Qa)):"print"===r?R("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?e.postMessage(n):"onAbort"===r?s.onAbort&&s.onAbort(n.arg):r&&x("worker sent an unknown command "+r);fe.kb=void 0},e.onerror=e=>{throw x("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},_&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){}))),e.postMessage({cmd:"load",urlOrBlob:s.mainScriptUrlOrBlob||_scriptDir,wasmMemory:P,wasmModule:k})},hb:function(){var e=T("ort-wasm-threaded.worker.js");fe.Oa.push(new Worker(e))},lb:function(){return 0==fe.Oa.length&&(fe.hb(),fe.nb(fe.Oa[0])),fe.Oa.pop()}};function pe(e){for(;0<e.length;)e.shift()(s)}function de(e){if(O)return He(2,0,e);try{le(e)}catch(e){e instanceof ie||"unwind"==e||v(1,e)}}s.PThread=fe,s.establishStackSpace=function(){var e=rt(),t=a()[e+44>>2>>>0];e=a()[e+48>>2>>>0],ft(t,t-e),dt(t)};var me,ge,he=[];function ye(e){this.Pa=e-24,this.gb=function(e){o()[this.Pa+4>>2>>>0]=e},this.cb=function(e){o()[this.Pa+8>>2>>>0]=e},this.eb=function(){a()[this.Pa>>2>>>0]=0},this.bb=function(){t()[this.Pa+12>>0>>>0]=0},this.fb=function(){t()[this.Pa+13>>0>>>0]=0},this.Ua=function(e,t){this.ab(),this.gb(e),this.cb(t),this.eb(),this.bb(),this.fb()},this.ab=function(){o()[this.Pa+16>>2>>>0]=0}}function ve(e,t,n,r){return O?He(3,1,e,t,n,r):be(e,t,n,r)}function be(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?ve(e,t,n,r):(e={pb:n,Ka:e,ib:r,vb:a},O?(e.wb="spawnThread",postMessage(e,a),0):ue(e))}function we(e,t,n){return O?He(4,1,e,t,n):0}function _e(e,t){if(O)return He(5,1,e,t)}function Oe(e,t){if(O)return He(6,1,e,t)}function Se(e,t,n){if(O)return He(7,1,e,t,n)}function Te(e,t,n){return O?He(8,1,e,t,n):0}function Ae(e,t){if(O)return He(9,1,e,t)}function Ee(e,t,n){if(O)return He(10,1,e,t,n)}function Me(e,t,n,r){if(O)return He(11,1,e,t,n,r)}function Re(e,t,n,r){if(O)return He(12,1,e,t,n,r)}function xe(e,t,n,r){if(O)return He(13,1,e,t,n,r)}function Ce(e){if(O)return He(14,1,e)}function Pe(e,t){if(O)return He(15,1,e,t)}function ke(e,t,n){if(O)return He(16,1,e,t,n)}function De(e){Atomics.store(a(),e>>2,1),rt()&&ut(e),Atomics.compareExchange(a(),e>>2,1,0)}function Fe(e){return o()[e>>>2]+4294967296*a()[e+4>>>2]}function Ue(e,t,n,r,a,o){return O?He(17,1,e,t,n,r,a,o):-52}function Ie(e,t,n,r,a,o){if(O)return He(18,1,e,t,n,r,a,o)}function We(e){var n=N(e)+1,r=at(n);return r&&B(e,t(),r,n),r}function je(e,t,n){function r(e){return(e=e.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?e[1]:"GMT"}if(O)return He(19,1,e,t,n);var i=(new Date).getFullYear(),s=new Date(i,0,1),u=new Date(i,6,1);i=s.getTimezoneOffset();var c=u.getTimezoneOffset(),l=Math.max(i,c);a()[e>>2>>>0]=60*l,a()[t>>2>>>0]=Number(i!=c),e=r(s),t=r(u),e=We(e),t=We(t),c<i?(o()[n>>2>>>0]=e,o()[n+4>>2>>>0]=t):(o()[n>>2>>>0]=t,o()[n+4>>2>>>0]=e)}function He(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=pt();return e=e(),dt(t),e}((()=>{for(var a=mt(8*n),o=a>>3,s=0;s<n;s++){var u=r[2+s];i()[o+s>>>0]=u}return st(e,n,a,t)}))}s.invokeEntryPoint=function(e,t){var n=he[e];n||(e>=he.length&&(he.length=e+1),he[e]=n=$.get(e)),e=n(t),C?fe.Ya(e):lt(e)},s.executeNotifiedProxyingQueue=De,ge=_?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:O?()=>performance.now()-s.__performance_now_clock_drift:()=>performance.now();var Le,Ye=[],ze={};function Be(){if(!Le){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:y||"./this.program"};for(e in ze)void 0===ze[e]?delete t[e]:t[e]=ze[e];var n=[];for(e in t)n.push(e+"="+t[e]);Le=n}return Le}function Ne(e,n){if(O)return He(20,1,e,n);var r=0;return Be().forEach((function(a,i){var s=n+r;for(i=o()[e+4*i>>2>>>0]=s,s=0;s<a.length;++s)t()[i++>>0>>>0]=a.charCodeAt(s);t()[i>>0>>>0]=0,r+=a.length+1})),0}function Ge(e,t){if(O)return He(21,1,e,t);var n=Be();o()[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),o()[t>>2>>>0]=r,0}function qe(e){return O?He(22,1,e):52}function $e(e,t,n,r){return O?He(23,1,e,t,n,r):52}function Ve(e,t,n,r,a){return O?He(24,1,e,t,n,r,a):70}var Je=[null,[],[]];function Qe(e,t,n,a){if(O)return He(25,1,e,t,n,a);for(var i=0,s=0;s<n;s++){var u=o()[t>>2>>>0],c=o()[t+4>>2>>>0];t+=8;for(var l=0;l<c;l++){var f=r()[u+l>>>0],p=Je[e];0===f||10===f?((1===e?R:x)(Y(p,0)),p.length=0):p.push(f)}i+=c}return o()[a>>2>>>0]=i,0}function Xe(e){return 0==e%4&&(0!=e%100||0==e%400)}var Ke=[31,29,31,30,31,30,31,31,30,31,30,31],Ze=[31,28,31,30,31,30,31,31,30,31,30,31];function et(e,n,r,o){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function s(e,t){return i(e,t,"0")}function u(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function c(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function l(e){var t=e.Ma;for(e=new Date(new Date(e.Na+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(Xe(e.getFullYear())?Ke:Ze)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=c(new Date(e.getFullYear(),0,4)),n=c(n),0>=u(t,e)?0>=u(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var f=a()[o+40>>2>>>0];for(var p in o={tb:a()[o>>2>>>0],sb:a()[o+4>>2>>>0],Sa:a()[o+8>>2>>>0],Va:a()[o+12>>2>>>0],Ta:a()[o+16>>2>>>0],Na:a()[o+20>>2>>>0],Ja:a()[o+24>>2>>>0],Ma:a()[o+28>>2>>>0],zb:a()[o+32>>2>>>0],rb:a()[o+36>>2>>>0],ub:f?z(f):""},r=z(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),m="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(e){return d[e.Ja].substring(0,3)},"%A":function(e){return d[e.Ja]},"%b":function(e){return m[e.Ta].substring(0,3)},"%B":function(e){return m[e.Ta]},"%C":function(e){return s((e.Na+1900)/100|0,2)},"%d":function(e){return s(e.Va,2)},"%e":function(e){return i(e.Va,2," ")},"%g":function(e){return l(e).toString().substring(2)},"%G":function(e){return l(e)},"%H":function(e){return s(e.Sa,2)},"%I":function(e){return 0==(e=e.Sa)?e=12:12<e&&(e-=12),s(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.Ta-1;t+=(Xe(e.Na+1900)?Ke:Ze)[n++]);return s(e.Va+t,3)},"%m":function(e){return s(e.Ta+1,2)},"%M":function(e){return s(e.sb,2)},"%n":function(){return"\\n"},"%p":function(e){return 0<=e.Sa&&12>e.Sa?"AM":"PM"},"%S":function(e){return s(e.tb,2)},"%t":function(){return"\\t"},"%u":function(e){return e.Ja||7},"%U":function(e){return s(Math.floor((e.Ma+7-e.Ja)/7),2)},"%V":function(e){var t=Math.floor((e.Ma+7-(e.Ja+6)%7)/7);if(2>=(e.Ja+371-e.Ma-2)%7&&t++,t)53==t&&(4==(n=(e.Ja+371-e.Ma)%7)||3==n&&Xe(e.Na)||(t=1));else{t=52;var n=(e.Ja+7-e.Ma-1)%7;(4==n||5==n&&Xe(e.Na%400-1))&&t++}return s(t,2)},"%w":function(e){return e.Ja},"%W":function(e){return s(Math.floor((e.Ma+7-(e.Ja+6)%7)/7),2)},"%y":function(e){return(e.Na+1900).toString().substring(2)},"%Y":function(e){return e.Na+1900},"%z":function(e){var t=0<=(e=e.rb);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.ub},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](o)));return p=function(e){var t=Array(N(e)+1);return B(e,t,0,t.length),t}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(e,n){t().set(e,n>>>0)}(p,e),p.length-1)}fe.Ua();var tt=[null,ce,de,ve,we,_e,Oe,Se,Te,Ae,Ee,Me,Re,xe,Ce,Pe,ke,Ue,Ie,je,Ne,Ge,qe,$e,Ve,Qe],nt={b:function(e){return at(e+24)+24},c:function(e,t,n){throw new ye(e).Ua(t,n),e},L:function(e){ot(e,!w,1,!b),fe.Za()},l:function(e){O?postMessage({cmd:"cleanupThread",thread:e}):se(e)},D:be,i:we,R:_e,z:Oe,B:Se,T:Te,P:Ae,I:Ee,O:Me,p:Re,A:xe,x:Ce,Q:Pe,y:ke,r:function(){},j:function(){ne("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},s:function(){ne("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},q:function(){return Date.now()},E:function(){return 2097152},V:function(){return!0},F:function(e,t,n,r){if(e==t)setTimeout((()=>De(r)));else if(O)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{if(!(e=fe.La[e]))return;e.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},K:function(){return-1},W:function(e,t){e=new Date(1e3*Fe(e)),a()[t>>2>>>0]=e.getUTCSeconds(),a()[t+4>>2>>>0]=e.getUTCMinutes(),a()[t+8>>2>>>0]=e.getUTCHours(),a()[t+12>>2>>>0]=e.getUTCDate(),a()[t+16>>2>>>0]=e.getUTCMonth(),a()[t+20>>2>>>0]=e.getUTCFullYear()-1900,a()[t+24>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[t+28>>2>>>0]=e},X:function(e,t){e=new Date(1e3*Fe(e)),a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),a()[t+20>>2>>>0]=e.getFullYear()-1900,a()[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1),r=(e.getTime()-n.getTime())/864e5|0;a()[t+28>>2>>>0]=r,a()[t+36>>2>>>0]=-60*e.getTimezoneOffset(),r=new Date(e.getFullYear(),6,1).getTimezoneOffset(),e=0|(r!=(n=n.getTimezoneOffset())&&e.getTimezoneOffset()==Math.min(n,r)),a()[t+32>>2>>>0]=e},Y:function(e){var t=new Date(a()[e+20>>2>>>0]+1900,a()[e+16>>2>>>0],a()[e+12>>2>>>0],a()[e+8>>2>>>0],a()[e+4>>2>>>0],a()[e>>2>>>0],0),n=a()[e+32>>2>>>0],r=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),u=Math.min(s,i);return 0>n?a()[e+32>>2>>>0]=Number(i!=s&&u==r):0<n!=(u==r)&&(i=Math.max(s,i),t.setTime(t.getTime()+6e4*((0<n?u:i)-r))),a()[e+24>>2>>>0]=t.getDay(),n=(t.getTime()-o.getTime())/864e5|0,a()[e+28>>2>>>0]=n,a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},G:Ue,H:Ie,Z:function e(t,n,r){e.jb||(e.jb=!0,je(t,n,r))},d:function(){ne("")},m:function(){if(!_&&!w){var e="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";me||(me={}),me[e]||(me[e]=1,_&&(e="warning: "+e),x(e))}},w:function(){return 4294901760},f:ge,S:function(e,t,n){r().copyWithin(e>>>0,t>>>0,t+n>>>0)},g:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},J:function(e,t,n){Ye.length=t,n>>=3;for(var r=0;r<t;r++)Ye[r]=i()[n+r>>>0];return(0>e?oe[-e-1]:tt[e]).apply(null,Ye)},v:function(e){var t=r().length;if((e>>>=0)<=t||4294901760<e)return!1;for(var n=1;4>=n;n*=2){var a=t*(1+.2/n);a=Math.min(a,e+100663296);var o=Math;a=Math.max(e,a),o=o.min.call(o,4294901760,a+(65536-a%65536)%65536);e:{try{P.grow(o-D.byteLength+65535>>>16),G(P.buffer);var i=1;break e}catch(e){}i=void 0}if(i)return!0}return!1},U:function(){throw"unwind"},M:Ne,N:Ge,k:le,h:qe,o:$e,t:Ve,n:Qe,u:function e(r,a){e.Wa||(e.Wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(_)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>ne("randomDevice")}());for(var o=0;o<a;o++)t()[r+o>>0>>>0]=e.Wa();return 0},a:P||s.wasmMemory,C:et,e:function(e,t,n,r){return et(e,t,n,r)}};!function(){function e(e,t){s.asm=e.exports,fe.$a.push(s.asm.wa),$=s.asm.za,J.unshift(s.asm._),k=t,O||(Z--,s.monitorRunDependencies&&s.monitorRunDependencies(Z),0==Z&&(null!==ee&&(clearInterval(ee),ee=null),te&&(e=te,te=null,e())))}function t(t){e(t.instance,t.module)}function n(e){return function(){if(!M&&(b||w)){if("function"==typeof fetch&&!K.startsWith("file://"))return fetch(K,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at \'"+K+"\'";return e.arrayBuffer()})).catch((function(){return ae()}));if(f)return new Promise((function(e,t){f(K,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return ae()}))}().then((function(e){return WebAssembly.instantiate(e,r)})).then((function(e){return e})).then(e,(function(e){x("failed to asynchronously prepare wasm: "+e),ne(e)}))}var r={a:nt};if(O||(Z++,s.monitorRunDependencies&&s.monitorRunDependencies(Z)),s.instantiateWasm)try{return s.instantiateWasm(r,e)}catch(e){return x("Module.instantiateWasm callback failed with error: "+e),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||re()||K.startsWith("file://")||_||"function"!=typeof fetch?n(t):fetch(K,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(t,(function(e){return x("wasm streaming compile failed: "+e),x("falling back to ArrayBuffer instantiation"),n(t)}))}))).catch(c)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm._).apply(null,arguments)},s._OrtInit=function(){return(s._OrtInit=s.asm.$).apply(null,arguments)},s._OrtCreateSessionOptions=function(){return(s._OrtCreateSessionOptions=s.asm.aa).apply(null,arguments)},s._OrtAppendExecutionProvider=function(){return(s._OrtAppendExecutionProvider=s.asm.ba).apply(null,arguments)},s._OrtAddSessionConfigEntry=function(){return(s._OrtAddSessionConfigEntry=s.asm.ca).apply(null,arguments)},s._OrtReleaseSessionOptions=function(){return(s._OrtReleaseSessionOptions=s.asm.da).apply(null,arguments)},s._OrtCreateSession=function(){return(s._OrtCreateSession=s.asm.ea).apply(null,arguments)},s._OrtReleaseSession=function(){return(s._OrtReleaseSession=s.asm.fa).apply(null,arguments)},s._OrtGetInputCount=function(){return(s._OrtGetInputCount=s.asm.ga).apply(null,arguments)},s._OrtGetOutputCount=function(){return(s._OrtGetOutputCount=s.asm.ha).apply(null,arguments)},s._OrtGetInputName=function(){return(s._OrtGetInputName=s.asm.ia).apply(null,arguments)},s._OrtGetOutputName=function(){return(s._OrtGetOutputName=s.asm.ja).apply(null,arguments)},s._OrtFree=function(){return(s._OrtFree=s.asm.ka).apply(null,arguments)},s._OrtCreateTensor=function(){return(s._OrtCreateTensor=s.asm.la).apply(null,arguments)},s._OrtGetTensorData=function(){return(s._OrtGetTensorData=s.asm.ma).apply(null,arguments)},s._OrtReleaseTensor=function(){return(s._OrtReleaseTensor=s.asm.na).apply(null,arguments)},s._OrtCreateRunOptions=function(){return(s._OrtCreateRunOptions=s.asm.oa).apply(null,arguments)},s._OrtAddRunConfigEntry=function(){return(s._OrtAddRunConfigEntry=s.asm.pa).apply(null,arguments)},s._OrtReleaseRunOptions=function(){return(s._OrtReleaseRunOptions=s.asm.qa).apply(null,arguments)},s._OrtRun=function(){return(s._OrtRun=s.asm.ra).apply(null,arguments)},s._OrtEndProfiling=function(){return(s._OrtEndProfiling=s.asm.sa).apply(null,arguments)};var rt=s._pthread_self=function(){return(rt=s._pthread_self=s.asm.ta).apply(null,arguments)},at=s._malloc=function(){return(at=s._malloc=s.asm.ua).apply(null,arguments)};s._free=function(){return(s._free=s.asm.va).apply(null,arguments)},s.__emscripten_tls_init=function(){return(s.__emscripten_tls_init=s.asm.wa).apply(null,arguments)};var ot=s.__emscripten_thread_init=function(){return(ot=s.__emscripten_thread_init=s.asm.xa).apply(null,arguments)};s.__emscripten_thread_crashed=function(){return(s.__emscripten_thread_crashed=s.asm.ya).apply(null,arguments)};var it,st=s._emscripten_run_in_main_runtime_thread_js=function(){return(st=s._emscripten_run_in_main_runtime_thread_js=s.asm.Aa).apply(null,arguments)},ut=s.__emscripten_proxy_execute_task_queue=function(){return(ut=s.__emscripten_proxy_execute_task_queue=s.asm.Ba).apply(null,arguments)},ct=s.__emscripten_thread_free_data=function(){return(ct=s.__emscripten_thread_free_data=s.asm.Ca).apply(null,arguments)},lt=s.__emscripten_thread_exit=function(){return(lt=s.__emscripten_thread_exit=s.asm.Da).apply(null,arguments)},ft=s._emscripten_stack_set_limits=function(){return(ft=s._emscripten_stack_set_limits=s.asm.Ea).apply(null,arguments)},pt=s.stackSave=function(){return(pt=s.stackSave=s.asm.Fa).apply(null,arguments)},dt=s.stackRestore=function(){return(dt=s.stackRestore=s.asm.Ga).apply(null,arguments)},mt=s.stackAlloc=function(){return(mt=s.stackAlloc=s.asm.Ha).apply(null,arguments)};function gt(){function e(){if(!it&&(it=!0,s.calledRun=!0,!H)&&(O||pe(J),u(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),!O)){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;){var e=s.postRun.shift();Q.unshift(e)}pe(Q)}}if(!(0<Z))if(O)u(s),O||pe(J),postMessage({cmd:"loaded"});else{if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)X();pe(V),0<Z||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),e()}),1)):e())}}if(s.___cxa_is_pointer_type=function(){return(s.___cxa_is_pointer_type=s.asm.Ia).apply(null,arguments)},s.UTF8ToString=z,s.stringToUTF8=function(e,t,n){return B(e,r(),t,n)},s.lengthBytesUTF8=N,s.keepRuntimeAlive=function(){return C},s.wasmMemory=P,s.stackSave=pt,s.stackRestore=dt,s.stackAlloc=mt,s.ExitStatus=ie,s.PThread=fe,te=function e(){it||gt(),it||(te=e)},s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);0<s.preInit.length;)s.preInit.pop()();return gt(),e.ready});e.exports=r},932:(e,t,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,r,a;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){r=e,a=t}));var o,i,s,u,c,l,f=Object.assign({},t),p="./this.program",d=(e,t)=>{throw t},m="object"==typeof window,g="function"==typeof importScripts,h="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,y="";h?(y=g?n(908).dirname(y)+"/":"//",l=()=>{c||(u=n(384),c=n(908))},o=function(e,t){return l(),e=c.normalize(e),u.readFileSync(e,t?void 0:"utf8")},s=e=>((e=o(e,!0)).buffer||(e=new Uint8Array(e)),e),i=(e,t,n)=>{l(),e=c.normalize(e),u.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof $))throw e})),process.on("unhandledRejection",(function(e){throw e})),d=(e,t)=>{if(_)throw process.exitCode=e,t;t instanceof $||w("exiting due to exception: "+t),process.exit(e)},t.inspect=function(){return"[Emscripten Module object]"}):(m||g)&&(g?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),_scriptDir&&(y=_scriptDir),y=0!==y.indexOf("blob:")?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),i=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var v,b=t.print||console.log.bind(console),w=t.printErr||console.warn.bind(console);Object.assign(t,f),f=null,t.thisProgram&&(p=t.thisProgram),t.quit&&(d=t.quit),t.wasmBinary&&(v=t.wasmBinary);var _=t.noExitRuntime||!0;"object"!=typeof WebAssembly&&B("no native wasm support detected");var O,S,T,A,E,M,R=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function C(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&x)return x.decode(e.subarray(t,n));for(r="";t<n;){var a=e[t++];if(128&a){var o=63&e[t++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|o);else{var i=63&e[t++];65536>(a=224==(240&a)?(15&a)<<12|o<<6|i:(7&a)<<18|o<<12|i<<6|63&e[t++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function P(e,t){return(e>>>=0)?C(A,e,t):""}function k(e,t,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var i=e.charCodeAt(o);if(55296<=i&&57343>=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++o)),127>=i){if(n>=r)break;t[n++>>>0]=i}else{if(2047>=i){if(n+1>=r)break;t[n++>>>0]=192|i>>6}else{if(65535>=i){if(n+2>=r)break;t[n++>>>0]=224|i>>12}else{if(n+3>=r)break;t[n++>>>0]=240|i>>18,t[n++>>>0]=128|i>>12&63}t[n++>>>0]=128|i>>6&63}t[n++>>>0]=128|63&i}}return t[n>>>0]=0,n-a}function D(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function F(){var e=O.buffer;S=e,t.HEAP8=T=new Int8Array(e),t.HEAP16=new Int16Array(e),t.HEAP32=E=new Int32Array(e),t.HEAPU8=A=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=M=new Uint32Array(e),t.HEAPF32=new Float32Array(e),t.HEAPF64=new Float64Array(e)}var U=[],I=[],W=[];function j(){var e=t.preRun.shift();U.unshift(e)}var H,L=0,Y=null,z=null;function B(e){throw t.onAbort&&t.onAbort(e),w(e="Aborted("+e+")"),R=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),a(e),e}function N(){return H.startsWith("data:application/octet-stream;base64,")}if(H="ort-wasm.wasm",!N()){var G=H;H=t.locateFile?t.locateFile(G,y):y+G}function q(){var e=H;try{if(e==H&&v)return new Uint8Array(v);if(s)return s(e);throw"both async and sync fetching of the wasm failed"}catch(e){B(e)}}function $(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function V(e){for(;0<e.length;)e.shift()(t)}function J(e){this.sa=e-24,this.Ia=function(e){M[this.sa+4>>2>>>0]=e},this.Ba=function(e){M[this.sa+8>>2>>>0]=e},this.Ga=function(){E[this.sa>>2>>>0]=0},this.Aa=function(){T[this.sa+12>>0>>>0]=0},this.Ha=function(){T[this.sa+13>>0>>>0]=0},this.ya=function(e,t){this.za(),this.Ia(e),this.Ba(t),this.Ga(),this.Aa(),this.Ha()},this.za=function(){M[this.sa+16>>2>>>0]=0}}function Q(e){var t=D(e)+1,n=ie(t);return n&&k(e,T,n,t),n}var X={};function K(){if(!Z){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(e in X)void 0===X[e]?delete t[e]:t[e]=X[e];var n=[];for(e in t)n.push(e+"="+t[e]);Z=n}return Z}var Z,ee=[null,[],[]];function te(e){return 0==e%4&&(0!=e%100||0==e%400)}var ne=[31,29,31,30,31,30,31,31,30,31,30,31],re=[31,28,31,30,31,30,31,31,30,31,30,31];function ae(e,t,n,r){function a(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function o(e,t){return a(e,t,"0")}function i(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function s(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.qa;for(e=new Date(new Date(e.ra+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(te(e.getFullYear())?ne:re)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=s(new Date(e.getFullYear(),0,4)),n=s(n),0>=i(t,e)?0>=i(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var c=E[r+40>>2>>>0];for(var l in r={Ea:E[r>>2>>>0],Da:E[r+4>>2>>>0],ta:E[r+8>>2>>>0],va:E[r+12>>2>>>0],ua:E[r+16>>2>>>0],ra:E[r+20>>2>>>0],la:E[r+24>>2>>>0],qa:E[r+28>>2>>>0],Ja:E[r+32>>2>>>0],Ca:E[r+36>>2>>>0],Fa:c?P(c):""},n=P(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),c[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in c={"%a":function(e){return f[e.la].substring(0,3)},"%A":function(e){return f[e.la]},"%b":function(e){return p[e.ua].substring(0,3)},"%B":function(e){return p[e.ua]},"%C":function(e){return o((e.ra+1900)/100|0,2)},"%d":function(e){return o(e.va,2)},"%e":function(e){return a(e.va,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return o(e.ta,2)},"%I":function(e){return 0==(e=e.ta)?e=12:12<e&&(e-=12),o(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.ua-1;t+=(te(e.ra+1900)?ne:re)[n++]);return o(e.va+t,3)},"%m":function(e){return o(e.ua+1,2)},"%M":function(e){return o(e.Da,2)},"%n":function(){return"\\n"},"%p":function(e){return 0<=e.ta&&12>e.ta?"AM":"PM"},"%S":function(e){return o(e.Ea,2)},"%t":function(){return"\\t"},"%u":function(e){return e.la||7},"%U":function(e){return o(Math.floor((e.qa+7-e.la)/7),2)},"%V":function(e){var t=Math.floor((e.qa+7-(e.la+6)%7)/7);if(2>=(e.la+371-e.qa-2)%7&&t++,t)53==t&&(4==(n=(e.la+371-e.qa)%7)||3==n&&te(e.ra)||(t=1));else{t=52;var n=(e.la+7-e.qa-1)%7;(4==n||5==n&&te(e.ra%400-1))&&t++}return o(t,2)},"%w":function(e){return e.la},"%W":function(e){return o(Math.floor((e.qa+7-(e.la+6)%7)/7),2)},"%y":function(e){return(e.ra+1900).toString().substring(2)},"%Y":function(e){return e.ra+1900},"%z":function(e){var t=0<=(e=e.Ca);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.Fa},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),c)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),c[l](r)));return l=function(e){var t=Array(D(e)+1);return k(e,t,0,t.length),t}(n=n.replace(/\\0\\0/g,"%")),l.length>t?0:(T.set(l,e>>>0),l.length-1)}var oe={a:function(e){return ie(e+24)+24},b:function(e,t,n){throw new J(e).ya(t,n),e},g:function(){return 0},I:function(){},w:function(){},y:function(){},K:function(){return 0},G:function(){},C:function(){},F:function(){},k:function(){},x:function(){},u:function(){},H:function(){},v:function(){},n:function(){},p:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},o:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},l:function(){return Date.now()},L:function(){return!0},M:function(e,t){e=new Date(1e3*(M[e>>>2]+4294967296*E[e+4>>>2])),E[t>>2>>>0]=e.getUTCSeconds(),E[t+4>>2>>>0]=e.getUTCMinutes(),E[t+8>>2>>>0]=e.getUTCHours(),E[t+12>>2>>>0]=e.getUTCDate(),E[t+16>>2>>>0]=e.getUTCMonth(),E[t+20>>2>>>0]=e.getUTCFullYear()-1900,E[t+24>>2>>>0]=e.getUTCDay(),E[t+28>>2>>>0]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},N:function(e,t){e=new Date(1e3*(M[e>>>2]+4294967296*E[e+4>>>2])),E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),E[t+20>>2>>>0]=e.getFullYear()-1900,E[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1);E[t+28>>2>>>0]=(e.getTime()-n.getTime())/864e5|0,E[t+36>>2>>>0]=-60*e.getTimezoneOffset();var r=new Date(e.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[t+32>>2>>>0]=0|(r!=n&&e.getTimezoneOffset()==Math.min(n,r))},O:function(e){var t=new Date(E[e+20>>2>>>0]+1900,E[e+16>>2>>>0],E[e+12>>2>>>0],E[e+8>>2>>>0],E[e+4>>2>>>0],E[e>>2>>>0],0),n=E[e+32>>2>>>0],r=t.getTimezoneOffset(),a=new Date(t.getFullYear(),0,1),o=new Date(t.getFullYear(),6,1).getTimezoneOffset(),i=a.getTimezoneOffset(),s=Math.min(i,o);return 0>n?E[e+32>>2>>>0]=Number(o!=i&&s==r):0<n!=(s==r)&&(o=Math.max(i,o),t.setTime(t.getTime()+6e4*((0<n?s:o)-r))),E[e+24>>2>>>0]=t.getDay(),E[e+28>>2>>>0]=(t.getTime()-a.getTime())/864e5|0,E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},z:function(){return-52},B:function(){},m:function e(t,n,r){e.xa||(e.xa=!0,function(e,t,n){function r(e){return(e=e.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?e[1]:"GMT"}var a=(new Date).getFullYear(),o=new Date(a,0,1),i=new Date(a,6,1);a=o.getTimezoneOffset();var s=i.getTimezoneOffset();E[e>>2>>>0]=60*Math.max(a,s),E[t>>2>>>0]=Number(a!=s),e=r(o),t=r(i),e=Q(e),t=Q(t),s<a?(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t):(M[n>>2>>>0]=t,M[n+4>>2>>>0]=e)}(t,n,r))},d:function(){B("")},t:function(){return 4294901760},h:h?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now(),J:function(e,t,n){A.copyWithin(e>>>0,t>>>0,t+n>>>0)},f:function(e){var t=A.length;if(4294901760<(e>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var a=Math;r=Math.max(e,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);e:{try{O.grow(a-S.byteLength+65535>>>16),F();var o=1;break e}catch(e){}o=void 0}if(o)return!0}return!1},D:function(e,t){var n=0;return K().forEach((function(r,a){var o=t+n;for(a=M[e+4*a>>2>>>0]=o,o=0;o<r.length;++o)T[a++>>0>>>0]=r.charCodeAt(o);T[a>>0>>>0]=0,n+=r.length+1})),0},E:function(e,t){var n=K();M[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),M[t>>2>>>0]=r,0},r:function(e){_||(t.onExit&&t.onExit(e),R=!0),d(e,new $(e))},e:function(){return 52},j:function(){return 52},q:function(){return 70},i:function(e,t,n,r){for(var a=0,o=0;o<n;o++){var i=M[t>>2>>>0],s=M[t+4>>2>>>0];t+=8;for(var u=0;u<s;u++){var c=A[i+u>>>0],l=ee[e];0===c||10===c?((1===e?b:w)(C(l,0)),l.length=0):l.push(c)}a+=s}return M[r>>2>>>0]=a,0},s:function e(t,r){e.wa||(e.wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(h)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>B("randomDevice")}());for(var a=0;a<r;a++)T[t+a>>0>>>0]=e.wa();return 0},A:ae,c:function(e,t,n,r){return ae(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,O=t.asm.P,F(),I.unshift(t.asm.Q),L--,t.monitorRunDependencies&&t.monitorRunDependencies(L),0==L&&(null!==Y&&(clearInterval(Y),Y=null),z&&(e=z,z=null,e()))}function n(t){e(t.instance)}function r(e){return function(){if(!v&&(m||g)){if("function"==typeof fetch&&!H.startsWith("file://"))return fetch(H,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at \'"+H+"\'";return e.arrayBuffer()})).catch((function(){return q()}));if(i)return new Promise((function(e,t){i(H,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return q()}))}().then((function(e){return WebAssembly.instantiate(e,o)})).then((function(e){return e})).then(e,(function(e){w("failed to asynchronously prepare wasm: "+e),B(e)}))}var o={a:oe};if(L++,t.monitorRunDependencies&&t.monitorRunDependencies(L),t.instantiateWasm)try{return t.instantiateWasm(o,e)}catch(e){return w("Module.instantiateWasm callback failed with error: "+e),!1}(v||"function"!=typeof WebAssembly.instantiateStreaming||N()||H.startsWith("file://")||h||"function"!=typeof fetch?r(n):fetch(H,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(n,(function(e){return w("wasm streaming compile failed: "+e),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Q).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.R).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.S).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.T).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.U).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm.V).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.W).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.X).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.Y).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.Z).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm._).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.$).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.aa).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.ba).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.ca).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.da).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.ea).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.fa).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.ga).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.ha).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.ia).apply(null,arguments)};var ie=t._malloc=function(){return(ie=t._malloc=t.asm.ja).apply(null,arguments)};t._free=function(){return(t._free=t.asm.ka).apply(null,arguments)};var se,ue=t.stackSave=function(){return(ue=t.stackSave=t.asm.ma).apply(null,arguments)},ce=t.stackRestore=function(){return(ce=t.stackRestore=t.asm.na).apply(null,arguments)},le=t.stackAlloc=function(){return(le=t.stackAlloc=t.asm.oa).apply(null,arguments)};function fe(){function e(){if(!se&&(se=!0,t.calledRun=!0,!R)){if(V(I),r(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();W.unshift(e)}V(W)}}if(!(0<L)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)j();V(U),0<L||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.___cxa_is_pointer_type=function(){return(t.___cxa_is_pointer_type=t.asm.pa).apply(null,arguments)},t.UTF8ToString=P,t.stringToUTF8=function(e,t,n){return k(e,A,t,n)},t.lengthBytesUTF8=D,t.stackSave=ue,t.stackRestore=ce,t.stackAlloc=le,z=function e(){se||fe(),se||(z=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return fe(),e.ready});e.exports=r},154:e=>{"use strict";e.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},760:()=>{},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},t={};function n(r){var a=t[r];if(void 0!==a)return a.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";const e=n(259),t=n(263);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,t.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(e=>postMessage({type:"init-wasm",err:e})));break;case"init-ort":try{const{numThreads:t,loggingLevel:r}=n.data.in;(0,e.initOrt)(t,r),postMessage({type:"init-ort"})}catch(e){postMessage({type:"init-ort",err:e})}break;case"create_allocate":try{const{model:t}=n.data.in,r=(0,e.createSessionAllocate)(t);postMessage({type:"create_allocate",out:r})}catch(e){postMessage({type:"create_allocate",err:e})}break;case"create_finalize":try{const{modeldata:t,options:r}=n.data.in,a=(0,e.createSessionFinalize)(t,r);postMessage({type:"create_finalize",out:a})}catch(e){postMessage({type:"create_finalize",err:e})}break;case"create":try{const{model:t,options:r}=n.data.in,a=(0,e.createSession)(t,r);postMessage({type:"create",out:a})}catch(e){postMessage({type:"create",err:e})}break;case"release":try{const t=n.data.in;(0,e.releaseSession)(t),postMessage({type:"release"})}catch(e){postMessage({type:"release",err:e})}break;case"run":try{const{sessionId:t,inputIndices:r,inputs:a,outputIndices:o,options:i}=n.data.in;(0,e.run)(t,r,a,o,i).then((t=>{postMessage({type:"run",out:t},(0,e.extractTransferableBuffers)(t))}),(e=>{postMessage({type:"run",err:e})}))}catch(e){postMessage({type:"run",err:e})}break;case"end-profiling":try{const t=n.data.in;(0,e.endProfiling)(t),postMessage({type:"end-profiling"})}catch(e){postMessage({type:"end-profiling",err:e})}}}})()})();\n',"Worker",void 0,void 0)}},6614:e=>{"use strict";e.exports=function(e,t,n,r){var i=self||window;try{try{var o;try{o=new i.Blob([e])}catch(t){(o=new(i.BlobBuilder||i.WebKitBlobBuilder||i.MozBlobBuilder||i.MSBlobBuilder)).append(e),o=o.getBlob()}var s=i.URL||i.webkitURL,a=s.createObjectURL(o),u=new i[t](a,n);return s.revokeObjectURL(a),u}catch(r){return new i[t]("data:application/javascript,".concat(encodeURIComponent(e)),n)}}catch(e){if(!r)throw Error("Inline worker is not supported");return new i[t](r,n)}}},3474:(e,t,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){function t(){return M.buffer!=D&&W(M.buffer),$}function i(){return M.buffer!=D&&W(M.buffer),L}function o(){return M.buffer!=D&&W(M.buffer),F}function s(){return M.buffer!=D&&W(M.buffer),U}function a(){return M.buffer!=D&&W(M.buffer),N}var u,l,c;e=e||{},u||(u=void 0!==e?e:{}),u.ready=new Promise((function(e,t){l=e,c=t}));var d,h,p,f,g,m,b=Object.assign({},u),y="./this.program",v=(e,t)=>{throw t},w="object"==typeof window,S="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,T=u.ENVIRONMENT_IS_PTHREAD||!1,x="";function E(e){return u.locateFile?u.locateFile(e,x):x+e}if(_){let t;x=S?n(908).dirname(x)+"/":"//",m=()=>{g||(f=n(1384),g=n(908))},d=function(e,t){return m(),e=g.normalize(e),f.readFileSync(e,t?void 0:"utf8")},p=e=>((e=d(e,!0)).buffer||(e=new Uint8Array(e)),e),h=(e,t,n)=>{m(),e=g.normalize(e),f.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(y=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof ae))throw e})),process.on("unhandledRejection",(function(e){throw e})),v=(e,t)=>{if(I)throw process.exitCode=e,t;t instanceof ae||k("exiting due to exception: "+t),process.exit(e)},u.inspect=function(){return"[Emscripten Module object]"};try{t=n(9925)}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}n.g.Worker=t.Worker}else(w||S)&&(S?x=self.location.href:"undefined"!=typeof document&&document.currentScript&&(x=document.currentScript.src),r&&(x=r),x=0!==x.indexOf("blob:")?x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(d=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},S&&(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),h=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var C=console.log.bind(console),P=console.warn.bind(console);_&&(m(),C=e=>f.writeSync(1,e+"\n"),P=e=>f.writeSync(2,e+"\n"));var O,A=u.print||C,k=u.printErr||P;Object.assign(u,b),b=null,u.thisProgram&&(y=u.thisProgram),u.quit&&(v=u.quit),u.wasmBinary&&(O=u.wasmBinary);var I=u.noExitRuntime||!0;"object"!=typeof WebAssembly&&re("no native wasm support detected");var M,R,D,$,L,F,U,N,j=!1,B="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&B)return B.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,n):e.subarray(t,n));for(r="";t<n;){var i=e[t++];if(128&i){var o=63&e[t++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var s=63&e[t++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function V(e,t){return(e>>>=0)?z(i(),e,t):""}function G(e,t,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var s=e.charCodeAt(o);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-i}function H(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function W(e){D=e,u.HEAP8=$=new Int8Array(e),u.HEAP16=new Int16Array(e),u.HEAP32=F=new Int32Array(e),u.HEAPU8=L=new Uint8Array(e),u.HEAPU16=new Uint16Array(e),u.HEAPU32=U=new Uint32Array(e),u.HEAPF32=new Float32Array(e),u.HEAPF64=N=new Float64Array(e)}T&&(D=u.buffer);var q=u.INITIAL_MEMORY||16777216;if(T)M=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)M=u.wasmMemory;else if(!((M=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw k("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");M&&(D=M.buffer),q=D.byteLength,W(D);var K,X=[],J=[],Q=[];function Y(){var e=u.preRun.shift();X.unshift(e)}var Z,ee=0,te=null,ne=null;function re(e){throw T?postMessage({cmd:"onAbort",arg:e}):u.onAbort&&u.onAbort(e),k(e="Aborted("+e+")"),j=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),c(e),e}function ie(){return Z.startsWith("data:application/octet-stream;base64,")}function oe(){var e=Z;try{if(e==Z&&O)return new Uint8Array(O);if(p)return p(e);throw"both async and sync fetching of the wasm failed"}catch(e){re(e)}}Z="ort-wasm-threaded.wasm",ie()||(Z=E(Z));var se={};function ae(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ue(e){(e=he.La[e])||re(),he.Xa(e)}function le(e){var t=he.lb();if(!t)return 6;he.Ra.push(t),he.La[e.Ka]=t,t.Ka=e.Ka;var n={cmd:"run",start_routine:e.pb,arg:e.ib,pthread_ptr:e.Ka};return t.Qa=()=>{n.time=performance.now(),t.postMessage(n,e.vb)},t.loaded&&(t.Qa(),delete t.Qa),0}function ce(e){if(T)return je(1,1,e);I||(he.qb(),u.onExit&&u.onExit(e),j=!0),v(e,new ae(e))}function de(e,t){if(!t&&T)throw fe(e),"unwind";ce(e)}var he={Oa:[],Ra:[],$a:[],La:{},Ua:function(){T&&he.mb()},xb:function(){},mb:function(){he.receiveObjectTransfer=he.ob,he.threadInitTLS=he.Za,he.setExitStatus=he.Ya,I=!1},Ya:function(){},qb:function(){for(var e of Object.values(he.La))he.Xa(e);for(e of he.Oa)e.terminate();he.Oa=[]},Xa:function(e){var t=e.Ka;delete he.La[t],he.Oa.push(e),he.Ra.splice(he.Ra.indexOf(e),1),e.Ka=0,ct(t)},ob:function(){},Za:function(){he.$a.forEach((e=>e()))},nb:function(e,t){e.onmessage=n=>{var r=(n=n.data).cmd;if(e.Ka&&(he.kb=e.Ka),n.targetThread&&n.targetThread!=it()){var i=he.La[n.yb];i?i.postMessage(n,n.transferList):k('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?De(n.queue):"spawnThread"===r?le(n):"cleanupThread"===r?ue(n.thread):"killThread"===r?(n=n.thread,r=he.La[n],delete he.La[n],r.terminate(),ct(n),he.Ra.splice(he.Ra.indexOf(r),1),r.Ka=0):"cancelThread"===r?he.La[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,t&&t(e),e.Qa&&(e.Qa(),delete e.Qa)):"print"===r?A("Thread "+n.threadId+": "+n.text):"printErr"===r?k("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?e.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&k("worker sent an unknown command "+r);he.kb=void 0},e.onerror=e=>{throw k("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},_&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){}))),e.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:M,wasmModule:R})},hb:function(){var e=E("ort-wasm-threaded.worker.js");he.Oa.push(new Worker(e))},lb:function(){return 0==he.Oa.length&&(he.hb(),he.nb(he.Oa[0])),he.Oa.pop()}};function pe(e){for(;0<e.length;)e.shift()(u)}function fe(e){if(T)return je(2,0,e);try{de(e)}catch(e){e instanceof ae||"unwind"==e||v(1,e)}}u.PThread=he,u.establishStackSpace=function(){var e=it(),t=o()[e+44>>2>>>0];e=o()[e+48>>2>>>0],ht(t,t-e),ft(t)};var ge,me,be=[];function ye(e){this.Pa=e-24,this.gb=function(e){s()[this.Pa+4>>2>>>0]=e},this.cb=function(e){s()[this.Pa+8>>2>>>0]=e},this.eb=function(){o()[this.Pa>>2>>>0]=0},this.bb=function(){t()[(this.Pa+12|0)>>>0]=0},this.fb=function(){t()[(this.Pa+13|0)>>>0]=0},this.Ua=function(e,t){this.ab(),this.gb(e),this.cb(t),this.eb(),this.bb(),this.fb()},this.ab=function(){s()[this.Pa+16>>2>>>0]=0}}function ve(e,t,n,r){return T?je(3,1,e,t,n,r):we(e,t,n,r)}function we(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return k("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return T&&0===i.length?ve(e,t,n,r):(e={pb:n,Ka:e,ib:r,vb:i},T?(e.wb="spawnThread",postMessage(e,i),0):le(e))}function Se(e,t,n){return T?je(4,1,e,t,n):0}function _e(e,t){if(T)return je(5,1,e,t)}function Te(e,t){if(T)return je(6,1,e,t)}function xe(e,t,n){if(T)return je(7,1,e,t,n)}function Ee(e,t,n){return T?je(8,1,e,t,n):0}function Ce(e,t){if(T)return je(9,1,e,t)}function Pe(e,t,n){if(T)return je(10,1,e,t,n)}function Oe(e,t,n,r){if(T)return je(11,1,e,t,n,r)}function Ae(e,t,n,r){if(T)return je(12,1,e,t,n,r)}function ke(e,t,n,r){if(T)return je(13,1,e,t,n,r)}function Ie(e){if(T)return je(14,1,e)}function Me(e,t){if(T)return je(15,1,e,t)}function Re(e,t,n){if(T)return je(16,1,e,t,n)}function De(e){Atomics.store(o(),e>>2,1),it()&&lt(e),Atomics.compareExchange(o(),e>>2,1,0)}function $e(e){return s()[e>>>2]+4294967296*o()[e+4>>>2]}function Le(e,t,n,r,i,o){return T?je(17,1,e,t,n,r,i,o):-52}function Fe(e,t,n,r,i,o){if(T)return je(18,1,e,t,n,r,i,o)}function Ue(e){var n=H(e)+1,r=ot(n);return r&&G(e,t(),r,n),r}function Ne(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}if(T)return je(19,1,e,t,n);var i=(new Date).getFullYear(),a=new Date(i,0,1),u=new Date(i,6,1);i=a.getTimezoneOffset();var l=u.getTimezoneOffset(),c=Math.max(i,l);o()[e>>2>>>0]=60*c,o()[t>>2>>>0]=Number(i!=l),e=r(a),t=r(u),e=Ue(e),t=Ue(t),l<i?(s()[n>>2>>>0]=e,s()[n+4>>2>>>0]=t):(s()[n>>2>>>0]=t,s()[n+4>>2>>>0]=e)}function je(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=pt();return e=e(),ft(t),e}((()=>{for(var i=gt(8*n),o=i>>3,s=0;s<n;s++){var u=r[2+s];a()[o+s>>>0]=u}return ut(e,n,i,t)}))}u.invokeEntryPoint=function(e,t){var n=be[e];n||(e>=be.length&&(be.length=e+1),be[e]=n=K.get(e)),e=n(t),I?he.Ya(e):dt(e)},u.executeNotifiedProxyingQueue=De,me=_?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:T?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var Be,ze=[],Ve={};function Ge(){if(!Be){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:y||"./this.program"};for(e in Ve)void 0===Ve[e]?delete t[e]:t[e]=Ve[e];var n=[];for(e in t)n.push(e+"="+t[e]);Be=n}return Be}function He(e,n){if(T)return je(20,1,e,n);var r=0;return Ge().forEach((function(i,o){var a=n+r;for(o=s()[e+4*o>>2>>>0]=a,a=0;a<i.length;++a)t()[(0|o++)>>>0]=i.charCodeAt(a);t()[(0|o)>>>0]=0,r+=i.length+1})),0}function We(e,t){if(T)return je(21,1,e,t);var n=Ge();s()[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),s()[t>>2>>>0]=r,0}function qe(e){return T?je(22,1,e):52}function Ke(e,t,n,r){return T?je(23,1,e,t,n,r):52}function Xe(e,t,n,r,i){return T?je(24,1,e,t,n,r,i):70}var Je=[null,[],[]];function Qe(e,t,n,r){if(T)return je(25,1,e,t,n,r);for(var o=0,a=0;a<n;a++){var u=s()[t>>2>>>0],l=s()[t+4>>2>>>0];t+=8;for(var c=0;c<l;c++){var d=i()[u+c>>>0],h=Je[e];0===d||10===d?((1===e?A:k)(z(h,0)),h.length=0):h.push(d)}o+=l}return s()[r>>2>>>0]=o,0}function Ye(e){return 0==e%4&&(0!=e%100||0==e%400)}var Ze=[31,29,31,30,31,30,31,31,30,31,30,31],et=[31,28,31,30,31,30,31,31,30,31,30,31];function tt(e,n,r,i){function s(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function a(e,t){return s(e,t,"0")}function u(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function l(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function c(e){var t=e.Ma;for(e=new Date(new Date(e.Na+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(Ye(e.getFullYear())?Ze:et)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=l(new Date(e.getFullYear(),0,4)),n=l(n),0>=u(t,e)?0>=u(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var d=o()[i+40>>2>>>0];for(var h in i={tb:o()[i>>2>>>0],sb:o()[i+4>>2>>>0],Sa:o()[i+8>>2>>>0],Va:o()[i+12>>2>>>0],Ta:o()[i+16>>2>>>0],Na:o()[i+20>>2>>>0],Ja:o()[i+24>>2>>>0],Ma:o()[i+28>>2>>>0],zb:o()[i+32>>2>>>0],rb:o()[i+36>>2>>>0],ub:d?V(d):""},r=V(r),d={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(h,"g"),d[h]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),f="January February March April May June July August September October November December".split(" ");for(h in d={"%a":function(e){return p[e.Ja].substring(0,3)},"%A":function(e){return p[e.Ja]},"%b":function(e){return f[e.Ta].substring(0,3)},"%B":function(e){return f[e.Ta]},"%C":function(e){return a((e.Na+1900)/100|0,2)},"%d":function(e){return a(e.Va,2)},"%e":function(e){return s(e.Va,2," ")},"%g":function(e){return c(e).toString().substring(2)},"%G":function(e){return c(e)},"%H":function(e){return a(e.Sa,2)},"%I":function(e){return 0==(e=e.Sa)?e=12:12<e&&(e-=12),a(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.Ta-1;t+=(Ye(e.Na+1900)?Ze:et)[n++]);return a(e.Va+t,3)},"%m":function(e){return a(e.Ta+1,2)},"%M":function(e){return a(e.sb,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.Sa&&12>e.Sa?"AM":"PM"},"%S":function(e){return a(e.tb,2)},"%t":function(){return"\t"},"%u":function(e){return e.Ja||7},"%U":function(e){return a(Math.floor((e.Ma+7-e.Ja)/7),2)},"%V":function(e){var t=Math.floor((e.Ma+7-(e.Ja+6)%7)/7);if(2>=(e.Ja+371-e.Ma-2)%7&&t++,t)53==t&&(4==(n=(e.Ja+371-e.Ma)%7)||3==n&&Ye(e.Na)||(t=1));else{t=52;var n=(e.Ja+7-e.Ma-1)%7;(4==n||5==n&&Ye(e.Na%400-1))&&t++}return a(t,2)},"%w":function(e){return e.Ja},"%W":function(e){return a(Math.floor((e.Ma+7-(e.Ja+6)%7)/7),2)},"%y":function(e){return(e.Na+1900).toString().substring(2)},"%Y":function(e){return e.Na+1900},"%z":function(e){var t=0<=(e=e.rb);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.ub},"%%":function(){return"%"}},r=r.replace(/%%/g,"\0\0"),d)r.includes(h)&&(r=r.replace(new RegExp(h,"g"),d[h](i)));return h=function(e){var t=Array(H(e)+1);return G(e,t,0,t.length),t}(r=r.replace(/\0\0/g,"%")),h.length>n?0:(function(e,n){t().set(e,n>>>0)}(h,e),h.length-1)}he.Ua();var nt=[null,ce,fe,ve,Se,_e,Te,xe,Ee,Ce,Pe,Oe,Ae,ke,Ie,Me,Re,Le,Fe,Ne,He,We,qe,Ke,Xe,Qe],rt={b:function(e){return ot(e+24)+24},c:function(e,t,n){throw new ye(e).Ua(t,n),e},L:function(e){st(e,!S,1,!w),he.Za()},l:function(e){T?postMessage({cmd:"cleanupThread",thread:e}):ue(e)},D:we,i:Se,R:_e,z:Te,B:xe,T:Ee,P:Ce,I:Pe,O:Oe,p:Ae,A:ke,x:Ie,Q:Me,y:Re,r:function(){},j:function(){re("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},s:function(){re("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},q:function(){return Date.now()},E:function(){return 2097152},V:function(){return!0},F:function(e,t,n,r){if(e==t)setTimeout((()=>De(r)));else if(T)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{if(!(e=he.La[e]))return;e.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},K:function(){return-1},W:function(e,t){e=new Date(1e3*$e(e)),o()[t>>2>>>0]=e.getUTCSeconds(),o()[t+4>>2>>>0]=e.getUTCMinutes(),o()[t+8>>2>>>0]=e.getUTCHours(),o()[t+12>>2>>>0]=e.getUTCDate(),o()[t+16>>2>>>0]=e.getUTCMonth(),o()[t+20>>2>>>0]=e.getUTCFullYear()-1900,o()[t+24>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[t+28>>2>>>0]=e},X:function(e,t){e=new Date(1e3*$e(e)),o()[t>>2>>>0]=e.getSeconds(),o()[t+4>>2>>>0]=e.getMinutes(),o()[t+8>>2>>>0]=e.getHours(),o()[t+12>>2>>>0]=e.getDate(),o()[t+16>>2>>>0]=e.getMonth(),o()[t+20>>2>>>0]=e.getFullYear()-1900,o()[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1),r=(e.getTime()-n.getTime())/864e5|0;o()[t+28>>2>>>0]=r,o()[t+36>>2>>>0]=-60*e.getTimezoneOffset(),r=new Date(e.getFullYear(),6,1).getTimezoneOffset(),e=0|(r!=(n=n.getTimezoneOffset())&&e.getTimezoneOffset()==Math.min(n,r)),o()[t+32>>2>>>0]=e},Y:function(e){var t=new Date(o()[e+20>>2>>>0]+1900,o()[e+16>>2>>>0],o()[e+12>>2>>>0],o()[e+8>>2>>>0],o()[e+4>>2>>>0],o()[e>>2>>>0],0),n=o()[e+32>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),0,1),s=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=i.getTimezoneOffset(),u=Math.min(a,s);return 0>n?o()[e+32>>2>>>0]=Number(s!=a&&u==r):0<n!=(u==r)&&(s=Math.max(a,s),t.setTime(t.getTime()+6e4*((0<n?u:s)-r))),o()[e+24>>2>>>0]=t.getDay(),n=(t.getTime()-i.getTime())/864e5|0,o()[e+28>>2>>>0]=n,o()[e>>2>>>0]=t.getSeconds(),o()[e+4>>2>>>0]=t.getMinutes(),o()[e+8>>2>>>0]=t.getHours(),o()[e+12>>2>>>0]=t.getDate(),o()[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},G:Le,H:Fe,Z:function e(t,n,r){e.jb||(e.jb=!0,Ne(t,n,r))},d:function(){re("")},m:function(){if(!_&&!S){var e="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";ge||(ge={}),ge[e]||(ge[e]=1,_&&(e="warning: "+e),k(e))}},w:function(){return 4294901760},f:me,S:function(e,t,n){i().copyWithin(e>>>0,t>>>0,t+n>>>0)},g:function(){return _?n(3993).cpus().length:navigator.hardwareConcurrency},J:function(e,t,n){ze.length=t,n>>=3;for(var r=0;r<t;r++)ze[r]=a()[n+r>>>0];return(0>e?se[-e-1]:nt[e]).apply(null,ze)},v:function(e){var t=i().length;if((e>>>=0)<=t||4294901760<e)return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var o=Math;r=Math.max(e,r),o=o.min.call(o,4294901760,r+(65536-r%65536)%65536);e:{try{M.grow(o-D.byteLength+65535>>>16),W(M.buffer);var s=1;break e}catch(e){}s=void 0}if(s)return!0}return!1},U:function(){throw"unwind"},M:He,N:We,k:de,h:qe,o:Ke,t:Xe,n:Qe,u:function e(r,i){e.Wa||(e.Wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(_)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>re("randomDevice")}());for(var o=0;o<i;o++)t()[(r+o|0)>>>0]=e.Wa();return 0},a:M||u.wasmMemory,C:tt,e:function(e,t,n,r){return tt(e,t,n,r)}};!function(){function e(e,t){u.asm=e.exports,he.$a.push(u.asm.wa),K=u.asm.za,J.unshift(u.asm._),R=t,T||(ee--,u.monitorRunDependencies&&u.monitorRunDependencies(ee),0==ee&&(null!==te&&(clearInterval(te),te=null),ne&&(e=ne,ne=null,e())))}function t(t){e(t.instance,t.module)}function n(e){return function(){if(!O&&(w||S)){if("function"==typeof fetch&&!Z.startsWith("file://"))return fetch(Z,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+Z+"'";return e.arrayBuffer()})).catch((function(){return oe()}));if(h)return new Promise((function(e,t){h(Z,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return oe()}))}().then((function(e){return WebAssembly.instantiate(e,r)})).then((function(e){return e})).then(e,(function(e){k("failed to asynchronously prepare wasm: "+e),re(e)}))}var r={a:rt};if(T||(ee++,u.monitorRunDependencies&&u.monitorRunDependencies(ee)),u.instantiateWasm)try{return u.instantiateWasm(r,e)}catch(e){return k("Module.instantiateWasm callback failed with error: "+e),!1}(O||"function"!=typeof WebAssembly.instantiateStreaming||ie()||Z.startsWith("file://")||_||"function"!=typeof fetch?n(t):fetch(Z,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(t,(function(e){return k("wasm streaming compile failed: "+e),k("falling back to ArrayBuffer instantiation"),n(t)}))}))).catch(c)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm._).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.$).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.aa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.ba).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.ca).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm.da).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.ea).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.fa).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.ga).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.ha).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.ia).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.ja).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.ka).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.la).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.ma).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.na).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.oa).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.pa).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.qa).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.ra).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.sa).apply(null,arguments)};var it=u._pthread_self=function(){return(it=u._pthread_self=u.asm.ta).apply(null,arguments)},ot=u._malloc=function(){return(ot=u._malloc=u.asm.ua).apply(null,arguments)};u._free=function(){return(u._free=u.asm.va).apply(null,arguments)},u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.wa).apply(null,arguments)};var st=u.__emscripten_thread_init=function(){return(st=u.__emscripten_thread_init=u.asm.xa).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.ya).apply(null,arguments)};var at,ut=u._emscripten_run_in_main_runtime_thread_js=function(){return(ut=u._emscripten_run_in_main_runtime_thread_js=u.asm.Aa).apply(null,arguments)},lt=u.__emscripten_proxy_execute_task_queue=function(){return(lt=u.__emscripten_proxy_execute_task_queue=u.asm.Ba).apply(null,arguments)},ct=u.__emscripten_thread_free_data=function(){return(ct=u.__emscripten_thread_free_data=u.asm.Ca).apply(null,arguments)},dt=u.__emscripten_thread_exit=function(){return(dt=u.__emscripten_thread_exit=u.asm.Da).apply(null,arguments)},ht=u._emscripten_stack_set_limits=function(){return(ht=u._emscripten_stack_set_limits=u.asm.Ea).apply(null,arguments)},pt=u.stackSave=function(){return(pt=u.stackSave=u.asm.Fa).apply(null,arguments)},ft=u.stackRestore=function(){return(ft=u.stackRestore=u.asm.Ga).apply(null,arguments)},gt=u.stackAlloc=function(){return(gt=u.stackAlloc=u.asm.Ha).apply(null,arguments)};function mt(){function e(){if(!at&&(at=!0,u.calledRun=!0,!j)&&(T||pe(J),l(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!T)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var e=u.postRun.shift();Q.unshift(e)}pe(Q)}}if(!(0<ee))if(T)l(u),T||pe(J),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)Y();pe(X),0<ee||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),e()}),1)):e())}}if(u.___cxa_is_pointer_type=function(){return(u.___cxa_is_pointer_type=u.asm.Ia).apply(null,arguments)},u.UTF8ToString=V,u.stringToUTF8=function(e,t,n){return G(e,i(),t,n)},u.lengthBytesUTF8=H,u.keepRuntimeAlive=function(){return I},u.wasmMemory=M,u.stackSave=pt,u.stackRestore=ft,u.stackAlloc=gt,u.ExitStatus=ae,u.PThread=he,ne=function e(){at||mt(),at||(ne=e)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return mt(),e.ready});e.exports=i},932:(e,t,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,i,o;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){i=e,o=t}));var s,a,u,l,c,d,h=Object.assign({},t),p="./this.program",f=(e,t)=>{throw t},g="object"==typeof window,m="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,y="";b?(y=m?n(908).dirname(y)+"/":"//",d=()=>{c||(l=n(1384),c=n(908))},s=function(e,t){return d(),e=c.normalize(e),l.readFileSync(e,t?void 0:"utf8")},u=e=>((e=s(e,!0)).buffer||(e=new Uint8Array(e)),e),a=(e,t,n)=>{d(),e=c.normalize(e),l.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof K))throw e})),process.on("unhandledRejection",(function(e){throw e})),f=(e,t)=>{if(_)throw process.exitCode=e,t;t instanceof K||S("exiting due to exception: "+t),process.exit(e)},t.inspect=function(){return"[Emscripten Module object]"}):(g||m)&&(m?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),r&&(y=r),y=0!==y.indexOf("blob:")?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},m&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),a=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var v,w=t.print||console.log.bind(console),S=t.printErr||console.warn.bind(console);Object.assign(t,h),h=null,t.thisProgram&&(p=t.thisProgram),t.quit&&(f=t.quit),t.wasmBinary&&(v=t.wasmBinary);var _=t.noExitRuntime||!0;"object"!=typeof WebAssembly&&G("no native wasm support detected");var T,x,E,C,P,O,A=!1,k="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function I(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&k)return k.decode(e.subarray(t,n));for(r="";t<n;){var i=e[t++];if(128&i){var o=63&e[t++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var s=63&e[t++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function M(e,t){return(e>>>=0)?I(C,e,t):""}function R(e,t,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var s=e.charCodeAt(o);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-i}function D(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function $(){var e=T.buffer;x=e,t.HEAP8=E=new Int8Array(e),t.HEAP16=new Int16Array(e),t.HEAP32=P=new Int32Array(e),t.HEAPU8=C=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=O=new Uint32Array(e),t.HEAPF32=new Float32Array(e),t.HEAPF64=new Float64Array(e)}var L=[],F=[],U=[];function N(){var e=t.preRun.shift();L.unshift(e)}var j,B=0,z=null,V=null;function G(e){throw t.onAbort&&t.onAbort(e),S(e="Aborted("+e+")"),A=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),o(e),e}function H(){return j.startsWith("data:application/octet-stream;base64,")}if(j="ort-wasm.wasm",!H()){var W=j;j=t.locateFile?t.locateFile(W,y):y+W}function q(){var e=j;try{if(e==j&&v)return new Uint8Array(v);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){G(e)}}function K(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function X(e){for(;0<e.length;)e.shift()(t)}function J(e){this.sa=e-24,this.Ia=function(e){O[this.sa+4>>2>>>0]=e},this.Ba=function(e){O[this.sa+8>>2>>>0]=e},this.Ga=function(){P[this.sa>>2>>>0]=0},this.Aa=function(){E[(this.sa+12|0)>>>0]=0},this.Ha=function(){E[(this.sa+13|0)>>>0]=0},this.ya=function(e,t){this.za(),this.Ia(e),this.Ba(t),this.Ga(),this.Aa(),this.Ha()},this.za=function(){O[this.sa+16>>2>>>0]=0}}function Q(e){var t=D(e)+1,n=ae(t);return n&&R(e,E,n,t),n}var Y={};function Z(){if(!ee){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(e in Y)void 0===Y[e]?delete t[e]:t[e]=Y[e];var n=[];for(e in t)n.push(e+"="+t[e]);ee=n}return ee}var ee,te=[null,[],[]];function ne(e){return 0==e%4&&(0!=e%100||0==e%400)}var re=[31,29,31,30,31,30,31,31,30,31,30,31],ie=[31,28,31,30,31,30,31,31,30,31,30,31];function oe(e,t,n,r){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function o(e,t){return i(e,t,"0")}function s(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function a(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.qa;for(e=new Date(new Date(e.ra+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(ne(e.getFullYear())?re:ie)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=a(new Date(e.getFullYear(),0,4)),n=a(n),0>=s(t,e)?0>=s(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var l=P[r+40>>2>>>0];for(var c in r={Ea:P[r>>2>>>0],Da:P[r+4>>2>>>0],ta:P[r+8>>2>>>0],va:P[r+12>>2>>>0],ua:P[r+16>>2>>>0],ra:P[r+20>>2>>>0],la:P[r+24>>2>>>0],qa:P[r+28>>2>>>0],Ja:P[r+32>>2>>>0],Ca:P[r+36>>2>>>0],Fa:l?M(l):""},n=M(n),l={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(c,"g"),l[c]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),h="January February March April May June July August September October November December".split(" ");for(c in l={"%a":function(e){return d[e.la].substring(0,3)},"%A":function(e){return d[e.la]},"%b":function(e){return h[e.ua].substring(0,3)},"%B":function(e){return h[e.ua]},"%C":function(e){return o((e.ra+1900)/100|0,2)},"%d":function(e){return o(e.va,2)},"%e":function(e){return i(e.va,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return o(e.ta,2)},"%I":function(e){return 0==(e=e.ta)?e=12:12<e&&(e-=12),o(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.ua-1;t+=(ne(e.ra+1900)?re:ie)[n++]);return o(e.va+t,3)},"%m":function(e){return o(e.ua+1,2)},"%M":function(e){return o(e.Da,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.ta&&12>e.ta?"AM":"PM"},"%S":function(e){return o(e.Ea,2)},"%t":function(){return"\t"},"%u":function(e){return e.la||7},"%U":function(e){return o(Math.floor((e.qa+7-e.la)/7),2)},"%V":function(e){var t=Math.floor((e.qa+7-(e.la+6)%7)/7);if(2>=(e.la+371-e.qa-2)%7&&t++,t)53==t&&(4==(n=(e.la+371-e.qa)%7)||3==n&&ne(e.ra)||(t=1));else{t=52;var n=(e.la+7-e.qa-1)%7;(4==n||5==n&&ne(e.ra%400-1))&&t++}return o(t,2)},"%w":function(e){return e.la},"%W":function(e){return o(Math.floor((e.qa+7-(e.la+6)%7)/7),2)},"%y":function(e){return(e.ra+1900).toString().substring(2)},"%Y":function(e){return e.ra+1900},"%z":function(e){var t=0<=(e=e.Ca);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.Fa},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),l)n.includes(c)&&(n=n.replace(new RegExp(c,"g"),l[c](r)));return c=function(e){var t=Array(D(e)+1);return R(e,t,0,t.length),t}(n=n.replace(/\0\0/g,"%")),c.length>t?0:(E.set(c,e>>>0),c.length-1)}var se={a:function(e){return ae(e+24)+24},b:function(e,t,n){throw new J(e).ya(t,n),e},g:function(){return 0},I:function(){},w:function(){},y:function(){},K:function(){return 0},G:function(){},C:function(){},F:function(){},k:function(){},x:function(){},u:function(){},H:function(){},v:function(){},n:function(){},p:function(){G("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},o:function(){G("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},l:function(){return Date.now()},L:function(){return!0},M:function(e,t){e=new Date(1e3*(O[e>>>2]+4294967296*P[e+4>>>2])),P[t>>2>>>0]=e.getUTCSeconds(),P[t+4>>2>>>0]=e.getUTCMinutes(),P[t+8>>2>>>0]=e.getUTCHours(),P[t+12>>2>>>0]=e.getUTCDate(),P[t+16>>2>>>0]=e.getUTCMonth(),P[t+20>>2>>>0]=e.getUTCFullYear()-1900,P[t+24>>2>>>0]=e.getUTCDay(),P[t+28>>2>>>0]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},N:function(e,t){e=new Date(1e3*(O[e>>>2]+4294967296*P[e+4>>>2])),P[t>>2>>>0]=e.getSeconds(),P[t+4>>2>>>0]=e.getMinutes(),P[t+8>>2>>>0]=e.getHours(),P[t+12>>2>>>0]=e.getDate(),P[t+16>>2>>>0]=e.getMonth(),P[t+20>>2>>>0]=e.getFullYear()-1900,P[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1);P[t+28>>2>>>0]=(e.getTime()-n.getTime())/864e5|0,P[t+36>>2>>>0]=-60*e.getTimezoneOffset();var r=new Date(e.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),P[t+32>>2>>>0]=0|(r!=n&&e.getTimezoneOffset()==Math.min(n,r))},O:function(e){var t=new Date(P[e+20>>2>>>0]+1900,P[e+16>>2>>>0],P[e+12>>2>>>0],P[e+8>>2>>>0],P[e+4>>2>>>0],P[e>>2>>>0],0),n=P[e+32>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),0,1),o=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=i.getTimezoneOffset(),a=Math.min(s,o);return 0>n?P[e+32>>2>>>0]=Number(o!=s&&a==r):0<n!=(a==r)&&(o=Math.max(s,o),t.setTime(t.getTime()+6e4*((0<n?a:o)-r))),P[e+24>>2>>>0]=t.getDay(),P[e+28>>2>>>0]=(t.getTime()-i.getTime())/864e5|0,P[e>>2>>>0]=t.getSeconds(),P[e+4>>2>>>0]=t.getMinutes(),P[e+8>>2>>>0]=t.getHours(),P[e+12>>2>>>0]=t.getDate(),P[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},z:function(){return-52},B:function(){},m:function e(t,n,r){e.xa||(e.xa=!0,function(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}var i=(new Date).getFullYear(),o=new Date(i,0,1),s=new Date(i,6,1);i=o.getTimezoneOffset();var a=s.getTimezoneOffset();P[e>>2>>>0]=60*Math.max(i,a),P[t>>2>>>0]=Number(i!=a),e=r(o),t=r(s),e=Q(e),t=Q(t),a<i?(O[n>>2>>>0]=e,O[n+4>>2>>>0]=t):(O[n>>2>>>0]=t,O[n+4>>2>>>0]=e)}(t,n,r))},d:function(){G("")},t:function(){return 4294901760},h:b?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now(),J:function(e,t,n){C.copyWithin(e>>>0,t>>>0,t+n>>>0)},f:function(e){var t=C.length;if(4294901760<(e>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var i=Math;r=Math.max(e,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);e:{try{T.grow(i-x.byteLength+65535>>>16),$();var o=1;break e}catch(e){}o=void 0}if(o)return!0}return!1},D:function(e,t){var n=0;return Z().forEach((function(r,i){var o=t+n;for(i=O[e+4*i>>2>>>0]=o,o=0;o<r.length;++o)E[(0|i++)>>>0]=r.charCodeAt(o);E[(0|i)>>>0]=0,n+=r.length+1})),0},E:function(e,t){var n=Z();O[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),O[t>>2>>>0]=r,0},r:function(e){_||(t.onExit&&t.onExit(e),A=!0),f(e,new K(e))},e:function(){return 52},j:function(){return 52},q:function(){return 70},i:function(e,t,n,r){for(var i=0,o=0;o<n;o++){var s=O[t>>2>>>0],a=O[t+4>>2>>>0];t+=8;for(var u=0;u<a;u++){var l=C[s+u>>>0],c=te[e];0===l||10===l?((1===e?w:S)(I(c,0)),c.length=0):c.push(l)}i+=a}return O[r>>2>>>0]=i,0},s:function e(t,r){e.wa||(e.wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(b)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>G("randomDevice")}());for(var i=0;i<r;i++)E[(t+i|0)>>>0]=e.wa();return 0},A:oe,c:function(e,t,n,r){return oe(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,T=t.asm.P,$(),F.unshift(t.asm.Q),B--,t.monitorRunDependencies&&t.monitorRunDependencies(B),0==B&&(null!==z&&(clearInterval(z),z=null),V&&(e=V,V=null,e()))}function n(t){e(t.instance)}function r(e){return function(){if(!v&&(g||m)){if("function"==typeof fetch&&!j.startsWith("file://"))return fetch(j,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+j+"'";return e.arrayBuffer()})).catch((function(){return q()}));if(a)return new Promise((function(e,t){a(j,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return q()}))}().then((function(e){return WebAssembly.instantiate(e,i)})).then((function(e){return e})).then(e,(function(e){S("failed to asynchronously prepare wasm: "+e),G(e)}))}var i={a:se};if(B++,t.monitorRunDependencies&&t.monitorRunDependencies(B),t.instantiateWasm)try{return t.instantiateWasm(i,e)}catch(e){return S("Module.instantiateWasm callback failed with error: "+e),!1}(v||"function"!=typeof WebAssembly.instantiateStreaming||H()||j.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(j,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,i).then(n,(function(e){return S("wasm streaming compile failed: "+e),S("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(o)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Q).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.R).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.S).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.T).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.U).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm.V).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.W).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.X).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.Y).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.Z).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm._).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.$).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.aa).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.ba).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.ca).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.da).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.ea).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.fa).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.ga).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.ha).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.ia).apply(null,arguments)};var ae=t._malloc=function(){return(ae=t._malloc=t.asm.ja).apply(null,arguments)};t._free=function(){return(t._free=t.asm.ka).apply(null,arguments)};var ue,le=t.stackSave=function(){return(le=t.stackSave=t.asm.ma).apply(null,arguments)},ce=t.stackRestore=function(){return(ce=t.stackRestore=t.asm.na).apply(null,arguments)},de=t.stackAlloc=function(){return(de=t.stackAlloc=t.asm.oa).apply(null,arguments)};function he(){function e(){if(!ue&&(ue=!0,t.calledRun=!0,!A)){if(X(F),i(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();U.unshift(e)}X(U)}}if(!(0<B)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)N();X(L),0<B||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.___cxa_is_pointer_type=function(){return(t.___cxa_is_pointer_type=t.asm.pa).apply(null,arguments)},t.UTF8ToString=M,t.stringToUTF8=function(e,t,n){return R(e,C,t,n)},t.lengthBytesUTF8=D,t.stackSave=le,t.stackRestore=ce,t.stackAlloc=de,V=function e(){ue||he(),ue||(V=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return he(),e.ready});e.exports=i},4537:e=>{"use strict";e.exports=function(e,t){for(var n=new Array(arguments.length-1),r=0,i=2,o=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise((function(i,s){n[r]=function(e){if(o)if(o=!1,e)s(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;)t[n++]=arguments[n];i.apply(null,t)}};try{e.apply(t||null,n)}catch(e){o&&(o=!1,s(e))}}))}},7419:(e,t)=>{"use strict";var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var r=new Array(64),i=new Array(123),o=0;o<64;)i[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;n.encode=function(e,t,n){for(var i,o=null,s=[],a=0,u=0;t<n;){var l=e[t++];switch(u){case 0:s[a++]=r[l>>2],i=(3&l)<<4,u=1;break;case 1:s[a++]=r[i|l>>4],i=(15&l)<<2,u=2;break;case 2:s[a++]=r[i|l>>6],s[a++]=r[63&l],u=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0)}return u&&(s[a++]=r[i],s[a++]=61,1===u&&(s[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";n.decode=function(e,t,n){for(var r,o=n,a=0,u=0;u<e.length;){var l=e.charCodeAt(u++);if(61===l&&a>1)break;if(void 0===(l=i[l]))throw Error(s);switch(a){case 0:r=l,a=1;break;case 1:t[n++]=r<<2|(48&l)>>4,r=l,a=2;break;case 2:t[n++]=(15&r)<<4|(60&l)>>2,r=l,a=3;break;case 3:t[n++]=(3&r)<<6|l,a=0}}if(1===a)throw Error(s);return n-o},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},9211:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],r=0;r<n.length;)n[r].fn===t?n.splice(r,1):++r;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<t.length;)t[r].fn.apply(t[r++].ctx,n)}return this}},945:e=>{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),r=128===n[3];function i(e,r,i){t[0]=e,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function o(e,r,i){t[0]=e,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function s(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],t[0]}function a(e,r){return n[3]=e[r],n[2]=e[r+1],n[1]=e[r+2],n[0]=e[r+3],t[0]}e.writeFloatLE=r?i:o,e.writeFloatBE=r?o:i,e.readFloatLE=r?s:a,e.readFloatBE=r?a:s}():function(){function t(e,t,n,r){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,n,r);else if(isNaN(t))e(2143289344,n,r);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,n,r);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,n,r);else{var o=Math.floor(Math.log(t)/Math.LN2);e((i<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,n,r)}}function s(e,t,n){var r=e(t,n),i=2*(r>>31)+1,o=r>>>23&255,s=8388607&r;return 255===o?s?NaN:i*(1/0):0===o?1401298464324817e-60*i*s:i*Math.pow(2,o-150)*(s+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,r),e.readFloatLE=s.bind(null,i),e.readFloatBE=s.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),r=128===n[7];function i(e,r,i){t[0]=e,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function o(e,r,i){t[0]=e,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function s(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],n[4]=e[r+4],n[5]=e[r+5],n[6]=e[r+6],n[7]=e[r+7],t[0]}function a(e,r){return n[7]=e[r],n[6]=e[r+1],n[5]=e[r+2],n[4]=e[r+3],n[3]=e[r+4],n[2]=e[r+5],n[1]=e[r+6],n[0]=e[r+7],t[0]}e.writeDoubleLE=r?i:o,e.writeDoubleBE=r?o:i,e.readDoubleLE=r?s:a,e.readDoubleBE=r?a:s}():function(){function t(e,t,n,r,i,o){var s=r<0?1:0;if(s&&(r=-r),0===r)e(0,i,o+t),e(1/r>0?0:2147483648,i,o+n);else if(isNaN(r))e(0,i,o+t),e(2146959360,i,o+n);else if(r>17976931348623157e292)e(0,i,o+t),e((s<<31|2146435072)>>>0,i,o+n);else{var a;if(r<22250738585072014e-324)e((a=r/5e-324)>>>0,i,o+t),e((s<<31|a/4294967296)>>>0,i,o+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(a=r*Math.pow(2,-u))>>>0,i,o+t),e((s<<31|u+1023<<20|1048576*a&1048575)>>>0,i,o+n)}}}function s(e,t,n,r,i){var o=e(r,i+t),s=e(r,i+n),a=2*(s>>31)+1,u=s>>>20&2047,l=4294967296*(1048575&s)+o;return 2047===u?l?NaN:a*(1/0):0===u?5e-324*a*l:a*Math.pow(2,u-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,r,4,0),e.readDoubleLE=s.bind(null,i,0,4),e.readDoubleBE=s.bind(null,o,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function r(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function o(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},7199:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},6662:e=>{"use strict";e.exports=function(e,t,n){var r=n||8192,i=r>>>1,o=null,s=r;return function(n){if(n<1||n>i)return e(n);s+n>r&&(o=e(r),s=0);var a=t.call(o,s,s+=n);return 7&s&&(s=1+(7|s)),a}}},4997:(e,t)=>{"use strict";var n=t;n.length=function(e){for(var t=0,n=0,r=0;r<e.length;++r)(n=e.charCodeAt(r))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t},n.read=function(e,t,n){if(n-t<1)return"";for(var r,i=null,o=[],s=0;t<n;)(r=e[t++])<128?o[s++]=r:r>191&&r<224?o[s++]=(31&r)<<6|63&e[t++]:r>239&&r<365?(r=((7&r)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[s++]=55296+(r>>10),o[s++]=56320+(1023&r)):o[s++]=(15&r)<<12|(63&e[t++])<<6|63&e[t++],s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))},n.write=function(e,t,n){for(var r,i,o=n,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t[n++]=r:r<2048?(t[n++]=r>>6|192,t[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=e.charCodeAt(s+1)))?(r=65536+((1023&r)<<10)+(1023&i),++s,t[n++]=r>>18|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>12|224,t[n++]=r>>6&63|128,t[n++]=63&r|128);return n-o}},3442:(e,t)=>{"use strict";t.__esModule=!0;var n=function(){function e(t){if(!t)throw new TypeError("Invalid argument; `value` has no value.");this.value=e.EMPTY,t&&e.isGuid(t)&&(this.value=t)}return e.isGuid=function(t){var n=t.toString();return t&&(t instanceof e||e.validator.test(n))},e.create=function(){return new e([e.gen(2),e.gen(1),e.gen(1),e.gen(1),e.gen(3)].join("-"))},e.createEmpty=function(){return new e("emptyguid")},e.parse=function(t){return new e(t)},e.raw=function(){return[e.gen(2),e.gen(1),e.gen(1),e.gen(1),e.gen(3)].join("-")},e.gen=function(e){for(var t="",n=0;n<e;n++)t+=(65536*(1+Math.random())|0).toString(16).substring(1);return t},e.prototype.equals=function(t){return e.isGuid(t)&&this.value===t.toString()},e.prototype.isEmpty=function(){return this.value===e.EMPTY},e.prototype.toString=function(){return this.value},e.prototype.toJSON=function(){return{value:this.value}},e.validator=new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$","i"),e.EMPTY="00000000-0000-0000-0000-000000000000",e}();t.Guid=n},3720:e=>{e.exports=n;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},o={};function s(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=o[e])?r:(n=u(e,(0|e)<0?-1:0,!0),s&&(o[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=i[e])?r:(n=u(e,e<0?-1:0,!1),s&&(i[e]=n),n)}function a(e,t){if(isNaN(e))return t?b:m;if(t){if(e<0)return b;if(e>=p)return _}else{if(e<=-f)return T;if(e+1>=f)return S}return e<0?a(-e,t).neg():u(e%h|0,e/h|0,t)}function u(e,t,r){return new n(e,t,r)}n.fromInt=s,n.fromNumber=a,n.fromBits=u;var l=Math.pow;function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return m;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return c(e.substring(1),t,n).neg();for(var i=a(l(n,8)),o=m,s=0;s<e.length;s+=8){var u=Math.min(8,e.length-s),d=parseInt(e.substring(s,s+u),n);if(u<8){var h=a(l(n,u));o=o.mul(h).add(a(d))}else o=(o=o.mul(i)).add(a(d))}return o.unsigned=t,o}function d(e,t){return"number"==typeof e?a(e,t):"string"==typeof e?c(e,t):u(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}n.fromString=c,n.fromValue=d;var h=4294967296,p=h*h,f=p/2,g=s(1<<24),m=s(0);n.ZERO=m;var b=s(0,!0);n.UZERO=b;var y=s(1);n.ONE=y;var v=s(1,!0);n.UONE=v;var w=s(-1);n.NEG_ONE=w;var S=u(-1,2147483647,!1);n.MAX_VALUE=S;var _=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=_;var T=u(0,-2147483648,!1);n.MIN_VALUE=T;var x=n.prototype;x.toInt=function(){return this.unsigned?this.low>>>0:this.low},x.toNumber=function(){return this.unsigned?(this.high>>>0)*h+(this.low>>>0):this.high*h+(this.low>>>0)},x.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(T)){var t=a(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var i=a(l(e,6),this.unsigned),o=this,s="";;){var u=o.div(i),c=(o.sub(u.mul(i)).toInt()>>>0).toString(e);if((o=u).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},x.getHighBits=function(){return this.high},x.getHighBitsUnsigned=function(){return this.high>>>0},x.getLowBits=function(){return this.low},x.getLowBitsUnsigned=function(){return this.low>>>0},x.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},x.isZero=function(){return 0===this.high&&0===this.low},x.eqz=x.isZero,x.isNegative=function(){return!this.unsigned&&this.high<0},x.isPositive=function(){return this.unsigned||this.high>=0},x.isOdd=function(){return!(1&~this.low)},x.isEven=function(){return!(1&this.low)},x.equals=function(e){return r(e)||(e=d(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},x.eq=x.equals,x.notEquals=function(e){return!this.eq(e)},x.neq=x.notEquals,x.ne=x.notEquals,x.lessThan=function(e){return this.comp(e)<0},x.lt=x.lessThan,x.lessThanOrEqual=function(e){return this.comp(e)<=0},x.lte=x.lessThanOrEqual,x.le=x.lessThanOrEqual,x.greaterThan=function(e){return this.comp(e)>0},x.gt=x.greaterThan,x.greaterThanOrEqual=function(e){return this.comp(e)>=0},x.gte=x.greaterThanOrEqual,x.ge=x.greaterThanOrEqual,x.compare=function(e){if(r(e)||(e=d(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},x.comp=x.compare,x.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(y)},x.neg=x.negate,x.add=function(e){r(e)||(e=d(e));var t=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,s=e.high>>>16,a=65535&e.high,l=e.low>>>16,c=0,h=0,p=0,f=0;return p+=(f+=o+(65535&e.low))>>>16,h+=(p+=i+l)>>>16,c+=(h+=n+a)>>>16,c+=t+s,u((p&=65535)<<16|(f&=65535),(c&=65535)<<16|(h&=65535),this.unsigned)},x.subtract=function(e){return r(e)||(e=d(e)),this.add(e.neg())},x.sub=x.subtract,x.multiply=function(e){if(this.isZero())return m;if(r(e)||(e=d(e)),t)return u(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return m;if(this.eq(T))return e.isOdd()?T:m;if(e.eq(T))return this.isOdd()?T:m;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(g)&&e.lt(g))return a(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,o=this.low>>>16,s=65535&this.low,l=e.high>>>16,c=65535&e.high,h=e.low>>>16,p=65535&e.low,f=0,b=0,y=0,v=0;return y+=(v+=s*p)>>>16,b+=(y+=o*p)>>>16,y&=65535,b+=(y+=s*h)>>>16,f+=(b+=i*p)>>>16,b&=65535,f+=(b+=o*h)>>>16,b&=65535,f+=(b+=s*c)>>>16,f+=n*p+i*h+o*c+s*l,u((y&=65535)<<16|(v&=65535),(f&=65535)<<16|(b&=65535),this.unsigned)},x.mul=x.multiply,x.divide=function(e){if(r(e)||(e=d(e)),e.isZero())throw Error("division by zero");var n,i,o;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?u((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?b:m;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return b;if(e.gt(this.shru(1)))return v;o=b}else{if(this.eq(T))return e.eq(y)||e.eq(w)?T:e.eq(T)?y:(n=this.shr(1).div(e).shl(1)).eq(m)?e.isNegative()?y:w:(i=this.sub(e.mul(n)),o=n.add(i.div(e)));if(e.eq(T))return this.unsigned?b:m;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();o=m}for(i=this;i.gte(e);){n=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(n)/Math.LN2),c=s<=48?1:l(2,s-48),h=a(n),p=h.mul(e);p.isNegative()||p.gt(i);)p=(h=a(n-=c,this.unsigned)).mul(e);h.isZero()&&(h=y),o=o.add(h),i=i.sub(p)}return o},x.div=x.divide,x.modulo=function(e){return r(e)||(e=d(e)),t?u((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},x.mod=x.modulo,x.rem=x.modulo,x.not=function(){return u(~this.low,~this.high,this.unsigned)},x.and=function(e){return r(e)||(e=d(e)),u(this.low&e.low,this.high&e.high,this.unsigned)},x.or=function(e){return r(e)||(e=d(e)),u(this.low|e.low,this.high|e.high,this.unsigned)},x.xor=function(e){return r(e)||(e=d(e)),u(this.low^e.low,this.high^e.high,this.unsigned)},x.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):u(0,this.low<<e-32,this.unsigned)},x.shl=x.shiftLeft,x.shiftRight=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):u(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},x.shr=x.shiftRight,x.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?u(this.low>>>e|t<<32-e,t>>>e,this.unsigned):u(32===e?t:t>>>e-32,0,this.unsigned)},x.shru=x.shiftRightUnsigned,x.shr_u=x.shiftRightUnsigned,x.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},x.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},x.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},x.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},x.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},1446:(e,t,n)=>{"use strict";var r,i,o,s=n(2100),a=s.Reader,u=s.Writer,l=s.util,c=s.roots.default||(s.roots.default={});c.onnx=((o={}).Version=(r={},(i=Object.create(r))[r[0]="_START_VERSION"]=0,i[r[1]="IR_VERSION_2017_10_10"]=1,i[r[2]="IR_VERSION_2017_10_30"]=2,i[r[3]="IR_VERSION_2017_11_3"]=3,i[r[4]="IR_VERSION_2019_1_22"]=4,i[r[5]="IR_VERSION"]=5,i),o.AttributeProto=function(){function e(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.name="",e.prototype.refAttrName="",e.prototype.docString="",e.prototype.type=0,e.prototype.f=0,e.prototype.i=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.s=l.newBuffer([]),e.prototype.t=null,e.prototype.g=null,e.prototype.floats=l.emptyArray,e.prototype.ints=l.emptyArray,e.prototype.strings=l.emptyArray,e.prototype.tensors=l.emptyArray,e.prototype.graphs=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.name&&e.hasOwnProperty("name")&&t.uint32(10).string(e.name),null!=e.f&&e.hasOwnProperty("f")&&t.uint32(21).float(e.f),null!=e.i&&e.hasOwnProperty("i")&&t.uint32(24).int64(e.i),null!=e.s&&e.hasOwnProperty("s")&&t.uint32(34).bytes(e.s),null!=e.t&&e.hasOwnProperty("t")&&c.onnx.TensorProto.encode(e.t,t.uint32(42).fork()).ldelim(),null!=e.g&&e.hasOwnProperty("g")&&c.onnx.GraphProto.encode(e.g,t.uint32(50).fork()).ldelim(),null!=e.floats&&e.floats.length){t.uint32(58).fork();for(var n=0;n<e.floats.length;++n)t.float(e.floats[n]);t.ldelim()}if(null!=e.ints&&e.ints.length){for(t.uint32(66).fork(),n=0;n<e.ints.length;++n)t.int64(e.ints[n]);t.ldelim()}if(null!=e.strings&&e.strings.length)for(n=0;n<e.strings.length;++n)t.uint32(74).bytes(e.strings[n]);if(null!=e.tensors&&e.tensors.length)for(n=0;n<e.tensors.length;++n)c.onnx.TensorProto.encode(e.tensors[n],t.uint32(82).fork()).ldelim();if(null!=e.graphs&&e.graphs.length)for(n=0;n<e.graphs.length;++n)c.onnx.GraphProto.encode(e.graphs[n],t.uint32(90).fork()).ldelim();return null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(106).string(e.docString),null!=e.type&&e.hasOwnProperty("type")&&t.uint32(160).int32(e.type),null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&t.uint32(170).string(e.refAttrName),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.AttributeProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.name=e.string();break;case 21:r.refAttrName=e.string();break;case 13:r.docString=e.string();break;case 20:r.type=e.int32();break;case 2:r.f=e.float();break;case 3:r.i=e.int64();break;case 4:r.s=e.bytes();break;case 5:r.t=c.onnx.TensorProto.decode(e,e.uint32());break;case 6:r.g=c.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&i))for(var o=e.uint32()+e.pos;e.pos<o;)r.floats.push(e.float());else r.floats.push(e.float());break;case 8:if(r.ints&&r.ints.length||(r.ints=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.ints.push(e.int64());else r.ints.push(e.int64());break;case 9:r.strings&&r.strings.length||(r.strings=[]),r.strings.push(e.bytes());break;case 10:r.tensors&&r.tensors.length||(r.tensors=[]),r.tensors.push(c.onnx.TensorProto.decode(e,e.uint32()));break;case 11:r.graphs&&r.graphs.length||(r.graphs=[]),r.graphs.push(c.onnx.GraphProto.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&!l.isString(e.refAttrName))return"refAttrName: string expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:}if(null!=e.f&&e.hasOwnProperty("f")&&"number"!=typeof e.f)return"f: number expected";if(null!=e.i&&e.hasOwnProperty("i")&&!(l.isInteger(e.i)||e.i&&l.isInteger(e.i.low)&&l.isInteger(e.i.high)))return"i: integer|Long expected";if(null!=e.s&&e.hasOwnProperty("s")&&!(e.s&&"number"==typeof e.s.length||l.isString(e.s)))return"s: buffer expected";if(null!=e.t&&e.hasOwnProperty("t")&&(n=c.onnx.TensorProto.verify(e.t)))return"t."+n;if(null!=e.g&&e.hasOwnProperty("g")&&(n=c.onnx.GraphProto.verify(e.g)))return"g."+n;if(null!=e.floats&&e.hasOwnProperty("floats")){if(!Array.isArray(e.floats))return"floats: array expected";for(var t=0;t<e.floats.length;++t)if("number"!=typeof e.floats[t])return"floats: number[] expected"}if(null!=e.ints&&e.hasOwnProperty("ints")){if(!Array.isArray(e.ints))return"ints: array expected";for(t=0;t<e.ints.length;++t)if(!(l.isInteger(e.ints[t])||e.ints[t]&&l.isInteger(e.ints[t].low)&&l.isInteger(e.ints[t].high)))return"ints: integer|Long[] expected"}if(null!=e.strings&&e.hasOwnProperty("strings")){if(!Array.isArray(e.strings))return"strings: array expected";for(t=0;t<e.strings.length;++t)if(!(e.strings[t]&&"number"==typeof e.strings[t].length||l.isString(e.strings[t])))return"strings: buffer[] expected"}if(null!=e.tensors&&e.hasOwnProperty("tensors")){if(!Array.isArray(e.tensors))return"tensors: array expected";for(t=0;t<e.tensors.length;++t)if(n=c.onnx.TensorProto.verify(e.tensors[t]))return"tensors."+n}if(null!=e.graphs&&e.hasOwnProperty("graphs")){if(!Array.isArray(e.graphs))return"graphs: array expected";for(t=0;t<e.graphs.length;++t){var n;if(n=c.onnx.GraphProto.verify(e.graphs[t]))return"graphs."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.AttributeProto)return e;var t=new c.onnx.AttributeProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.refAttrName&&(t.refAttrName=String(e.refAttrName)),null!=e.docString&&(t.docString=String(e.docString)),e.type){case"UNDEFINED":case 0:t.type=0;break;case"FLOAT":case 1:t.type=1;break;case"INT":case 2:t.type=2;break;case"STRING":case 3:t.type=3;break;case"TENSOR":case 4:t.type=4;break;case"GRAPH":case 5:t.type=5;break;case"FLOATS":case 6:t.type=6;break;case"INTS":case 7:t.type=7;break;case"STRINGS":case 8:t.type=8;break;case"TENSORS":case 9:t.type=9;break;case"GRAPHS":case 10:t.type=10}if(null!=e.f&&(t.f=Number(e.f)),null!=e.i&&(l.Long?(t.i=l.Long.fromValue(e.i)).unsigned=!1:"string"==typeof e.i?t.i=parseInt(e.i,10):"number"==typeof e.i?t.i=e.i:"object"==typeof e.i&&(t.i=new l.LongBits(e.i.low>>>0,e.i.high>>>0).toNumber())),null!=e.s&&("string"==typeof e.s?l.base64.decode(e.s,t.s=l.newBuffer(l.base64.length(e.s)),0):e.s.length&&(t.s=e.s)),null!=e.t){if("object"!=typeof e.t)throw TypeError(".onnx.AttributeProto.t: object expected");t.t=c.onnx.TensorProto.fromObject(e.t)}if(null!=e.g){if("object"!=typeof e.g)throw TypeError(".onnx.AttributeProto.g: object expected");t.g=c.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");t.floats=[];for(var n=0;n<e.floats.length;++n)t.floats[n]=Number(e.floats[n])}if(e.ints){if(!Array.isArray(e.ints))throw TypeError(".onnx.AttributeProto.ints: array expected");for(t.ints=[],n=0;n<e.ints.length;++n)l.Long?(t.ints[n]=l.Long.fromValue(e.ints[n])).unsigned=!1:"string"==typeof e.ints[n]?t.ints[n]=parseInt(e.ints[n],10):"number"==typeof e.ints[n]?t.ints[n]=e.ints[n]:"object"==typeof e.ints[n]&&(t.ints[n]=new l.LongBits(e.ints[n].low>>>0,e.ints[n].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(t.strings=[],n=0;n<e.strings.length;++n)"string"==typeof e.strings[n]?l.base64.decode(e.strings[n],t.strings[n]=l.newBuffer(l.base64.length(e.strings[n])),0):e.strings[n].length&&(t.strings[n]=e.strings[n])}if(e.tensors){if(!Array.isArray(e.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");for(t.tensors=[],n=0;n<e.tensors.length;++n){if("object"!=typeof e.tensors[n])throw TypeError(".onnx.AttributeProto.tensors: object expected");t.tensors[n]=c.onnx.TensorProto.fromObject(e.tensors[n])}}if(e.graphs){if(!Array.isArray(e.graphs))throw TypeError(".onnx.AttributeProto.graphs: array expected");for(t.graphs=[],n=0;n<e.graphs.length;++n){if("object"!=typeof e.graphs[n])throw TypeError(".onnx.AttributeProto.graphs: object expected");t.graphs[n]=c.onnx.GraphProto.fromObject(e.graphs[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.floats=[],n.ints=[],n.strings=[],n.tensors=[],n.graphs=[]),t.defaults){if(n.name="",n.f=0,l.Long){var r=new l.Long(0,0,!1);n.i=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.i=t.longs===String?"0":0;t.bytes===String?n.s="":(n.s=[],t.bytes!==Array&&(n.s=l.newBuffer(n.s))),n.t=null,n.g=null,n.docString="",n.type=t.enums===String?"UNDEFINED":0,n.refAttrName=""}if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.f&&e.hasOwnProperty("f")&&(n.f=t.json&&!isFinite(e.f)?String(e.f):e.f),null!=e.i&&e.hasOwnProperty("i")&&("number"==typeof e.i?n.i=t.longs===String?String(e.i):e.i:n.i=t.longs===String?l.Long.prototype.toString.call(e.i):t.longs===Number?new l.LongBits(e.i.low>>>0,e.i.high>>>0).toNumber():e.i),null!=e.s&&e.hasOwnProperty("s")&&(n.s=t.bytes===String?l.base64.encode(e.s,0,e.s.length):t.bytes===Array?Array.prototype.slice.call(e.s):e.s),null!=e.t&&e.hasOwnProperty("t")&&(n.t=c.onnx.TensorProto.toObject(e.t,t)),null!=e.g&&e.hasOwnProperty("g")&&(n.g=c.onnx.GraphProto.toObject(e.g,t)),e.floats&&e.floats.length){n.floats=[];for(var i=0;i<e.floats.length;++i)n.floats[i]=t.json&&!isFinite(e.floats[i])?String(e.floats[i]):e.floats[i]}if(e.ints&&e.ints.length)for(n.ints=[],i=0;i<e.ints.length;++i)"number"==typeof e.ints[i]?n.ints[i]=t.longs===String?String(e.ints[i]):e.ints[i]:n.ints[i]=t.longs===String?l.Long.prototype.toString.call(e.ints[i]):t.longs===Number?new l.LongBits(e.ints[i].low>>>0,e.ints[i].high>>>0).toNumber():e.ints[i];if(e.strings&&e.strings.length)for(n.strings=[],i=0;i<e.strings.length;++i)n.strings[i]=t.bytes===String?l.base64.encode(e.strings[i],0,e.strings[i].length):t.bytes===Array?Array.prototype.slice.call(e.strings[i]):e.strings[i];if(e.tensors&&e.tensors.length)for(n.tensors=[],i=0;i<e.tensors.length;++i)n.tensors[i]=c.onnx.TensorProto.toObject(e.tensors[i],t);if(e.graphs&&e.graphs.length)for(n.graphs=[],i=0;i<e.graphs.length;++i)n.graphs[i]=c.onnx.GraphProto.toObject(e.graphs[i],t);return null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?c.onnx.AttributeProto.AttributeType[e.type]:e.type),null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&(n.refAttrName=e.refAttrName),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.AttributeType=function(){var e={},t=Object.create(e);return t[e[0]="UNDEFINED"]=0,t[e[1]="FLOAT"]=1,t[e[2]="INT"]=2,t[e[3]="STRING"]=3,t[e[4]="TENSOR"]=4,t[e[5]="GRAPH"]=5,t[e[6]="FLOATS"]=6,t[e[7]="INTS"]=7,t[e[8]="STRINGS"]=8,t[e[9]="TENSORS"]=9,t[e[10]="GRAPHS"]=10,t}(),e}(),o.ValueInfoProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.name="",e.prototype.type=null,e.prototype.docString="",e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.name&&e.hasOwnProperty("name")&&t.uint32(10).string(e.name),null!=e.type&&e.hasOwnProperty("type")&&c.onnx.TypeProto.encode(e.type,t.uint32(18).fork()).ldelim(),null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(26).string(e.docString),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.ValueInfoProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.name=e.string();break;case 2:r.type=c.onnx.TypeProto.decode(e,e.uint32());break;case 3:r.docString=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.type&&e.hasOwnProperty("type")){var t=c.onnx.TypeProto.verify(e.type);if(t)return"type."+t}return null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString)?"docString: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.ValueInfoProto)return e;var t=new c.onnx.ValueInfoProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.type){if("object"!=typeof e.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");t.type=c.onnx.TypeProto.fromObject(e.type)}return null!=e.docString&&(t.docString=String(e.docString)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.name="",n.type=null,n.docString=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.type&&e.hasOwnProperty("type")&&(n.type=c.onnx.TypeProto.toObject(e.type,t)),null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.NodeProto=function(){function e(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.input=l.emptyArray,e.prototype.output=l.emptyArray,e.prototype.name="",e.prototype.opType="",e.prototype.domain="",e.prototype.attribute=l.emptyArray,e.prototype.docString="",e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.input&&e.input.length)for(var n=0;n<e.input.length;++n)t.uint32(10).string(e.input[n]);if(null!=e.output&&e.output.length)for(n=0;n<e.output.length;++n)t.uint32(18).string(e.output[n]);if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(26).string(e.name),null!=e.opType&&e.hasOwnProperty("opType")&&t.uint32(34).string(e.opType),null!=e.attribute&&e.attribute.length)for(n=0;n<e.attribute.length;++n)c.onnx.AttributeProto.encode(e.attribute[n],t.uint32(42).fork()).ldelim();return null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(50).string(e.docString),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(58).string(e.domain),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.NodeProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(e.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(e.string());break;case 3:r.name=e.string();break;case 4:r.opType=e.string();break;case 7:r.domain=e.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(c.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:r.docString=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.input&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var t=0;t<e.input.length;++t)if(!l.isString(e.input[t]))return"input: string[] expected"}if(null!=e.output&&e.hasOwnProperty("output")){if(!Array.isArray(e.output))return"output: array expected";for(t=0;t<e.output.length;++t)if(!l.isString(e.output[t]))return"output: string[] expected"}if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.opType&&e.hasOwnProperty("opType")&&!l.isString(e.opType))return"opType: string expected";if(null!=e.domain&&e.hasOwnProperty("domain")&&!l.isString(e.domain))return"domain: string expected";if(null!=e.attribute&&e.hasOwnProperty("attribute")){if(!Array.isArray(e.attribute))return"attribute: array expected";for(t=0;t<e.attribute.length;++t){var n=c.onnx.AttributeProto.verify(e.attribute[t]);if(n)return"attribute."+n}}return null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString)?"docString: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.NodeProto)return e;var t=new c.onnx.NodeProto;if(e.input){if(!Array.isArray(e.input))throw TypeError(".onnx.NodeProto.input: array expected");t.input=[];for(var n=0;n<e.input.length;++n)t.input[n]=String(e.input[n])}if(e.output){if(!Array.isArray(e.output))throw TypeError(".onnx.NodeProto.output: array expected");for(t.output=[],n=0;n<e.output.length;++n)t.output[n]=String(e.output[n])}if(null!=e.name&&(t.name=String(e.name)),null!=e.opType&&(t.opType=String(e.opType)),null!=e.domain&&(t.domain=String(e.domain)),e.attribute){if(!Array.isArray(e.attribute))throw TypeError(".onnx.NodeProto.attribute: array expected");for(t.attribute=[],n=0;n<e.attribute.length;++n){if("object"!=typeof e.attribute[n])throw TypeError(".onnx.NodeProto.attribute: object expected");t.attribute[n]=c.onnx.AttributeProto.fromObject(e.attribute[n])}}return null!=e.docString&&(t.docString=String(e.docString)),t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.input=[],n.output=[],n.attribute=[]),t.defaults&&(n.name="",n.opType="",n.docString="",n.domain=""),e.input&&e.input.length){n.input=[];for(var r=0;r<e.input.length;++r)n.input[r]=e.input[r]}if(e.output&&e.output.length)for(n.output=[],r=0;r<e.output.length;++r)n.output[r]=e.output[r];if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.opType&&e.hasOwnProperty("opType")&&(n.opType=e.opType),e.attribute&&e.attribute.length)for(n.attribute=[],r=0;r<e.attribute.length;++r)n.attribute[r]=c.onnx.AttributeProto.toObject(e.attribute[r],t);return null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.ModelProto=function(){function e(e){if(this.opsetImport=[],this.metadataProps=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.irVersion=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.opsetImport=l.emptyArray,e.prototype.producerName="",e.prototype.producerVersion="",e.prototype.domain="",e.prototype.modelVersion=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.docString="",e.prototype.graph=null,e.prototype.metadataProps=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.irVersion&&e.hasOwnProperty("irVersion")&&t.uint32(8).int64(e.irVersion),null!=e.producerName&&e.hasOwnProperty("producerName")&&t.uint32(18).string(e.producerName),null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&t.uint32(26).string(e.producerVersion),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(34).string(e.domain),null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&t.uint32(40).int64(e.modelVersion),null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(50).string(e.docString),null!=e.graph&&e.hasOwnProperty("graph")&&c.onnx.GraphProto.encode(e.graph,t.uint32(58).fork()).ldelim(),null!=e.opsetImport&&e.opsetImport.length)for(var n=0;n<e.opsetImport.length;++n)c.onnx.OperatorSetIdProto.encode(e.opsetImport[n],t.uint32(66).fork()).ldelim();if(null!=e.metadataProps&&e.metadataProps.length)for(n=0;n<e.metadataProps.length;++n)c.onnx.StringStringEntryProto.encode(e.metadataProps[n],t.uint32(114).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.ModelProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.irVersion=e.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(c.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:r.producerName=e.string();break;case 3:r.producerVersion=e.string();break;case 4:r.domain=e.string();break;case 5:r.modelVersion=e.int64();break;case 6:r.docString=e.string();break;case 7:r.graph=c.onnx.GraphProto.decode(e,e.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(c.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.irVersion&&e.hasOwnProperty("irVersion")&&!(l.isInteger(e.irVersion)||e.irVersion&&l.isInteger(e.irVersion.low)&&l.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(null!=e.opsetImport&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var t=0;t<e.opsetImport.length;++t)if(n=c.onnx.OperatorSetIdProto.verify(e.opsetImport[t]))return"opsetImport."+n}if(null!=e.producerName&&e.hasOwnProperty("producerName")&&!l.isString(e.producerName))return"producerName: string expected";if(null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&!l.isString(e.producerVersion))return"producerVersion: string expected";if(null!=e.domain&&e.hasOwnProperty("domain")&&!l.isString(e.domain))return"domain: string expected";if(null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&!(l.isInteger(e.modelVersion)||e.modelVersion&&l.isInteger(e.modelVersion.low)&&l.isInteger(e.modelVersion.high)))return"modelVersion: integer|Long expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.graph&&e.hasOwnProperty("graph")&&(n=c.onnx.GraphProto.verify(e.graph)))return"graph."+n;if(null!=e.metadataProps&&e.hasOwnProperty("metadataProps")){if(!Array.isArray(e.metadataProps))return"metadataProps: array expected";for(t=0;t<e.metadataProps.length;++t){var n;if(n=c.onnx.StringStringEntryProto.verify(e.metadataProps[t]))return"metadataProps."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.ModelProto)return e;var t=new c.onnx.ModelProto;if(null!=e.irVersion&&(l.Long?(t.irVersion=l.Long.fromValue(e.irVersion)).unsigned=!1:"string"==typeof e.irVersion?t.irVersion=parseInt(e.irVersion,10):"number"==typeof e.irVersion?t.irVersion=e.irVersion:"object"==typeof e.irVersion&&(t.irVersion=new l.LongBits(e.irVersion.low>>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");t.opsetImport=[];for(var n=0;n<e.opsetImport.length;++n){if("object"!=typeof e.opsetImport[n])throw TypeError(".onnx.ModelProto.opsetImport: object expected");t.opsetImport[n]=c.onnx.OperatorSetIdProto.fromObject(e.opsetImport[n])}}if(null!=e.producerName&&(t.producerName=String(e.producerName)),null!=e.producerVersion&&(t.producerVersion=String(e.producerVersion)),null!=e.domain&&(t.domain=String(e.domain)),null!=e.modelVersion&&(l.Long?(t.modelVersion=l.Long.fromValue(e.modelVersion)).unsigned=!1:"string"==typeof e.modelVersion?t.modelVersion=parseInt(e.modelVersion,10):"number"==typeof e.modelVersion?t.modelVersion=e.modelVersion:"object"==typeof e.modelVersion&&(t.modelVersion=new l.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber())),null!=e.docString&&(t.docString=String(e.docString)),null!=e.graph){if("object"!=typeof e.graph)throw TypeError(".onnx.ModelProto.graph: object expected");t.graph=c.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(t.metadataProps=[],n=0;n<e.metadataProps.length;++n){if("object"!=typeof e.metadataProps[n])throw TypeError(".onnx.ModelProto.metadataProps: object expected");t.metadataProps[n]=c.onnx.StringStringEntryProto.fromObject(e.metadataProps[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.opsetImport=[],n.metadataProps=[]),t.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.irVersion=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.irVersion=t.longs===String?"0":0;n.producerName="",n.producerVersion="",n.domain="",l.Long?(r=new l.Long(0,0,!1),n.modelVersion=t.longs===String?r.toString():t.longs===Number?r.toNumber():r):n.modelVersion=t.longs===String?"0":0,n.docString="",n.graph=null}if(null!=e.irVersion&&e.hasOwnProperty("irVersion")&&("number"==typeof e.irVersion?n.irVersion=t.longs===String?String(e.irVersion):e.irVersion:n.irVersion=t.longs===String?l.Long.prototype.toString.call(e.irVersion):t.longs===Number?new l.LongBits(e.irVersion.low>>>0,e.irVersion.high>>>0).toNumber():e.irVersion),null!=e.producerName&&e.hasOwnProperty("producerName")&&(n.producerName=e.producerName),null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&(n.producerVersion=e.producerVersion),null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&("number"==typeof e.modelVersion?n.modelVersion=t.longs===String?String(e.modelVersion):e.modelVersion:n.modelVersion=t.longs===String?l.Long.prototype.toString.call(e.modelVersion):t.longs===Number?new l.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.graph&&e.hasOwnProperty("graph")&&(n.graph=c.onnx.GraphProto.toObject(e.graph,t)),e.opsetImport&&e.opsetImport.length){n.opsetImport=[];for(var i=0;i<e.opsetImport.length;++i)n.opsetImport[i]=c.onnx.OperatorSetIdProto.toObject(e.opsetImport[i],t)}if(e.metadataProps&&e.metadataProps.length)for(n.metadataProps=[],i=0;i<e.metadataProps.length;++i)n.metadataProps[i]=c.onnx.StringStringEntryProto.toObject(e.metadataProps[i],t);return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.StringStringEntryProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.key="",e.prototype.value="",e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.key&&e.hasOwnProperty("key")&&t.uint32(10).string(e.key),null!=e.value&&e.hasOwnProperty("value")&&t.uint32(18).string(e.value),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.StringStringEntryProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.string();break;case 2:r.value=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.key&&e.hasOwnProperty("key")&&!l.isString(e.key)?"key: string expected":null!=e.value&&e.hasOwnProperty("value")&&!l.isString(e.value)?"value: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.StringStringEntryProto)return e;var t=new c.onnx.StringStringEntryProto;return null!=e.key&&(t.key=String(e.key)),null!=e.value&&(t.value=String(e.value)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.key="",n.value=""),null!=e.key&&e.hasOwnProperty("key")&&(n.key=e.key),null!=e.value&&e.hasOwnProperty("value")&&(n.value=e.value),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.TensorAnnotation=function(){function e(e){if(this.quantParameterTensorNames=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.tensorName="",e.prototype.quantParameterTensorNames=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.tensorName&&e.hasOwnProperty("tensorName")&&t.uint32(10).string(e.tensorName),null!=e.quantParameterTensorNames&&e.quantParameterTensorNames.length)for(var n=0;n<e.quantParameterTensorNames.length;++n)c.onnx.StringStringEntryProto.encode(e.quantParameterTensorNames[n],t.uint32(18).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorAnnotation;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.tensorName=e.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(c.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.tensorName&&e.hasOwnProperty("tensorName")&&!l.isString(e.tensorName))return"tensorName: string expected";if(null!=e.quantParameterTensorNames&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var t=0;t<e.quantParameterTensorNames.length;++t){var n=c.onnx.StringStringEntryProto.verify(e.quantParameterTensorNames[t]);if(n)return"quantParameterTensorNames."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.TensorAnnotation)return e;var t=new c.onnx.TensorAnnotation;if(null!=e.tensorName&&(t.tensorName=String(e.tensorName)),e.quantParameterTensorNames){if(!Array.isArray(e.quantParameterTensorNames))throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");t.quantParameterTensorNames=[];for(var n=0;n<e.quantParameterTensorNames.length;++n){if("object"!=typeof e.quantParameterTensorNames[n])throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");t.quantParameterTensorNames[n]=c.onnx.StringStringEntryProto.fromObject(e.quantParameterTensorNames[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.quantParameterTensorNames=[]),t.defaults&&(n.tensorName=""),null!=e.tensorName&&e.hasOwnProperty("tensorName")&&(n.tensorName=e.tensorName),e.quantParameterTensorNames&&e.quantParameterTensorNames.length){n.quantParameterTensorNames=[];for(var r=0;r<e.quantParameterTensorNames.length;++r)n.quantParameterTensorNames[r]=c.onnx.StringStringEntryProto.toObject(e.quantParameterTensorNames[r],t)}return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.GraphProto=function(){function e(e){if(this.node=[],this.initializer=[],this.input=[],this.output=[],this.valueInfo=[],this.quantizationAnnotation=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.node=l.emptyArray,e.prototype.name="",e.prototype.initializer=l.emptyArray,e.prototype.docString="",e.prototype.input=l.emptyArray,e.prototype.output=l.emptyArray,e.prototype.valueInfo=l.emptyArray,e.prototype.quantizationAnnotation=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.node&&e.node.length)for(var n=0;n<e.node.length;++n)c.onnx.NodeProto.encode(e.node[n],t.uint32(10).fork()).ldelim();if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(18).string(e.name),null!=e.initializer&&e.initializer.length)for(n=0;n<e.initializer.length;++n)c.onnx.TensorProto.encode(e.initializer[n],t.uint32(42).fork()).ldelim();if(null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(82).string(e.docString),null!=e.input&&e.input.length)for(n=0;n<e.input.length;++n)c.onnx.ValueInfoProto.encode(e.input[n],t.uint32(90).fork()).ldelim();if(null!=e.output&&e.output.length)for(n=0;n<e.output.length;++n)c.onnx.ValueInfoProto.encode(e.output[n],t.uint32(98).fork()).ldelim();if(null!=e.valueInfo&&e.valueInfo.length)for(n=0;n<e.valueInfo.length;++n)c.onnx.ValueInfoProto.encode(e.valueInfo[n],t.uint32(106).fork()).ldelim();if(null!=e.quantizationAnnotation&&e.quantizationAnnotation.length)for(n=0;n<e.quantizationAnnotation.length;++n)c.onnx.TensorAnnotation.encode(e.quantizationAnnotation[n],t.uint32(114).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.GraphProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(c.onnx.NodeProto.decode(e,e.uint32()));break;case 2:r.name=e.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(c.onnx.TensorProto.decode(e,e.uint32()));break;case 10:r.docString=e.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(c.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(c.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(c.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(c.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.node&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var t=0;t<e.node.length;++t)if(n=c.onnx.NodeProto.verify(e.node[t]))return"node."+n}if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.initializer&&e.hasOwnProperty("initializer")){if(!Array.isArray(e.initializer))return"initializer: array expected";for(t=0;t<e.initializer.length;++t)if(n=c.onnx.TensorProto.verify(e.initializer[t]))return"initializer."+n}if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.input&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(t=0;t<e.input.length;++t)if(n=c.onnx.ValueInfoProto.verify(e.input[t]))return"input."+n}if(null!=e.output&&e.hasOwnProperty("output")){if(!Array.isArray(e.output))return"output: array expected";for(t=0;t<e.output.length;++t)if(n=c.onnx.ValueInfoProto.verify(e.output[t]))return"output."+n}if(null!=e.valueInfo&&e.hasOwnProperty("valueInfo")){if(!Array.isArray(e.valueInfo))return"valueInfo: array expected";for(t=0;t<e.valueInfo.length;++t)if(n=c.onnx.ValueInfoProto.verify(e.valueInfo[t]))return"valueInfo."+n}if(null!=e.quantizationAnnotation&&e.hasOwnProperty("quantizationAnnotation")){if(!Array.isArray(e.quantizationAnnotation))return"quantizationAnnotation: array expected";for(t=0;t<e.quantizationAnnotation.length;++t){var n;if(n=c.onnx.TensorAnnotation.verify(e.quantizationAnnotation[t]))return"quantizationAnnotation."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.GraphProto)return e;var t=new c.onnx.GraphProto;if(e.node){if(!Array.isArray(e.node))throw TypeError(".onnx.GraphProto.node: array expected");t.node=[];for(var n=0;n<e.node.length;++n){if("object"!=typeof e.node[n])throw TypeError(".onnx.GraphProto.node: object expected");t.node[n]=c.onnx.NodeProto.fromObject(e.node[n])}}if(null!=e.name&&(t.name=String(e.name)),e.initializer){if(!Array.isArray(e.initializer))throw TypeError(".onnx.GraphProto.initializer: array expected");for(t.initializer=[],n=0;n<e.initializer.length;++n){if("object"!=typeof e.initializer[n])throw TypeError(".onnx.GraphProto.initializer: object expected");t.initializer[n]=c.onnx.TensorProto.fromObject(e.initializer[n])}}if(null!=e.docString&&(t.docString=String(e.docString)),e.input){if(!Array.isArray(e.input))throw TypeError(".onnx.GraphProto.input: array expected");for(t.input=[],n=0;n<e.input.length;++n){if("object"!=typeof e.input[n])throw TypeError(".onnx.GraphProto.input: object expected");t.input[n]=c.onnx.ValueInfoProto.fromObject(e.input[n])}}if(e.output){if(!Array.isArray(e.output))throw TypeError(".onnx.GraphProto.output: array expected");for(t.output=[],n=0;n<e.output.length;++n){if("object"!=typeof e.output[n])throw TypeError(".onnx.GraphProto.output: object expected");t.output[n]=c.onnx.ValueInfoProto.fromObject(e.output[n])}}if(e.valueInfo){if(!Array.isArray(e.valueInfo))throw TypeError(".onnx.GraphProto.valueInfo: array expected");for(t.valueInfo=[],n=0;n<e.valueInfo.length;++n){if("object"!=typeof e.valueInfo[n])throw TypeError(".onnx.GraphProto.valueInfo: object expected");t.valueInfo[n]=c.onnx.ValueInfoProto.fromObject(e.valueInfo[n])}}if(e.quantizationAnnotation){if(!Array.isArray(e.quantizationAnnotation))throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");for(t.quantizationAnnotation=[],n=0;n<e.quantizationAnnotation.length;++n){if("object"!=typeof e.quantizationAnnotation[n])throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");t.quantizationAnnotation[n]=c.onnx.TensorAnnotation.fromObject(e.quantizationAnnotation[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.node=[],n.initializer=[],n.input=[],n.output=[],n.valueInfo=[],n.quantizationAnnotation=[]),t.defaults&&(n.name="",n.docString=""),e.node&&e.node.length){n.node=[];for(var r=0;r<e.node.length;++r)n.node[r]=c.onnx.NodeProto.toObject(e.node[r],t)}if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),e.initializer&&e.initializer.length)for(n.initializer=[],r=0;r<e.initializer.length;++r)n.initializer[r]=c.onnx.TensorProto.toObject(e.initializer[r],t);if(null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),e.input&&e.input.length)for(n.input=[],r=0;r<e.input.length;++r)n.input[r]=c.onnx.ValueInfoProto.toObject(e.input[r],t);if(e.output&&e.output.length)for(n.output=[],r=0;r<e.output.length;++r)n.output[r]=c.onnx.ValueInfoProto.toObject(e.output[r],t);if(e.valueInfo&&e.valueInfo.length)for(n.valueInfo=[],r=0;r<e.valueInfo.length;++r)n.valueInfo[r]=c.onnx.ValueInfoProto.toObject(e.valueInfo[r],t);if(e.quantizationAnnotation&&e.quantizationAnnotation.length)for(n.quantizationAnnotation=[],r=0;r<e.quantizationAnnotation.length;++r)n.quantizationAnnotation[r]=c.onnx.TensorAnnotation.toObject(e.quantizationAnnotation[r],t);return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.TensorProto=function(){function e(e){if(this.dims=[],this.floatData=[],this.int32Data=[],this.stringData=[],this.int64Data=[],this.externalData=[],this.doubleData=[],this.uint64Data=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.dims=l.emptyArray,e.prototype.dataType=0,e.prototype.segment=null,e.prototype.floatData=l.emptyArray,e.prototype.int32Data=l.emptyArray,e.prototype.stringData=l.emptyArray,e.prototype.int64Data=l.emptyArray,e.prototype.name="",e.prototype.docString="",e.prototype.rawData=l.newBuffer([]),e.prototype.externalData=l.emptyArray,e.prototype.dataLocation=0,e.prototype.doubleData=l.emptyArray,e.prototype.uint64Data=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.dims&&e.dims.length){t.uint32(10).fork();for(var n=0;n<e.dims.length;++n)t.int64(e.dims[n]);t.ldelim()}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&t.uint32(16).int32(e.dataType),null!=e.segment&&e.hasOwnProperty("segment")&&c.onnx.TensorProto.Segment.encode(e.segment,t.uint32(26).fork()).ldelim(),null!=e.floatData&&e.floatData.length){for(t.uint32(34).fork(),n=0;n<e.floatData.length;++n)t.float(e.floatData[n]);t.ldelim()}if(null!=e.int32Data&&e.int32Data.length){for(t.uint32(42).fork(),n=0;n<e.int32Data.length;++n)t.int32(e.int32Data[n]);t.ldelim()}if(null!=e.stringData&&e.stringData.length)for(n=0;n<e.stringData.length;++n)t.uint32(50).bytes(e.stringData[n]);if(null!=e.int64Data&&e.int64Data.length){for(t.uint32(58).fork(),n=0;n<e.int64Data.length;++n)t.int64(e.int64Data[n]);t.ldelim()}if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(66).string(e.name),null!=e.rawData&&e.hasOwnProperty("rawData")&&t.uint32(74).bytes(e.rawData),null!=e.doubleData&&e.doubleData.length){for(t.uint32(82).fork(),n=0;n<e.doubleData.length;++n)t.double(e.doubleData[n]);t.ldelim()}if(null!=e.uint64Data&&e.uint64Data.length){for(t.uint32(90).fork(),n=0;n<e.uint64Data.length;++n)t.uint64(e.uint64Data[n]);t.ldelim()}if(null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(98).string(e.docString),null!=e.externalData&&e.externalData.length)for(n=0;n<e.externalData.length;++n)c.onnx.StringStringEntryProto.encode(e.externalData[n],t.uint32(106).fork()).ldelim();return null!=e.dataLocation&&e.hasOwnProperty("dataLocation")&&t.uint32(112).int32(e.dataLocation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&i))for(var o=e.uint32()+e.pos;e.pos<o;)r.dims.push(e.int64());else r.dims.push(e.int64());break;case 2:r.dataType=e.int32();break;case 3:r.segment=c.onnx.TensorProto.Segment.decode(e,e.uint32());break;case 4:if(r.floatData&&r.floatData.length||(r.floatData=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.floatData.push(e.float());else r.floatData.push(e.float());break;case 5:if(r.int32Data&&r.int32Data.length||(r.int32Data=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.int32Data.push(e.int32());else r.int32Data.push(e.int32());break;case 6:r.stringData&&r.stringData.length||(r.stringData=[]),r.stringData.push(e.bytes());break;case 7:if(r.int64Data&&r.int64Data.length||(r.int64Data=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.int64Data.push(e.int64());else r.int64Data.push(e.int64());break;case 8:r.name=e.string();break;case 12:r.docString=e.string();break;case 9:r.rawData=e.bytes();break;case 13:r.externalData&&r.externalData.length||(r.externalData=[]),r.externalData.push(c.onnx.StringStringEntryProto.decode(e,e.uint32()));break;case 14:r.dataLocation=e.int32();break;case 10:if(r.doubleData&&r.doubleData.length||(r.doubleData=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.doubleData.push(e.double());else r.doubleData.push(e.double());break;case 11:if(r.uint64Data&&r.uint64Data.length||(r.uint64Data=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.uint64Data.push(e.uint64());else r.uint64Data.push(e.uint64());break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.dims&&e.hasOwnProperty("dims")){if(!Array.isArray(e.dims))return"dims: array expected";for(var t=0;t<e.dims.length;++t)if(!(l.isInteger(e.dims[t])||e.dims[t]&&l.isInteger(e.dims[t].low)&&l.isInteger(e.dims[t].high)))return"dims: integer|Long[] expected"}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&!l.isInteger(e.dataType))return"dataType: integer expected";if(null!=e.segment&&e.hasOwnProperty("segment")&&(n=c.onnx.TensorProto.Segment.verify(e.segment)))return"segment."+n;if(null!=e.floatData&&e.hasOwnProperty("floatData")){if(!Array.isArray(e.floatData))return"floatData: array expected";for(t=0;t<e.floatData.length;++t)if("number"!=typeof e.floatData[t])return"floatData: number[] expected"}if(null!=e.int32Data&&e.hasOwnProperty("int32Data")){if(!Array.isArray(e.int32Data))return"int32Data: array expected";for(t=0;t<e.int32Data.length;++t)if(!l.isInteger(e.int32Data[t]))return"int32Data: integer[] expected"}if(null!=e.stringData&&e.hasOwnProperty("stringData")){if(!Array.isArray(e.stringData))return"stringData: array expected";for(t=0;t<e.stringData.length;++t)if(!(e.stringData[t]&&"number"==typeof e.stringData[t].length||l.isString(e.stringData[t])))return"stringData: buffer[] expected"}if(null!=e.int64Data&&e.hasOwnProperty("int64Data")){if(!Array.isArray(e.int64Data))return"int64Data: array expected";for(t=0;t<e.int64Data.length;++t)if(!(l.isInteger(e.int64Data[t])||e.int64Data[t]&&l.isInteger(e.int64Data[t].low)&&l.isInteger(e.int64Data[t].high)))return"int64Data: integer|Long[] expected"}if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.rawData&&e.hasOwnProperty("rawData")&&!(e.rawData&&"number"==typeof e.rawData.length||l.isString(e.rawData)))return"rawData: buffer expected";if(null!=e.externalData&&e.hasOwnProperty("externalData")){if(!Array.isArray(e.externalData))return"externalData: array expected";for(t=0;t<e.externalData.length;++t){var n;if(n=c.onnx.StringStringEntryProto.verify(e.externalData[t]))return"externalData."+n}}if(null!=e.dataLocation&&e.hasOwnProperty("dataLocation"))switch(e.dataLocation){default:return"dataLocation: enum value expected";case 0:case 1:}if(null!=e.doubleData&&e.hasOwnProperty("doubleData")){if(!Array.isArray(e.doubleData))return"doubleData: array expected";for(t=0;t<e.doubleData.length;++t)if("number"!=typeof e.doubleData[t])return"doubleData: number[] expected"}if(null!=e.uint64Data&&e.hasOwnProperty("uint64Data")){if(!Array.isArray(e.uint64Data))return"uint64Data: array expected";for(t=0;t<e.uint64Data.length;++t)if(!(l.isInteger(e.uint64Data[t])||e.uint64Data[t]&&l.isInteger(e.uint64Data[t].low)&&l.isInteger(e.uint64Data[t].high)))return"uint64Data: integer|Long[] expected"}return null},e.fromObject=function(e){if(e instanceof c.onnx.TensorProto)return e;var t=new c.onnx.TensorProto;if(e.dims){if(!Array.isArray(e.dims))throw TypeError(".onnx.TensorProto.dims: array expected");t.dims=[];for(var n=0;n<e.dims.length;++n)l.Long?(t.dims[n]=l.Long.fromValue(e.dims[n])).unsigned=!1:"string"==typeof e.dims[n]?t.dims[n]=parseInt(e.dims[n],10):"number"==typeof e.dims[n]?t.dims[n]=e.dims[n]:"object"==typeof e.dims[n]&&(t.dims[n]=new l.LongBits(e.dims[n].low>>>0,e.dims[n].high>>>0).toNumber())}if(null!=e.dataType&&(t.dataType=0|e.dataType),null!=e.segment){if("object"!=typeof e.segment)throw TypeError(".onnx.TensorProto.segment: object expected");t.segment=c.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(t.floatData=[],n=0;n<e.floatData.length;++n)t.floatData[n]=Number(e.floatData[n])}if(e.int32Data){if(!Array.isArray(e.int32Data))throw TypeError(".onnx.TensorProto.int32Data: array expected");for(t.int32Data=[],n=0;n<e.int32Data.length;++n)t.int32Data[n]=0|e.int32Data[n]}if(e.stringData){if(!Array.isArray(e.stringData))throw TypeError(".onnx.TensorProto.stringData: array expected");for(t.stringData=[],n=0;n<e.stringData.length;++n)"string"==typeof e.stringData[n]?l.base64.decode(e.stringData[n],t.stringData[n]=l.newBuffer(l.base64.length(e.stringData[n])),0):e.stringData[n].length&&(t.stringData[n]=e.stringData[n])}if(e.int64Data){if(!Array.isArray(e.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");for(t.int64Data=[],n=0;n<e.int64Data.length;++n)l.Long?(t.int64Data[n]=l.Long.fromValue(e.int64Data[n])).unsigned=!1:"string"==typeof e.int64Data[n]?t.int64Data[n]=parseInt(e.int64Data[n],10):"number"==typeof e.int64Data[n]?t.int64Data[n]=e.int64Data[n]:"object"==typeof e.int64Data[n]&&(t.int64Data[n]=new l.LongBits(e.int64Data[n].low>>>0,e.int64Data[n].high>>>0).toNumber())}if(null!=e.name&&(t.name=String(e.name)),null!=e.docString&&(t.docString=String(e.docString)),null!=e.rawData&&("string"==typeof e.rawData?l.base64.decode(e.rawData,t.rawData=l.newBuffer(l.base64.length(e.rawData)),0):e.rawData.length&&(t.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(t.externalData=[],n=0;n<e.externalData.length;++n){if("object"!=typeof e.externalData[n])throw TypeError(".onnx.TensorProto.externalData: object expected");t.externalData[n]=c.onnx.StringStringEntryProto.fromObject(e.externalData[n])}}switch(e.dataLocation){case"DEFAULT":case 0:t.dataLocation=0;break;case"EXTERNAL":case 1:t.dataLocation=1}if(e.doubleData){if(!Array.isArray(e.doubleData))throw TypeError(".onnx.TensorProto.doubleData: array expected");for(t.doubleData=[],n=0;n<e.doubleData.length;++n)t.doubleData[n]=Number(e.doubleData[n])}if(e.uint64Data){if(!Array.isArray(e.uint64Data))throw TypeError(".onnx.TensorProto.uint64Data: array expected");for(t.uint64Data=[],n=0;n<e.uint64Data.length;++n)l.Long?(t.uint64Data[n]=l.Long.fromValue(e.uint64Data[n])).unsigned=!0:"string"==typeof e.uint64Data[n]?t.uint64Data[n]=parseInt(e.uint64Data[n],10):"number"==typeof e.uint64Data[n]?t.uint64Data[n]=e.uint64Data[n]:"object"==typeof e.uint64Data[n]&&(t.uint64Data[n]=new l.LongBits(e.uint64Data[n].low>>>0,e.uint64Data[n].high>>>0).toNumber(!0))}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),t.defaults&&(n.dataType=0,n.segment=null,n.name="",t.bytes===String?n.rawData="":(n.rawData=[],t.bytes!==Array&&(n.rawData=l.newBuffer(n.rawData))),n.docString="",n.dataLocation=t.enums===String?"DEFAULT":0),e.dims&&e.dims.length){n.dims=[];for(var r=0;r<e.dims.length;++r)"number"==typeof e.dims[r]?n.dims[r]=t.longs===String?String(e.dims[r]):e.dims[r]:n.dims[r]=t.longs===String?l.Long.prototype.toString.call(e.dims[r]):t.longs===Number?new l.LongBits(e.dims[r].low>>>0,e.dims[r].high>>>0).toNumber():e.dims[r]}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&(n.dataType=e.dataType),null!=e.segment&&e.hasOwnProperty("segment")&&(n.segment=c.onnx.TensorProto.Segment.toObject(e.segment,t)),e.floatData&&e.floatData.length)for(n.floatData=[],r=0;r<e.floatData.length;++r)n.floatData[r]=t.json&&!isFinite(e.floatData[r])?String(e.floatData[r]):e.floatData[r];if(e.int32Data&&e.int32Data.length)for(n.int32Data=[],r=0;r<e.int32Data.length;++r)n.int32Data[r]=e.int32Data[r];if(e.stringData&&e.stringData.length)for(n.stringData=[],r=0;r<e.stringData.length;++r)n.stringData[r]=t.bytes===String?l.base64.encode(e.stringData[r],0,e.stringData[r].length):t.bytes===Array?Array.prototype.slice.call(e.stringData[r]):e.stringData[r];if(e.int64Data&&e.int64Data.length)for(n.int64Data=[],r=0;r<e.int64Data.length;++r)"number"==typeof e.int64Data[r]?n.int64Data[r]=t.longs===String?String(e.int64Data[r]):e.int64Data[r]:n.int64Data[r]=t.longs===String?l.Long.prototype.toString.call(e.int64Data[r]):t.longs===Number?new l.LongBits(e.int64Data[r].low>>>0,e.int64Data[r].high>>>0).toNumber():e.int64Data[r];if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.rawData&&e.hasOwnProperty("rawData")&&(n.rawData=t.bytes===String?l.base64.encode(e.rawData,0,e.rawData.length):t.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(n.doubleData=[],r=0;r<e.doubleData.length;++r)n.doubleData[r]=t.json&&!isFinite(e.doubleData[r])?String(e.doubleData[r]):e.doubleData[r];if(e.uint64Data&&e.uint64Data.length)for(n.uint64Data=[],r=0;r<e.uint64Data.length;++r)"number"==typeof e.uint64Data[r]?n.uint64Data[r]=t.longs===String?String(e.uint64Data[r]):e.uint64Data[r]:n.uint64Data[r]=t.longs===String?l.Long.prototype.toString.call(e.uint64Data[r]):t.longs===Number?new l.LongBits(e.uint64Data[r].low>>>0,e.uint64Data[r].high>>>0).toNumber(!0):e.uint64Data[r];if(null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),e.externalData&&e.externalData.length)for(n.externalData=[],r=0;r<e.externalData.length;++r)n.externalData[r]=c.onnx.StringStringEntryProto.toObject(e.externalData[r],t);return null!=e.dataLocation&&e.hasOwnProperty("dataLocation")&&(n.dataLocation=t.enums===String?c.onnx.TensorProto.DataLocation[e.dataLocation]:e.dataLocation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.DataType=function(){var e={},t=Object.create(e);return t[e[0]="UNDEFINED"]=0,t[e[1]="FLOAT"]=1,t[e[2]="UINT8"]=2,t[e[3]="INT8"]=3,t[e[4]="UINT16"]=4,t[e[5]="INT16"]=5,t[e[6]="INT32"]=6,t[e[7]="INT64"]=7,t[e[8]="STRING"]=8,t[e[9]="BOOL"]=9,t[e[10]="FLOAT16"]=10,t[e[11]="DOUBLE"]=11,t[e[12]="UINT32"]=12,t[e[13]="UINT64"]=13,t[e[14]="COMPLEX64"]=14,t[e[15]="COMPLEX128"]=15,t[e[16]="BFLOAT16"]=16,t}(),e.Segment=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.begin=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.end=l.Long?l.Long.fromBits(0,0,!1):0,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.begin&&e.hasOwnProperty("begin")&&t.uint32(8).int64(e.begin),null!=e.end&&e.hasOwnProperty("end")&&t.uint32(16).int64(e.end),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorProto.Segment;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.begin=e.int64();break;case 2:r.end=e.int64();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.begin&&e.hasOwnProperty("begin")&&!(l.isInteger(e.begin)||e.begin&&l.isInteger(e.begin.low)&&l.isInteger(e.begin.high))?"begin: integer|Long expected":null!=e.end&&e.hasOwnProperty("end")&&!(l.isInteger(e.end)||e.end&&l.isInteger(e.end.low)&&l.isInteger(e.end.high))?"end: integer|Long expected":null},e.fromObject=function(e){if(e instanceof c.onnx.TensorProto.Segment)return e;var t=new c.onnx.TensorProto.Segment;return null!=e.begin&&(l.Long?(t.begin=l.Long.fromValue(e.begin)).unsigned=!1:"string"==typeof e.begin?t.begin=parseInt(e.begin,10):"number"==typeof e.begin?t.begin=e.begin:"object"==typeof e.begin&&(t.begin=new l.LongBits(e.begin.low>>>0,e.begin.high>>>0).toNumber())),null!=e.end&&(l.Long?(t.end=l.Long.fromValue(e.end)).unsigned=!1:"string"==typeof e.end?t.end=parseInt(e.end,10):"number"==typeof e.end?t.end=e.end:"object"==typeof e.end&&(t.end=new l.LongBits(e.end.low>>>0,e.end.high>>>0).toNumber())),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.begin=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.begin=t.longs===String?"0":0;l.Long?(r=new l.Long(0,0,!1),n.end=t.longs===String?r.toString():t.longs===Number?r.toNumber():r):n.end=t.longs===String?"0":0}return null!=e.begin&&e.hasOwnProperty("begin")&&("number"==typeof e.begin?n.begin=t.longs===String?String(e.begin):e.begin:n.begin=t.longs===String?l.Long.prototype.toString.call(e.begin):t.longs===Number?new l.LongBits(e.begin.low>>>0,e.begin.high>>>0).toNumber():e.begin),null!=e.end&&e.hasOwnProperty("end")&&("number"==typeof e.end?n.end=t.longs===String?String(e.end):e.end:n.end=t.longs===String?l.Long.prototype.toString.call(e.end):t.longs===Number?new l.LongBits(e.end.low>>>0,e.end.high>>>0).toNumber():e.end),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e.DataLocation=function(){var e={},t=Object.create(e);return t[e[0]="DEFAULT"]=0,t[e[1]="EXTERNAL"]=1,t}(),e}(),o.TensorShapeProto=function(){function e(e){if(this.dim=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.dim=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.dim&&e.dim.length)for(var n=0;n<e.dim.length;++n)c.onnx.TensorShapeProto.Dimension.encode(e.dim[n],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorShapeProto;e.pos<n;){var i=e.uint32();i>>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(c.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&i)}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.dim&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var t=0;t<e.dim.length;++t){var n=c.onnx.TensorShapeProto.Dimension.verify(e.dim[t]);if(n)return"dim."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.TensorShapeProto)return e;var t=new c.onnx.TensorShapeProto;if(e.dim){if(!Array.isArray(e.dim))throw TypeError(".onnx.TensorShapeProto.dim: array expected");t.dim=[];for(var n=0;n<e.dim.length;++n){if("object"!=typeof e.dim[n])throw TypeError(".onnx.TensorShapeProto.dim: object expected");t.dim[n]=c.onnx.TensorShapeProto.Dimension.fromObject(e.dim[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.dim=[]),e.dim&&e.dim.length){n.dim=[];for(var r=0;r<e.dim.length;++r)n.dim[r]=c.onnx.TensorShapeProto.Dimension.toObject(e.dim[r],t)}return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.Dimension=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t;return e.prototype.dimValue=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.dimParam="",e.prototype.denotation="",Object.defineProperty(e.prototype,"value",{get:l.oneOfGetter(t=["dimValue","dimParam"]),set:l.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.dimValue&&e.hasOwnProperty("dimValue")&&t.uint32(8).int64(e.dimValue),null!=e.dimParam&&e.hasOwnProperty("dimParam")&&t.uint32(18).string(e.dimParam),null!=e.denotation&&e.hasOwnProperty("denotation")&&t.uint32(26).string(e.denotation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorShapeProto.Dimension;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.dimValue=e.int64();break;case 2:r.dimParam=e.string();break;case 3:r.denotation=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.dimValue&&e.hasOwnProperty("dimValue")&&(t.value=1,!(l.isInteger(e.dimValue)||e.dimValue&&l.isInteger(e.dimValue.low)&&l.isInteger(e.dimValue.high))))return"dimValue: integer|Long expected";if(null!=e.dimParam&&e.hasOwnProperty("dimParam")){if(1===t.value)return"value: multiple values";if(t.value=1,!l.isString(e.dimParam))return"dimParam: string expected"}return null!=e.denotation&&e.hasOwnProperty("denotation")&&!l.isString(e.denotation)?"denotation: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.TensorShapeProto.Dimension)return e;var t=new c.onnx.TensorShapeProto.Dimension;return null!=e.dimValue&&(l.Long?(t.dimValue=l.Long.fromValue(e.dimValue)).unsigned=!1:"string"==typeof e.dimValue?t.dimValue=parseInt(e.dimValue,10):"number"==typeof e.dimValue?t.dimValue=e.dimValue:"object"==typeof e.dimValue&&(t.dimValue=new l.LongBits(e.dimValue.low>>>0,e.dimValue.high>>>0).toNumber())),null!=e.dimParam&&(t.dimParam=String(e.dimParam)),null!=e.denotation&&(t.denotation=String(e.denotation)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.denotation=""),null!=e.dimValue&&e.hasOwnProperty("dimValue")&&("number"==typeof e.dimValue?n.dimValue=t.longs===String?String(e.dimValue):e.dimValue:n.dimValue=t.longs===String?l.Long.prototype.toString.call(e.dimValue):t.longs===Number?new l.LongBits(e.dimValue.low>>>0,e.dimValue.high>>>0).toNumber():e.dimValue,t.oneofs&&(n.value="dimValue")),null!=e.dimParam&&e.hasOwnProperty("dimParam")&&(n.dimParam=e.dimParam,t.oneofs&&(n.value="dimParam")),null!=e.denotation&&e.hasOwnProperty("denotation")&&(n.denotation=e.denotation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e}(),o.TypeProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t;return e.prototype.tensorType=null,e.prototype.denotation="",Object.defineProperty(e.prototype,"value",{get:l.oneOfGetter(t=["tensorType"]),set:l.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.tensorType&&e.hasOwnProperty("tensorType")&&c.onnx.TypeProto.Tensor.encode(e.tensorType,t.uint32(10).fork()).ldelim(),null!=e.denotation&&e.hasOwnProperty("denotation")&&t.uint32(50).string(e.denotation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TypeProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.tensorType=c.onnx.TypeProto.Tensor.decode(e,e.uint32());break;case 6:r.denotation=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.tensorType&&e.hasOwnProperty("tensorType")){var t=c.onnx.TypeProto.Tensor.verify(e.tensorType);if(t)return"tensorType."+t}return null!=e.denotation&&e.hasOwnProperty("denotation")&&!l.isString(e.denotation)?"denotation: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.TypeProto)return e;var t=new c.onnx.TypeProto;if(null!=e.tensorType){if("object"!=typeof e.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");t.tensorType=c.onnx.TypeProto.Tensor.fromObject(e.tensorType)}return null!=e.denotation&&(t.denotation=String(e.denotation)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.denotation=""),null!=e.tensorType&&e.hasOwnProperty("tensorType")&&(n.tensorType=c.onnx.TypeProto.Tensor.toObject(e.tensorType,t),t.oneofs&&(n.value="tensorType")),null!=e.denotation&&e.hasOwnProperty("denotation")&&(n.denotation=e.denotation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.Tensor=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.elemType=0,e.prototype.shape=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.elemType&&e.hasOwnProperty("elemType")&&t.uint32(8).int32(e.elemType),null!=e.shape&&e.hasOwnProperty("shape")&&c.onnx.TensorShapeProto.encode(e.shape,t.uint32(18).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TypeProto.Tensor;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.elemType=e.int32();break;case 2:r.shape=c.onnx.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.elemType&&e.hasOwnProperty("elemType")&&!l.isInteger(e.elemType))return"elemType: integer expected";if(null!=e.shape&&e.hasOwnProperty("shape")){var t=c.onnx.TensorShapeProto.verify(e.shape);if(t)return"shape."+t}return null},e.fromObject=function(e){if(e instanceof c.onnx.TypeProto.Tensor)return e;var t=new c.onnx.TypeProto.Tensor;if(null!=e.elemType&&(t.elemType=0|e.elemType),null!=e.shape){if("object"!=typeof e.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");t.shape=c.onnx.TensorShapeProto.fromObject(e.shape)}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.elemType=0,n.shape=null),null!=e.elemType&&e.hasOwnProperty("elemType")&&(n.elemType=e.elemType),null!=e.shape&&e.hasOwnProperty("shape")&&(n.shape=c.onnx.TensorShapeProto.toObject(e.shape,t)),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e}(),o.OperatorSetIdProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.domain="",e.prototype.version=l.Long?l.Long.fromBits(0,0,!1):0,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(10).string(e.domain),null!=e.version&&e.hasOwnProperty("version")&&t.uint32(16).int64(e.version),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.OperatorSetIdProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.domain=e.string();break;case 2:r.version=e.int64();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.domain&&e.hasOwnProperty("domain")&&!l.isString(e.domain)?"domain: string expected":null!=e.version&&e.hasOwnProperty("version")&&!(l.isInteger(e.version)||e.version&&l.isInteger(e.version.low)&&l.isInteger(e.version.high))?"version: integer|Long expected":null},e.fromObject=function(e){if(e instanceof c.onnx.OperatorSetIdProto)return e;var t=new c.onnx.OperatorSetIdProto;return null!=e.domain&&(t.domain=String(e.domain)),null!=e.version&&(l.Long?(t.version=l.Long.fromValue(e.version)).unsigned=!1:"string"==typeof e.version?t.version=parseInt(e.version,10):"number"==typeof e.version?t.version=e.version:"object"==typeof e.version&&(t.version=new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults)if(n.domain="",l.Long){var r=new l.Long(0,0,!1);n.version=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.version=t.longs===String?"0":0;return null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),null!=e.version&&e.hasOwnProperty("version")&&("number"==typeof e.version?n.version=t.longs===String?String(e.version):e.version:n.version=t.longs===String?l.Long.prototype.toString.call(e.version):t.longs===Number?new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o),e.exports=c},2100:(e,t,n)=>{"use strict";e.exports=n(9482)},9482:(e,t,n)=>{"use strict";var r=t;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=i,i()},1408:(e,t,n)=>{"use strict";e.exports=u;var r,i=n(9693),o=i.LongBits,s=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function u(e){this.buf=e,this.pos=0,this.len=e.length}var l,c="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new u(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new u(e);throw Error("illegal buffer")},d=function(){return i.Buffer?function(e){return(u.create=function(e){return i.Buffer.isBuffer(e)?new r(e):c(e)})(e)}:c};function h(){var e=new o(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}u.create=d(),u.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,u.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},u.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},u.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)},u.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},u.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},u._configure=function(e){r=e,u.create=d(),r._configure();var t=i.Long?"toLong":"toNumber";i.merge(u.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},593:(e,t,n)=>{"use strict";e.exports=o;var r=n(1408);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(e){r.call(this,e)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o._configure()},5054:e=>{"use strict";e.exports={}},5994:(e,t,n)=>{"use strict";t.Service=n(7948)},7948:(e,t,n)=>{"use strict";e.exports=i;var r=n(9693);function i(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function e(t,n,i,o,s){if(!o)throw TypeError("request must be specified");var a=this;if(!s)return r.asPromise(e,a,t,n,i,o);if(a.rpcImpl)try{return a.rpcImpl(t,n[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(e,n){if(e)return a.emit("error",e,t),s(e);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return a.emit("error",e,t),s(e)}return a.emit("data",n,t),s(null,n)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){s(e)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(e,t,n)=>{"use strict";e.exports=i;var r=n(9693);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return o;var t=e<0;t&&(e=-e);var n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(e){if("number"==typeof e)return i.fromNumber(e);if(r.isString(e)){if(!r.Long)return i.fromNumber(parseInt(e,10));e=r.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):o},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===s?o:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},9693:function(e,t,n){"use strict";var r=t;function i(e,t,n){for(var r=Object.keys(t),i=0;i<r.length;++i)void 0!==e[r[i]]&&n||(e[r[i]]=t[r[i]]);return e}function o(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&i(this,n)}return(t.prototype=Object.create(Error.prototype)).constructor=t,Object.defineProperty(t.prototype,"name",{get:function(){return e}}),t.prototype.toString=function(){return this.name+": "+this.message},t}r.asPromise=n(4537),r.base64=n(7419),r.EventEmitter=n(9211),r.float=n(945),r.inquire=n(7199),r.utf8=n(4997),r.pool=n(6662),r.LongBits=n(1945),r.isNode=Boolean(void 0!==n.g&&n.g&&n.g.process&&n.g.process.versions&&n.g.process.versions.node),r.global=r.isNode&&n.g||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},r.isString=function(e){return"string"==typeof e||e instanceof String},r.isObject=function(e){return e&&"object"==typeof e},r.isset=r.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},r.merge=i,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=o,r.ProtocolError=o("ProtocolError"),r.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},r.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var e=r.Buffer;e?(r._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},r._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):r._Buffer_from=r._Buffer_allocUnsafe=null}},1173:(e,t,n)=>{"use strict";e.exports=d;var r,i=n(9693),o=i.LongBits,s=i.base64,a=i.utf8;function u(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function l(){}function c(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function d(){this.len=0,this.head=new u(l,0,0),this.tail=this.head,this.states=null}var h=function(){return i.Buffer?function(){return(d.create=function(){return new r})()}:function(){return new d}};function p(e,t,n){t[n]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function m(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}d.create=h(),d.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.prototype._push=function(e,t,n){return this.tail=this.tail.next=new u(e,t,n),this.len+=t,this},f.prototype=Object.create(u.prototype),f.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},d.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},d.prototype.int32=function(e){return e<0?this._push(g,10,o.fromNumber(e)):this.uint32(e)},d.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},d.prototype.uint64=function(e){var t=o.from(e);return this._push(g,t.length(),t)},d.prototype.int64=d.prototype.uint64,d.prototype.sint64=function(e){var t=o.from(e).zzEncode();return this._push(g,t.length(),t)},d.prototype.bool=function(e){return this._push(p,1,e?1:0)},d.prototype.fixed32=function(e){return this._push(m,4,e>>>0)},d.prototype.sfixed32=d.prototype.fixed32,d.prototype.fixed64=function(e){var t=o.from(e);return this._push(m,4,t.lo)._push(m,4,t.hi)},d.prototype.sfixed64=d.prototype.fixed64,d.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},d.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var b=i.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var r=0;r<e.length;++r)t[n+r]=e[r]};d.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(p,1,0);if(i.isString(e)){var n=d.alloc(t=s.length(e));s.decode(e,n,0),e=n}return this.uint32(t)._push(b,t,e)},d.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},d.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new u(l,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(l,0,0),this.len=0),this},d.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},d.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},d._configure=function(e){r=e,d.create=h(),r._configure()}},3155:(e,t,n)=>{"use strict";e.exports=o;var r=n(1173);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(){r.call(this)}function s(e,t,n){e.length<40?i.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var r=0;r<e.length;)t[n++]=e[r++]}},o.prototype.bytes=function(e){i.isString(e)&&(e=i._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(s,t,e),this},o._configure()},4154:e=>{"use strict";e.exports='"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'},7067:()=>{},1296:()=>{},760:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(e,t,n)=>{"use strict";n.r(t),n.d(t,{flatbuffers:()=>r});var r={};r.Offset,r.Table,r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(e,t){this.low=0|e,this.high=0|t},r.Long.create=function(e,t){return 0==e&&0==t?r.Long.ZERO:new r.Long(e,t)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(e){return this.low==e.low&&this.high==e.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(e){if(e)t=e;else var t=1024;this.bb=r.ByteBuffer.allocate(t),this.space=t,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.forceDefaults=function(e){this.force_defaults=e},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(e,t){e>this.minalign&&(this.minalign=e);for(var n=1+~(this.bb.capacity()-this.space+t)&e-1;this.space<n+e+t;){var i=this.bb.capacity();this.bb=r.Builder.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)},r.Builder.prototype.pad=function(e){for(var t=0;t<e;t++)this.bb.writeInt8(--this.space,0)},r.Builder.prototype.writeInt8=function(e){this.bb.writeInt8(this.space-=1,e)},r.Builder.prototype.writeInt16=function(e){this.bb.writeInt16(this.space-=2,e)},r.Builder.prototype.writeInt32=function(e){this.bb.writeInt32(this.space-=4,e)},r.Builder.prototype.writeInt64=function(e){this.bb.writeInt64(this.space-=8,e)},r.Builder.prototype.writeFloat32=function(e){this.bb.writeFloat32(this.space-=4,e)},r.Builder.prototype.writeFloat64=function(e){this.bb.writeFloat64(this.space-=8,e)},r.Builder.prototype.addInt8=function(e){this.prep(1,0),this.writeInt8(e)},r.Builder.prototype.addInt16=function(e){this.prep(2,0),this.writeInt16(e)},r.Builder.prototype.addInt32=function(e){this.prep(4,0),this.writeInt32(e)},r.Builder.prototype.addInt64=function(e){this.prep(8,0),this.writeInt64(e)},r.Builder.prototype.addFloat32=function(e){this.prep(4,0),this.writeFloat32(e)},r.Builder.prototype.addFloat64=function(e){this.prep(8,0),this.writeFloat64(e)},r.Builder.prototype.addFieldInt8=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))},r.Builder.prototype.addFieldInt16=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))},r.Builder.prototype.addFieldInt32=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))},r.Builder.prototype.addFieldInt64=function(e,t,n){!this.force_defaults&&t.equals(n)||(this.addInt64(t),this.slot(e))},r.Builder.prototype.addFieldFloat32=function(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))},r.Builder.prototype.addFieldFloat64=function(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))},r.Builder.prototype.addFieldOffset=function(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))},r.Builder.prototype.addFieldStruct=function(e,t,n){t!=n&&(this.nested(t),this.slot(e))},r.Builder.prototype.nested=function(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")},r.Builder.prototype.notNested=function(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")},r.Builder.prototype.slot=function(e){this.vtable[e]=this.offset()},r.Builder.prototype.offset=function(){return this.bb.capacity()-this.space},r.Builder.growByteBuffer=function(e){var t=e.capacity();if(3221225472&t)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");var n=t<<1,i=r.ByteBuffer.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i},r.Builder.prototype.addOffset=function(e){this.prep(r.SIZEOF_INT,0),this.writeInt32(this.offset()-e+r.SIZEOF_INT)},r.Builder.prototype.startObject=function(e){this.notNested(),null==this.vtable&&(this.vtable=[]),this.vtable_in_use=e;for(var t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()},r.Builder.prototype.endObject=function(){if(null==this.vtable||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);for(var e=this.offset(),t=this.vtable_in_use-1;t>=0&&0==this.vtable[t];t--);for(var n=t+1;t>=0;t--)this.addInt16(0!=this.vtable[t]?e-this.vtable[t]:0);this.addInt16(e-this.object_start);var i=(n+2)*r.SIZEOF_SHORT;this.addInt16(i);var o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){var a=this.bb.capacity()-this.vtables[t];if(i==this.bb.readInt16(a)){for(var u=r.SIZEOF_SHORT;u<i;u+=r.SIZEOF_SHORT)if(this.bb.readInt16(s+u)!=this.bb.readInt16(a+u))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e},r.Builder.prototype.finish=function(e,t,n){var i=n?r.SIZE_PREFIX_LENGTH:0;if(t){var o=t;if(this.prep(this.minalign,r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH+i),o.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var s=r.FILE_IDENTIFIER_LENGTH-1;s>=0;s--)this.writeInt8(o.charCodeAt(s))}this.prep(this.minalign,r.SIZEOF_INT+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(e,t){this.finish(e,t,!0)},r.Builder.prototype.requiredField=function(e,t){var n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+t))throw new Error("FlatBuffers: field "+t+" must be set")},r.Builder.prototype.startVector=function(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(r.SIZEOF_INT,e*t),this.prep(n,e*t)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(e){if(e instanceof Uint8Array)var t=e;else{t=[];for(var n=0;n<e.length;){var r,i=e.charCodeAt(n++);(r=i<55296||i>=56320?i:(i<<10)+e.charCodeAt(n++)+-56613888)<128?t.push(r):(r<2048?t.push(r>>6&31|192):(r<65536?t.push(r>>12&15|224):t.push(r>>18&7|240,r>>12&63|128),t.push(r>>6&63|128)),t.push(63&r|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length),n=0;for(var o=this.space,s=this.bb.bytes();n<t.length;n++)s[o++]=t[n];return this.endVector()},r.Builder.prototype.createLong=function(e,t){return r.Long.create(e,t)},r.ByteBuffer=function(e){this.bytes_=e,this.position_=0},r.ByteBuffer.allocate=function(e){return new r.ByteBuffer(new Uint8Array(e))},r.ByteBuffer.prototype.clear=function(){this.position_=0},r.ByteBuffer.prototype.bytes=function(){return this.bytes_},r.ByteBuffer.prototype.position=function(){return this.position_},r.ByteBuffer.prototype.setPosition=function(e){this.position_=e},r.ByteBuffer.prototype.capacity=function(){return this.bytes_.length},r.ByteBuffer.prototype.readInt8=function(e){return this.readUint8(e)<<24>>24},r.ByteBuffer.prototype.readUint8=function(e){return this.bytes_[e]},r.ByteBuffer.prototype.readInt16=function(e){return this.readUint16(e)<<16>>16},r.ByteBuffer.prototype.readUint16=function(e){return this.bytes_[e]|this.bytes_[e+1]<<8},r.ByteBuffer.prototype.readInt32=function(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24},r.ByteBuffer.prototype.readUint32=function(e){return this.readInt32(e)>>>0},r.ByteBuffer.prototype.readInt64=function(e){return new r.Long(this.readInt32(e),this.readInt32(e+4))},r.ByteBuffer.prototype.readUint64=function(e){return new r.Long(this.readUint32(e),this.readUint32(e+4))},r.ByteBuffer.prototype.readFloat32=function(e){return r.int32[0]=this.readInt32(e),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(e){return r.int32[r.isLittleEndian?0:1]=this.readInt32(e),r.int32[r.isLittleEndian?1:0]=this.readInt32(e+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(e,t){this.bytes_[e]=t},r.ByteBuffer.prototype.writeUint8=function(e,t){this.bytes_[e]=t},r.ByteBuffer.prototype.writeInt16=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8},r.ByteBuffer.prototype.writeUint16=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8},r.ByteBuffer.prototype.writeInt32=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24},r.ByteBuffer.prototype.writeUint32=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24},r.ByteBuffer.prototype.writeInt64=function(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)},r.ByteBuffer.prototype.writeUint64=function(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)},r.ByteBuffer.prototype.writeFloat32=function(e,t){r.float32[0]=t,this.writeInt32(e,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(e,t){r.float64[0]=t,this.writeInt32(e,r.int32[r.isLittleEndian?0:1]),this.writeInt32(e+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length<this.position_+r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");for(var e="",t=0;t<r.FILE_IDENTIFIER_LENGTH;t++)e+=String.fromCharCode(this.readInt8(this.position_+r.SIZEOF_INT+t));return e},r.ByteBuffer.prototype.__offset=function(e,t){var n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0},r.ByteBuffer.prototype.__union=function(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e},r.ByteBuffer.prototype.__string=function(e,t){e+=this.readInt32(e);var n=this.readInt32(e),i="",o=0;if(e+=r.SIZEOF_INT,t===r.Encoding.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;o<n;){var s,a=this.readUint8(e+o++);if(a<192)s=a;else{var u=this.readUint8(e+o++);if(a<224)s=(31&a)<<6|63&u;else{var l=this.readUint8(e+o++);s=a<240?(15&a)<<12|(63&u)<<6|63&l:(7&a)<<18|(63&u)<<12|(63&l)<<6|63&this.readUint8(e+o++)}}s<65536?i+=String.fromCharCode(s):(s-=65536,i+=String.fromCharCode(55296+(s>>10),56320+(1023&s)))}return i},r.ByteBuffer.prototype.__indirect=function(e){return e+this.readInt32(e)},r.ByteBuffer.prototype.__vector=function(e){return e+this.readInt32(e)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(e){return this.readInt32(e+this.readInt32(e))},r.ByteBuffer.prototype.__has_identifier=function(e){if(e.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var t=0;t<r.FILE_IDENTIFIER_LENGTH;t++)if(e.charCodeAt(t)!=this.readInt8(this.position_+r.SIZEOF_INT+t))return!1;return!0},r.ByteBuffer.prototype.createLong=function(e,t){return r.Long.create(e,t)}}},__webpack_module_cache__={};function __nested_webpack_require_606622__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__nested_webpack_require_606622__),n.exports}__nested_webpack_require_606622__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __nested_webpack_require_606622__.d(t,{a:t}),t},__nested_webpack_require_606622__.d=(e,t)=>{for(var n in t)__nested_webpack_require_606622__.o(t,n)&&!__nested_webpack_require_606622__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__nested_webpack_require_606622__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__nested_webpack_require_606622__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__nested_webpack_require_606622__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __nested_webpack_exports__=__nested_webpack_require_606622__(1057);return __nested_webpack_exports__})(),module.exports=t()},793:e=>{"use strict";function t(e){try{return JSON.stringify(e)}catch(e){return'"[Circular]"'}}e.exports=function(e,n,r){var i=r&&r.stringify||t;if("object"==typeof e&&null!==e){var o=n.length+1;if(1===o)return e;var s=new Array(o);s[0]=i(e);for(var a=1;a<o;a++)s[a]=i(n[a]);return s.join(" ")}if("string"!=typeof e)return e;var u=n.length;if(0===u)return e;for(var l="",c=0,d=-1,h=e&&e.length||0,p=0;p<h;){if(37===e.charCodeAt(p)&&p+1<h){switch(d=d>-1?d:0,e.charCodeAt(p+1)){case 100:case 102:if(c>=u)break;if(null==n[c])break;d<p&&(l+=e.slice(d,p)),l+=Number(n[c]),d=p+2,p++;break;case 105:if(c>=u)break;if(null==n[c])break;d<p&&(l+=e.slice(d,p)),l+=Math.floor(Number(n[c])),d=p+2,p++;break;case 79:case 111:case 106:if(c>=u)break;if(void 0===n[c])break;d<p&&(l+=e.slice(d,p));var f=typeof n[c];if("string"===f){l+="'"+n[c]+"'",d=p+2,p++;break}if("function"===f){l+=n[c].name||"<anonymous>",d=p+2,p++;break}l+=i(n[c]),d=p+2,p++;break;case 115:if(c>=u)break;d<p&&(l+=e.slice(d,p)),l+=String(n[c]),d=p+2,p++;break;case 37:d<p&&(l+=e.slice(d,p)),l+="%",d=p+2,p++,c--}++c}++p}return-1===d?e:(d<h&&(l+=e.slice(d)),l)}},955:function(e){var t;t=()=>(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{RingBuffer:()=>n});class n{static fromArray(e,t=0){const r=new n(t);return r.fromArray(e,0===t),r}constructor(e){if(this.buffer=[],this.pos=0,e<0)throw new RangeError("Invalid size.");this.size=e}getSize(){return this.size}getPos(){return this.pos}getBufferLength(){return this.buffer.length}add(...e){e.forEach((e=>{this.buffer[this.pos]=e,this.pos=(this.pos+1)%this.size}))}get(e){if(e<0&&(e+=this.buffer.length),!(e<0||e>this.buffer.length))return this.buffer.length<this.size?this.buffer[e]:this.buffer[(this.pos+e)%this.size]}getFirst(){return this.get(0)}getLast(){return this.get(-1)}getFirstN(e){return 0===e?[]:e<0?this.getLastN(-e):this.toArray().slice(0,e)}getLastN(e){return 0===e?[]:e<0?this.getFirstN(-e):this.toArray().slice(-e)}remove(e,t=1){if(e<0&&(e+=this.buffer.length),e<0||e>this.buffer.length)return[];const n=this.toArray(),r=n.splice(e,t);return this.fromArray(n),r}removeFirst(){return this.remove(0)[0]}removeLast(){return this.remove(-1)[0]}toArray(){return this.buffer.slice(this.pos).concat(this.buffer.slice(0,this.pos))}fromArray(e,t=!1){if(!Array.isArray(e))throw new TypeError("Input value is not an array.");t&&this.resize(e.length),0!==this.size&&(this.buffer=e.slice(-this.size),this.pos=this.buffer.length%this.size)}clear(){this.buffer=[],this.pos=0}resize(e){if(e<0)throw new RangeError("The size does not allow negative values.");if(0===e)this.clear();else if(e!==this.size){const t=this.toArray();this.fromArray(t.slice(-e)),this.pos=this.buffer.length%e}this.size=e}isFull(){return this.buffer.length===this.size}isEmpty(){return 0===this.buffer.length}}return t})(),e.exports=t()},963:e=>{"use strict";const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const r=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++)n=r[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+n+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(n.attribute=e.substring(t+1,r),n.value=e.substring(r+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const r=t.matchPrefix(e+n,"a=ice-ufrag:")[0],i=t.matchPrefix(e+n,"a=ice-pwd:")[0];return r&&i?{usernameFragment:r.substring(12),password:i.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");n.profile=r[2];for(let i=3;i<r.length;i++){const o=r[i],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const r=t.parseRtpMap(s),i=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(r.parameters=i.length?t.parseFmtp(i[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{i.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let r="";r+="m="+e+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let i=0;return n.codecs.forEach((e=>{e.maxptime>i&&(i=e.maxptime)})),i>0&&(r+="a=maxptime:"+i+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const n=[],r=t.parseRtpParameters(e),i=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let u;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(u=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&u&&(t.rtx={ssrc:u}),n.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.push({ssrc:a});let c=t.matchPrefix(e,"b=");return c.length&&(c=0===c[0].indexOf("b=TIAS:")?parseInt(c[0].substring(7),10):0===c[0].indexOf("b=AS:")?1e3*parseInt(c[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=c}))),n},t.parseRtcpParameters=function(e){const n={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=i.length>0,n.compound=0===i.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};const i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0?(n=i[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let i;r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,r){let i;const o=void 0!==n?n:2;return i=e||t.generateSessionId(),"v=0\r\no="+(r||"thisisadapterortc")+" "+i+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t},874:(e,t,n)=>{"use strict";const r=n(793);e.exports=d;const i=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},o={mapHttpRequest:b,mapHttpResponse:b,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:b,res:b,err:g,errWithCause:g};function s(e,t){return"silent"===e?1/0:t.levels.values[e]}const a=Symbol("pino.logFuncs"),u=Symbol("pino.hierarchy"),l={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function c(e,t){const n={logger:t,parent:e[u]};t[u]=n}function d(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const n=e.browser.write||i;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},o=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,r);let u=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(u=!1);const g=Object.keys(e.customLevels||{}),b=["error","fatal","warn","info","debug","trace"].concat(g);"function"==typeof n&&b.forEach((function(e){n[e]=n})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const y=e.level||"info",w=Object.create(n);w.log||(w.log=v),function(e,t,n){const r={};t.forEach((e=>{r[e]=n[e]?n[e]:i[e]||i[l[e]||"log"]||v})),e[a]=r}(w,b,n),c({},w),Object.defineProperty(w,"levelVal",{get:function(){return s(this.level,this)}}),Object.defineProperty(w,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,h(this,S,w,"error"),h(this,S,w,"fatal"),h(this,S,w,"warn"),h(this,S,w,"info"),h(this,S,w,"debug"),h(this,S,w,"trace"),g.forEach((e=>{h(this,S,w,e)}))}});const S={transmit:t,serialize:o,asObject:e.browser.asObject,formatters:e.browser.formatters,levels:b,timestamp:m(e)};return w.levels=function(e){const t=e.customLevels||{};return{values:Object.assign({},d.levels.values,t),labels:Object.assign({},d.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(n){t[e[n]]=n})),t}(t))}}(e),w.level=y,w.setMaxListeners=w.getMaxListeners=w.emit=w.addListener=w.on=w.prependListener=w.once=w.prependOnceListener=w.removeListener=w.removeAllListeners=w.listeners=w.listenerCount=w.eventNames=w.write=w.flush=v,w.serializers=r,w._serialize=o,w._stdErrSerialize=u,w.child=function(n,i){if(!n)throw new Error("missing bindings for child Pino");i=i||{},o&&n.serializers&&(i.serializers=n.serializers);const s=i.serializers;if(o&&s){var a=Object.assign({},r,s),u=!0===e.browser.serialize?Object.keys(a):o;delete n.serializers,p([n],u,a,this._stdErrSerialize)}function l(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,a&&(this.serializers=a,this._serialize=u),t&&(this._logEvent=f([].concat(e._logEvent.bindings,n)))}l.prototype=this;const d=new l(this);return c(this,d),d.level=this.level,d},t&&(w._logEvent=f()),w}function h(e,t,n,o){if(Object.defineProperty(e,o,{value:s(e.level,n)>s(o,n)?v:n[a][o],writable:!0,enumerable:!0,configurable:!0}),!t.transmit&&e[o]===v)return;e[o]=function(e,t,n,o){return u=e[a][o],function(){const a=t.timestamp(),l=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===i?i:this;for(var d=0;d<l.length;d++)l[d]=arguments[d];if(t.serialize&&!t.asObject&&p(l,this._serialize,this.serializers,this._stdErrSerialize),t.asObject||t.formatters?u.call(c,function(e,t,n,i,o={}){const{level:s=(()=>e.levels.values[t]),log:a=(e=>e)}=o;e._serialize&&p(n,e._serialize,e.serializers,e._stdErrSerialize);const u=n.slice();let l=u[0];const c={};i&&(c.time=i),c.level=s(t,e.levels.values[t]);let d=1+(0|e._childLevel);if(d<1&&(d=1),null!==l&&"object"==typeof l){for(;d--&&"object"==typeof u[0];)Object.assign(c,u.shift());l=u.length?r(u.shift(),u):void 0}else"string"==typeof l&&(l=r(u.shift(),u));return void 0!==l&&(c.msg=l),a(c)}(this,o,l,a,t.formatters)):u.apply(c,l),t.transmit){const r=t.transmit.level||e._level,i=n.levels.values[r],u=n.levels.values[o];if(u<i)return;!function(e,t,n){const r=t.send,i=t.ts,o=t.methodLevel,s=t.methodValue,a=t.val,u=e._logEvent.bindings;p(n,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=i,e._logEvent.messages=n.filter((function(e){return-1===u.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=s,r(o,e._logEvent,a),e._logEvent=f(u)}(this,{ts:a,methodLevel:o,methodValue:u,transmitLevel:r,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:s(e._level,n)},l)}};var u}(e,t,n,o);const l=function(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[u];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}(e);0!==l.length&&(e[o]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(l,e[o]))}function p(e,t,n,r){for(const i in e)if(r&&e[i]instanceof Error)e[i]=d.stdSerializers.err(e[i]);else if("object"==typeof e[i]&&!Array.isArray(e[i]))for(const r in e[i])t&&t.indexOf(r)>-1&&r in n&&(e[i][r]=n[r](e[i][r]))}function f(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function g(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)void 0===t[n]&&(t[n]=e[n]);return t}function m(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?w:S}function b(){return{}}function y(e){return e}function v(){}function w(){return!1}function S(){return Date.now()}d.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},d.stdSerializers=o,d.stdTimeFunctions=Object.assign({},{nullTime:w,epochTime:S,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),e.exports.default=d,e.exports.pino=d}},__webpack_module_cache__={},leafPrototypes,getProto,inProgress,dataWebpackPrefix;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.m=__webpack_modules__,__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var n=Object.create(null);__webpack_require__.r(n);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var i=2&t&&e;"object"==typeof i&&!~leafPrototypes.indexOf(i);i=getProto(i))Object.getOwnPropertyNames(i).forEach((t=>r[t]=()=>e[t]));return r.default=()=>e,__webpack_require__.d(n,r),n},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce(((t,n)=>(__webpack_require__.f[n](e,t),t)),[])),__webpack_require__.u=e=>e+".index.js",__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),inProgress={},dataWebpackPrefix="Uneeq:",__webpack_require__.l=(e,t,n,r)=>{if(inProgress[e])inProgress[e].push(t);else{var i,o;if(void 0!==n)for(var s=document.getElementsByTagName("script"),a=0;a<s.length;a++){var u=s[a];if(u.getAttribute("src")==e||u.getAttribute("data-webpack")==dataWebpackPrefix+n){i=u;break}}i||(o=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,__webpack_require__.nc&&i.setAttribute("nonce",__webpack_require__.nc),i.setAttribute("data-webpack",dataWebpackPrefix+n),i.src=e),inProgress[e]=[t];var l=(t,n)=>{i.onerror=i.onload=null,clearTimeout(c);var r=inProgress[e];if(delete inProgress[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach((e=>e(n))),t)return t(n)},c=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),o&&document.head.appendChild(i)}},__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var r=n.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=n[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})(),(()=>{var e={792:0};__webpack_require__.f.j=(t,n)=>{var r=__webpack_require__.o(e,t)?e[t]:void 0;if(0!==r)if(r)n.push(r[2]);else{var i=new Promise(((n,i)=>r=e[t]=[n,i]));n.push(r[2]=i);var o=__webpack_require__.p+__webpack_require__.u(t),s=new Error;__webpack_require__.l(o,(n=>{if(__webpack_require__.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var i=n&&("load"===n.type?"missing":n.type),o=n&&n.target&&n.target.src;s.message="Loading chunk "+t+" failed.\n("+i+": "+o+")",s.name="ChunkLoadError",s.type=i,s.request=o,r[1](s)}}),"chunk-"+t,t)}};var t=(t,n)=>{var r,i,[o,s,a]=n,u=0;if(o.some((t=>0!==e[t]))){for(r in s)__webpack_require__.o(s,r)&&(__webpack_require__.m[r]=s[r]);a&&a(__webpack_require__)}for(t&&t(n);u<o.length;u++)i=o[u],__webpack_require__.o(e,i)&&e[i]&&e[i][0](),e[i]=0},n=Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})();var __webpack_exports__={};return(()=>{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{AvatarAnswerMessage:()=>In,AvatarStartedSpeakingMessage:()=>Ln,AvatarStoppedSpeakingMessage:()=>Fn,CameraAnchorDistance:()=>Ji,CameraAnchorHorizontal:()=>Qi,CustomMetadataUpdated:()=>Xn,DeviceErrorMessage:()=>kn,DigitalHumanMuted:()=>qn,DigitalHumanPlayedInMutedModeSuccess:()=>Hn,DigitalHumanUnmuted:()=>Wn,EnableMicrophoneUpdatedMessage:()=>Kn,LogLevel:()=>e,PromptRequestMessage:()=>Jn,PromptResultMessage:()=>Qn,SceneReadyMessage:()=>Yn,SessionBackendErrorMessage:()=>zn,SessionConnectingMessage:()=>Zn,SessionDisconnectedMessage:()=>er,SessionEndedMessage:()=>Gn,SessionErrorMessage:()=>Bn,SessionLiveMessage:()=>Un,SessionReconnectingFinishedMessage:()=>nr,SessionReconnectingMessage:()=>tr,SoftSwitchStartingMessage:()=>rr,SoftSwitchStoppingMessage:()=>ir,SpeechEventMessage:()=>Vn,SpeechRecognitionProvider:()=>ur,SpeechTranscriptionMessage:()=>Mn,Uneeq:()=>so,UneeqMessageType:()=>wn,UserStartedSpeakingMessage:()=>Dn,UserStoppedSpeakingMessage:()=>$n,VadInterruptionAllowedMessage:()=>Rn,VideoLayoutConfiguringMessage:()=>or,WaitingInQueueMessage:()=>Nn,WebRtcStatsMessage:()=>jn});var e,t=__webpack_require__(874),n=__webpack_require__.n(t);!function(e){e.Fatal="fatal",e.Error="error",e.Warn="warn",e.Info="info",e.Debug="debug",e.Trace="trace"}(e||(e={}));class r{static formatLogMessage(e,t){return"UneeQ SDK: "+e+" | "+JSON.stringify(t)}static fatal(e,...t){r.getLogger().fatal(r.formatLogMessage(e,t))}static error(e,...t){r.getLogger().error(r.formatLogMessage(e,t))}static warn(e,...t){r.getLogger().warn(r.formatLogMessage(e,t))}static info(e,...t){r.getLogger().info(r.formatLogMessage(e,t))}static debug(e,...t){r.getLogger().debug(r.formatLogMessage(e,t))}static trace(e,...t){r.getLogger().trace(r.formatLogMessage(e,t))}static getLogger(){return this.instance||(this.instance=n()({level:e.Info})),this.instance}static setLevel(t){Object.values(e).includes(t)?this.instance=n()({level:t}):this.instance=n()({level:e.Info})}static serialiseError(e){return JSON.stringify(e,Object.getOwnPropertyNames(e))}}var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)};function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function s(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function u(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function l(e){return"function"==typeof e}function c(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var d=c((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function h(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var p=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var c=s(o),h=c.next();!h.done;h=c.next())h.value.remove(this)}catch(t){e={error:t}}finally{try{h&&!h.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else o.remove(this);var p=this.initialTeardown;if(l(p))try{p()}catch(e){i=e instanceof d?e.errors:[e]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var g=s(f),b=g.next();!b.done;b=g.next()){var y=b.value;try{m(y)}catch(e){i=null!=i?i:[],e instanceof d?i=u(u([],a(i)),a(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{b&&!b.done&&(r=g.return)&&r.call(g)}finally{if(n)throw n.error}}}if(i)throw new d(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)m(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&h(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&h(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),f=p.EMPTY;function g(e){return e instanceof p||e&&"closed"in e&&l(e.remove)&&l(e.add)&&l(e.unsubscribe)}function m(e){l(e)?e():e.unsubscribe()}var b=null,y=null,v=void 0,w=!1,S=!1,_={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=_.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,u([e,t],a(n))):setTimeout.apply(void 0,u([e,t],a(n)))},clearTimeout:function(e){var t=_.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function T(){}var x=E("C",void 0,void 0);function E(e,t,n){return{kind:e,value:t,error:n}}var C=null;function P(e){if(w){var t=!C;if(t&&(C={errorThrown:!1,error:null}),e(),t){var n=C,r=n.errorThrown,i=n.error;if(C=null,r)throw i}}else e()}var O=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,g(t)&&t.add(n)):n.destination=$,n}return o(t,e),t.create=function(e,t,n){return new M(e,t,n)},t.prototype.next=function(e){this.isStopped?D(function(e){return E("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?D(E("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?D(x,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(p),A=Function.prototype.bind;function k(e,t){return A.call(e,t)}var I=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){R(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){R(e)}else R(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){R(e)}},e}(),M=function(e){function t(t,n,r){var i,o,s=e.call(this)||this;return l(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:s&&S?((o=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&k(t.next,o),error:t.error&&k(t.error,o),complete:t.complete&&k(t.complete,o)}):i=t,s.destination=new I(i),s}return o(t,e),t}(O);function R(e){var t;w?(t=e,w&&C&&(C.errorThrown=!0,C.error=t)):function(e){_.setTimeout((function(){if(!b)throw e;b(e)}))}(e)}function D(e,t){var n=y;n&&_.setTimeout((function(){return n(e,t)}))}var $={closed:!0,next:T,error:function(e){throw e},complete:T},L="function"==typeof Symbol&&Symbol.observable||"@@observable";function F(e){return e}var U=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,i=this,o=(r=e)&&r instanceof O||function(e){return e&&l(e.next)&&l(e.error)&&l(e.complete)}(r)&&g(r)?e:new M(e,t,n);return P((function(){var e=i,t=e.operator,n=e.source;o.add(t?t.call(o,n):n?i._subscribe(o):i._trySubscribe(o))})),o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=N(t))((function(t,r){var i=new M({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[L]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===(n=e).length?F:1===n.length?n[0]:function(e){return n.reduce((function(e,t){return t(e)}),e)})(this);var n},e.prototype.toPromise=function(e){var t=this;return new(e=N(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function N(e){var t;return null!==(t=null!=e?e:v)&&void 0!==t?t:Promise}var j,B,z,V=c((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),G=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return o(t,e),t.prototype.lift=function(e){var t=new H(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new V},t.prototype.next=function(e){var t=this;P((function(){var n,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=s(t.currentObservers),o=i.next();!o.done;o=i.next())o.value.next(e)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}}))},t.prototype.error=function(e){var t=this;P((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}}))},t.prototype.complete=function(){var e=this;P((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,i=n.isStopped,o=n.observers;return r||i?f:(this.currentObservers=null,o.push(e),new p((function(){t.currentObservers=null,h(o,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,i=t.isStopped;n?e.error(r):i&&e.complete()},t.prototype.asObservable=function(){var e=new U;return e.source=this,e},t.create=function(e,t){return new H(e,t)},t}(U),H=function(e){function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return o(t,e),t.prototype.next=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===n||n.call(t,e)},t.prototype.error=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===n||n.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,n;return null!==(n=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==n?n:f},t}(G),W={now:function(){return(W.delegate||Date).now()},delegate:void 0},q=function(e){function t(t,n,r){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===r&&(r=W);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return o(t,e),t.prototype.next=function(t){var n=this,r=n.isStopped,i=n._buffer,o=n._infiniteTimeWindow,s=n._timestampProvider,a=n._windowTime;r||(i.push(t),!o&&i.push(s.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this._infiniteTimeWindow,r=this._buffer.slice(),i=0;i<r.length&&!e.closed;i+=n?1:2)e.next(r[i]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,n=e._timestampProvider,r=e._buffer,i=e._infiniteTimeWindow,o=(i?1:2)*t;if(t<1/0&&o<r.length&&r.splice(0,r.length-o),!i){for(var s=n.now(),a=0,u=1;u<r.length&&r[u]<=s;u+=2)a=u;a&&r.splice(0,a+1)}},t}(G),K=__webpack_require__(963),X={d:(e,t)=>{for(var n in t)X.o(t,n)&&!X.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},J={};X.d(J,{Dz:()=>ft,g$:()=>Te,Lt:()=>we,Q9:()=>_e,qf:()=>Se,hV:()=>Tt,z$:()=>bn,J0:()=>vt,De:()=>ht,$C:()=>pt,al:()=>Me,_W:()=>Re,Gv:()=>Ke,m:()=>Xe,tz:()=>Ie,Nu:()=>yt,zg:()=>Dt,vp:()=>rt,vU:()=>it,wF:()=>Ve,rv:()=>mt,Nh:()=>bt,ss:()=>Mt,qW:()=>Je,QL:()=>qe,cf:()=>Lt,eM:()=>ze,Yd:()=>Q,Tk:()=>At,iM:()=>ue,qy:()=>Y,ce:()=>le,sK:()=>st,Ok:()=>ct,q5:()=>wt,g:()=>mn,xl:()=>Ne,I:()=>je,bx:()=>Be,dD:()=>tt,Ib:()=>ge,Az:()=>me,Iw:()=>be,qY:()=>ve,db:()=>ye,mR:()=>Qe,Tn:()=>ce,rV:()=>Ge,gh:()=>$e,Mi:()=>Le,j:()=>Fe,YB:()=>Ue,Yt:()=>We,i5:()=>He,x_:()=>ut,Am:()=>un,eR:()=>xe,r8:()=>De,u3:()=>$t,vd:()=>Ce,iV:()=>Oe,jZ:()=>Pe,SW:()=>ke,ZH:()=>Ae,Ni:()=>cn,lh:()=>Ee,ZP:()=>nt,bq:()=>de,$f:()=>hn,eu:()=>et,Ax:()=>Ze,Mc:()=>Ye});class Q{static GetStackTrace(){const e=new Error;let t="No Stack Available for this browser";return e.stack&&(t=e.stack.toString().replace(/Error/g,"")),t}static SetLoggerVerbosity(e){null!=this.verboseLogLevel&&(this.verboseLogLevel=e)}static Log(e,t,n){if(n>this.verboseLogLevel)return;const r=`Level: Log\nMsg: ${t}\nCaller: ${e}`;console.log(r)}static Info(e,t,n){if(n>this.verboseLogLevel)return;const r=`Level: Info\nMsg: ${t}`;console.info(r)}static Error(e,t){const n=`Level: Error\nMsg: ${t}\nCaller: ${e}`;console.error(n)}static Warning(e,t){const n=`Level: Warning\nCaller: ${e}\nMsg: ${t}`;console.warn(n)}}Q.verboseLogLevel=5,(z=j||(j={})).LIST_STREAMERS="listStreamers",z.SUBSCRIBE="subscribe",z.UNSUBSCRIBE="unsubscribe",z.ICE_CANDIDATE="iceCandidate",z.OFFER="offer",z.ANSWER="answer",z.DATACHANNELREQUEST="dataChannelRequest",z.SFURECVDATACHANNELREADY="peerDataChannelsReady",z.PONG="pong";class Y{sendFilter(e,t){return t}payload(){return Q.Log(Q.GetStackTrace(),"Sending => \n"+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class Z extends Y{constructor(){super(),this.type=j.LIST_STREAMERS}}class ee extends Y{constructor(e){super(),this.type=j.SUBSCRIBE,this.streamerId=e}}class te extends Y{constructor(){super(),this.type=j.UNSUBSCRIBE}}class ne extends Y{constructor(e){super(),this.type=j.PONG,this.time=e}}class re extends Y{constructor(e,t){super(),this.type=j.OFFER,this.minBitrate=0,this.maxBitrate=0,e&&(this.type=e.type,this.sdp=e.sdp,this.minBitrate=t.minBitrateBps,this.maxBitrate=t.maxBitrateBps)}sendFilter(e,t){if("minBitrate"!=e&&"maxBitrate"!=e||!(t<=0))return t}}class ie extends Y{constructor(e,t){super(),this.type=j.ANSWER,this.minBitrate=0,this.maxBitrate=0,e&&(this.type=e.type,this.sdp=e.sdp,this.minBitrate=t.minBitrateBps,this.maxBitrate=t.maxBitrateBps)}sendFilter(e,t){if("minBitrate"!=e&&"maxBitrate"!=e||!(t<=0))return t}}class oe extends Y{constructor(){super(),this.type=j.DATACHANNELREQUEST}}class se extends Y{constructor(){super(),this.type=j.SFURECVDATACHANNELREADY}}class ae{constructor(e){this.type=j.ICE_CANDIDATE,this.candidate=e}payload(){return Q.Log(Q.GetStackTrace(),"Sending => \n"+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}!function(e){e.CONFIG="config",e.STREAMER_LIST="streamerList",e.STREAMER_ID_CHANGED="streamerIDChanged",e.PLAYER_COUNT="playerCount",e.OFFER="offer",e.ANSWER="answer",e.ICE_CANDIDATE="iceCandidate",e.PEER_DATA_CHANNELS="peerDataChannels",e.PING="ping",e.WARNING="warning"}(B||(B={}));class ue{}class le extends ue{}class ce{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(e,t){this.FromUEMessageHandlers.set(e,t)}handleMessage(e,t){this.FromUEMessageHandlers.has(e)?this.FromUEMessageHandlers.get(e)(t):Q.Error(Q.GetStackTrace(),`Message type of ${e} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(e){e.signallingProtocol.addMessageHandler(B.PING,(t=>{const n=new ne((new Date).getTime()).payload();Q.Log(Q.GetStackTrace(),B.PING+": "+t,6),e.webSocket.send(n)})),e.signallingProtocol.addMessageHandler(B.CONFIG,(t=>{Q.Log(Q.GetStackTrace(),B.CONFIG,6);const n=JSON.parse(t);e.onConfig(n)})),e.signallingProtocol.addMessageHandler(B.STREAMER_LIST,(t=>{Q.Log(Q.GetStackTrace(),B.STREAMER_LIST,6);const n=JSON.parse(t);e.onStreamerList(n)})),e.signallingProtocol.addMessageHandler(B.STREAMER_ID_CHANGED,(t=>{Q.Log(Q.GetStackTrace(),B.STREAMER_ID_CHANGED,6);const n=JSON.parse(t);e.onStreamerIDChanged(n)})),e.signallingProtocol.addMessageHandler(B.PLAYER_COUNT,(t=>{Q.Log(Q.GetStackTrace(),B.PLAYER_COUNT,6);const n=JSON.parse(t);Q.Log(Q.GetStackTrace(),"Player Count: "+n.count,6),e.onPlayerCount(n)})),e.signallingProtocol.addMessageHandler(B.ANSWER,(t=>{Q.Log(Q.GetStackTrace(),B.ANSWER,6);const n=JSON.parse(t);e.onWebRtcAnswer(n)})),e.signallingProtocol.addMessageHandler(B.OFFER,(t=>{Q.Log(Q.GetStackTrace(),B.OFFER,6);const n=JSON.parse(t);e.onWebRtcOffer(n)})),e.signallingProtocol.addMessageHandler(B.ICE_CANDIDATE,(t=>{Q.Log(Q.GetStackTrace(),B.ICE_CANDIDATE,6);const n=JSON.parse(t);e.onIceCandidate(n.candidate)})),e.signallingProtocol.addMessageHandler(B.WARNING,(e=>{Q.Warning(Q.GetStackTrace(),`Warning received: ${e}`)})),e.signallingProtocol.addMessageHandler(B.PEER_DATA_CHANNELS,(t=>{Q.Log(Q.GetStackTrace(),B.PEER_DATA_CHANNELS,6);const n=JSON.parse(t);e.onWebRtcPeerDataChannels(n)}))}}class de{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new ce,ce.setupDefaultHandlers(this)}connect(e){Q.Log(Q.GetStackTrace(),e,6);try{return this.webSocket=new WebSocket(e),this.webSocket.onopen=e=>this.handleOnOpen(e),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=e=>this.handleOnClose(e),this.webSocket.onmessage=e=>this.handleOnMessage(e),this.webSocket.onmessagebinary=e=>this.handleOnMessageBinary(e),!0}catch(e){return Q.Error(e,e),!1}}handleOnMessageBinary(e){e&&e.data&&e.data.text().then((e=>{const t=new MessageEvent("messageFromBinary",{data:e});this.handleOnMessage(t)})).catch((e=>{Q.Error(Q.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${e}`)}))}handleOnMessage(e){if(e.data&&e.data instanceof Blob)return void this.handleOnMessageBinary(e);const t=JSON.parse(e.data);Q.Log(Q.GetStackTrace(),"received => \n"+JSON.stringify(JSON.parse(e.data),void 0,4),6),this.signallingProtocol.handleMessage(t.type,e.data)}handleOnOpen(e){Q.Log(Q.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){Q.Error(Q.GetStackTrace(),"WebSocket error")}handleOnClose(e){Q.Log(Q.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:e}))}requestStreamerList(){const e=new Z;this.webSocket.send(e.payload())}sendSubscribe(e){const t=new ee(e);this.webSocket.send(t.payload())}sendUnsubscribe(){const e=new te;this.webSocket.send(e.payload())}sendWebRtcOffer(e,t){const n=new re(e,t);this.webSocket.send(n.payload())}sendWebRtcAnswer(e,t){const n=new ie(e,t);this.webSocket.send(n.payload())}sendWebRtcDatachannelRequest(){const e=new oe;this.webSocket.send(e.payload())}sendSFURecvDataChannelReady(){const e=new se;this.webSocket.send(e.payload())}sendIceCandidate(e){if(Q.Log(Q.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const t=new ae(e);this.webSocket.send(t.payload())}}close(){var e;null===(e=this.webSocket)||void 0===e||e.close()}onConfig(e){}onStreamerList(e){}onStreamerIDChanged(e){}onIceCandidate(e){}onWebRtcAnswer(e){}onWebRtcOffer(e){}onWebRtcPeerDataChannels(e){}onPlayerCount(e){}}class he{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(Q.Log(Q.GetStackTrace(),"handleOnTrack "+JSON.stringify(e.streams),6),"probator"==e.track.id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&Q.Log(Q.GetStackTrace(),"Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState,6),"audio"!=e.track.kind)return"video"==e.track.kind&&t.srcObject!==e.streams[0]?(t.srcObject=e.streams[0],void Q.Log(Q.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(e.streams[0])}CreateAudioTrack(e){const t=this.videoElementProvider.getVideoElement();t.srcObject!=e&&t.srcObject&&t.srcObject!==e&&(this.audioElement.srcObject=e,Q.Log(Q.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class pe{constructor(e){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=e,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(e){const t=btoa(e.reduce(((e,t)=>e+String.fromCharCode(t)),""));this.imageElement.src="data:image/jpeg;base64,"+t}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(0!==this.freezeFrameWidth&&0!==this.freezeFrameHeight){let e=0,t=0,n=0,r=0;const i=this.rootDiv.clientWidth/this.rootDiv.clientHeight,o=this.freezeFrameWidth/this.freezeFrameHeight;i<o?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/o),n=Math.floor(.5*(this.rootDiv.clientHeight-t)),r=0):(e=Math.floor(this.rootDiv.clientHeight*o),t=this.rootDiv.clientHeight,n=0,r=Math.floor(.5*(this.rootDiv.clientWidth-e))),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=e+"px",this.imageElement.style.height=t+"px",this.imageElement.style.left=r+"px",this.imageElement.style.top=n+"px"}}}class fe{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new pe(e)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(e,t){this.freezeFrame.updateImageElementSource(e),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),t()}}processFreezeFrameMessage(e,t){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(e.slice(1,5).buffer).getInt32(0,!0);const n=e.slice(5);if(this.jpeg){const e=new Uint8Array(this.jpeg.length+n.length);e.set(this.jpeg,0),e.set(n,this.jpeg.length),this.jpeg=e}else this.jpeg=n,this.receiving=!0,Q.Log(Q.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,Q.Log(Q.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(Q.Error(Q.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class ge{constructor(e,t,n,r,i=(()=>{})){this.onChange=i,this.onChangeEmit=()=>{},this.id=e,this.description=n,this.label=t,this.value=r}set label(e){this._label=e,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(e){this._value=e,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class me extends ge{constructor(e,t,n,r,i,o=(()=>{})){super(e,t,n,r,o);const s=new URLSearchParams(window.location.search);if(i&&s.has(this.id)){const e=this.getUrlParamFlag();this.flag=e}else this.flag=r;this.useUrlParams=i}getUrlParamFlag(){const e=new URLSearchParams(window.location.search);return!!e.has(this.id)&&"false"!==e.get(this.id)&&"False"!==e.get(this.id)}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);!0===this.flag?e.set(this.id,"true"):e.set(this.id,"false"),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}}class be extends ge{constructor(e,t,n,r,i,o,s,a=(()=>{})){super(e,t,n,o,a),this._min=r,this._max=i;const u=new URLSearchParams(window.location.search);if(s&&u.has(this.id)){const e=Number.parseFloat(u.get(this.id));this.number=Number.isNaN(e)?o:e}else this.number=o;this.useUrlParams=s}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.number.toString()),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}set number(e){this.value=this.clamp(e)}get number(){return this.value}clamp(e){return null==this._min&&null==this._max?e:null==this._min?Math.min(this._max,e):null==this._max?Math.max(this._min,e):Math.max(Math.min(this._max,e),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(e){this.onChange=e}}class ye extends ge{constructor(e,t,n,r,i,o=(()=>{})){super(e,t,n,r,o);const s=new URLSearchParams(window.location.search);if(i&&s.has(this.id)){const e=this.getUrlParamText();this.text=e}else this.text=r;this.useUrlParams=i}getUrlParamText(){var e;const t=new URLSearchParams(window.location.search);return t.has(this.id)&&null!==(e=t.get(this.id))&&void 0!==e?e:""}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.text),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}get text(){return this.value}set text(e){this.value=e}}class ve extends ge{constructor(e,t,n,r,i,o,s=(()=>{})){super(e,t,n,r,s),this.options=i;const a=new URLSearchParams(window.location.search),u=o&&a.has(this.id)?this.getUrlParamText():r;this.selected=u,this.useUrlParams=o}getUrlParamText(){var e;const t=new URLSearchParams(window.location.search);return t.has(this.id)&&null!==(e=t.get(this.id))&&void 0!==e?e:""}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.selected),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}addOnChangedListener(e){this.onChange=e}get options(){return this._options}set options(e){this._options=e,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(e){let t=this.options.filter((t=>-1!==t.indexOf(e)));t.length?this.value=t[0]:(t=this.options.filter((t=>-1!==t.indexOf(e.split(" ")[0]))),t.length&&(this.value=t[0]))}}class we extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class Se extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class _e extends Event{constructor(){super("afkWarningDeactivate")}}class Te extends Event{constructor(){super("afkTimedOut")}}class xe extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class Ee extends Event{constructor(){super("webRtcSdp")}}class Ce extends Event{constructor(){super("webRtcAutoConnect")}}class Pe extends Event{constructor(){super("webRtcConnecting")}}class Oe extends Event{constructor(){super("webRtcConnected")}}class Ae extends Event{constructor(){super("webRtcFailed")}}class ke extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class Ie extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class Me extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class Re extends Event{constructor(e){super("dataChannelError"),this.data=e}}class De extends Event{constructor(){super("videoInitialized")}}class $e extends Event{constructor(){super("streamLoading")}}class Le extends Event{constructor(){super("streamConnect")}}class Fe extends Event{constructor(){super("streamDisconnect")}}class Ue extends Event{constructor(){super("streamReconnect")}}class Ne extends Event{constructor(e){super("playStreamError"),this.data=e}}class je extends Event{constructor(){super("playStream")}}class Be extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class ze extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class Ve extends Event{constructor(){super("hideFreezeFrame")}}class Ge extends Event{constructor(e){super("statsReceived"),this.data=e}}class He extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class We extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class qe extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class Ke extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class Xe extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class Je extends Event{constructor(e){super("initialSettings"),this.data=e}}class Qe extends Event{constructor(e){super("settingsChanged"),this.data=e}}class Ye extends Event{constructor(){super("xrSessionStarted")}}class Ze extends Event{constructor(){super("xrSessionEnded")}}class et extends Event{constructor(e){super("xrFrame"),this.data=e}}class tt extends Event{constructor(e){super("playerCount"),this.data=e}}class nt extends Event{constructor(){super("webRtcTCPRelayDetected")}}class rt extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class it{}it.AutoConnect="AutoConnect",it.AutoPlayVideo="AutoPlayVideo",it.AFKDetection="TimeoutIfIdle",it.BrowserSendOffer="OfferToReceive",it.HoveringMouseMode="HoveringMouse",it.ForceMonoAudio="ForceMonoAudio",it.ForceTURN="ForceTURN",it.FakeMouseWithTouches="FakeMouseWithTouches",it.IsQualityController="ControlsQuality",it.MatchViewportResolution="MatchViewportRes",it.StartVideoMuted="StartVideoMuted",it.SuppressBrowserKeys="SuppressBrowserKeys",it.UseMic="UseMic",it.KeyboardInput="KeyboardInput",it.MouseInput="MouseInput",it.TouchInput="TouchInput",it.GamepadInput="GamepadInput",it.XRControllerInput="XRControllerInput",it.WaitForStreamer="WaitForStreamer",it.HideUI="HideUI";const ot=e=>Object.getOwnPropertyNames(it).some((t=>it[t]===e));class st{}st.AFKTimeoutSecs="AFKTimeout",st.AFKCountdownSecs="AFKCountdown",st.MinQP="MinQP",st.MaxQP="MaxQP",st.WebRTCFPS="WebRTCFPS",st.WebRTCMinBitrate="WebRTCMinBitrate",st.WebRTCMaxBitrate="WebRTCMaxBitrate",st.MaxReconnectAttempts="MaxReconnectAttempts",st.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const at=e=>Object.getOwnPropertyNames(st).some((t=>st[t]===e));class ut{}ut.SignallingServerUrl="ss";const lt=e=>Object.getOwnPropertyNames(ut).some((t=>ut[t]===e));class ct{}ct.PreferredCodec="PreferredCodec",ct.StreamerId="StreamerId";const dt=e=>Object.getOwnPropertyNames(ct).some((t=>ct[t]===e));class ht{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:t,useUrlParams:n}=e;this._useUrlParams=!!n,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(e,t){this.textParameters.set(ut.SignallingServerUrl,new ye(ut.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&t.hasOwnProperty(ut.SignallingServerUrl)?t[ut.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(ct.StreamerId,new ve(ct.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&t.hasOwnProperty(ct.StreamerId)?t[ct.StreamerId]:"",[],e)),this.optionParameters.set(ct.PreferredCodec,new ve(ct.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",t&&t.hasOwnProperty(ct.PreferredCodec)?[t[ct.PreferredCodec]]:function(){const e=[];if(!RTCRtpReceiver.getCapabilities)return e.push("Only available on Chrome"),e;const t=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((n=>{const r=n.mimeType.split("/")[1]+" "+(n.sdpFmtpLine||"");null!==t.exec(r)&&e.push(r)})),e}(),e)),this.flags.set(it.AutoConnect,new me(it.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!t||!t.hasOwnProperty(it.AutoConnect))&&t[it.AutoConnect],e)),this.flags.set(it.AutoPlayVideo,new me(it.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!t||!t.hasOwnProperty(it.AutoPlayVideo)||t[it.AutoPlayVideo],e)),this.flags.set(it.BrowserSendOffer,new me(it.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!t||!t.hasOwnProperty(it.BrowserSendOffer))&&t[it.BrowserSendOffer],e)),this.flags.set(it.UseMic,new me(it.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!t.hasOwnProperty(it.UseMic))&&t[it.UseMic],e)),this.flags.set(it.StartVideoMuted,new me(it.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!t.hasOwnProperty(it.StartVideoMuted))&&t[it.StartVideoMuted],e)),this.flags.set(it.SuppressBrowserKeys,new me(it.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!t||!t.hasOwnProperty(it.SuppressBrowserKeys)||t[it.SuppressBrowserKeys],e)),this.flags.set(it.IsQualityController,new me(it.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!t.hasOwnProperty(it.IsQualityController)||t[it.IsQualityController],e)),this.flags.set(it.ForceMonoAudio,new me(it.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!t.hasOwnProperty(it.ForceMonoAudio))&&t[it.ForceMonoAudio],e)),this.flags.set(it.ForceTURN,new me(it.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!t.hasOwnProperty(it.ForceTURN))&&t[it.ForceTURN],e)),this.flags.set(it.AFKDetection,new me(it.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!t.hasOwnProperty(it.AFKDetection))&&t[it.AFKDetection],e)),this.flags.set(it.MatchViewportResolution,new me(it.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!t||!t.hasOwnProperty(it.MatchViewportResolution))&&t[it.MatchViewportResolution],e)),this.flags.set(it.HoveringMouseMode,new me(it.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!t||!t.hasOwnProperty(it.HoveringMouseMode))&&t[it.HoveringMouseMode],e,((e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`}))),this.flags.set(it.FakeMouseWithTouches,new me(it.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!t||!t.hasOwnProperty(it.FakeMouseWithTouches))&&t[it.FakeMouseWithTouches],e)),this.flags.set(it.KeyboardInput,new me(it.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!t.hasOwnProperty(it.KeyboardInput)||t[it.KeyboardInput],e)),this.flags.set(it.MouseInput,new me(it.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!t.hasOwnProperty(it.MouseInput)||t[it.MouseInput],e)),this.flags.set(it.TouchInput,new me(it.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!t.hasOwnProperty(it.TouchInput)||t[it.TouchInput],e)),this.flags.set(it.GamepadInput,new me(it.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!t.hasOwnProperty(it.GamepadInput)||t[it.GamepadInput],e)),this.flags.set(it.XRControllerInput,new me(it.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!t.hasOwnProperty(it.XRControllerInput)||t[it.XRControllerInput],e)),this.flags.set(it.WaitForStreamer,new me(it.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!t.hasOwnProperty(it.WaitForStreamer)||t[it.WaitForStreamer],e)),this.flags.set(it.HideUI,new me(it.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!t.hasOwnProperty(it.HideUI))&&t[it.HideUI],e)),this.numericParameters.set(st.AFKTimeoutSecs,new be(st.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,t&&t.hasOwnProperty(st.AFKTimeoutSecs)?t[st.AFKTimeoutSecs]:120,e)),this.numericParameters.set(st.AFKCountdownSecs,new be(st.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,e)),this.numericParameters.set(st.MaxReconnectAttempts,new be(st.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&t.hasOwnProperty(st.MaxReconnectAttempts)?t[st.MaxReconnectAttempts]:3,e)),this.numericParameters.set(st.MinQP,new be(st.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&t.hasOwnProperty(st.MinQP)?t[st.MinQP]:0,e)),this.numericParameters.set(st.MaxQP,new be(st.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&t.hasOwnProperty(st.MaxQP)?t[st.MaxQP]:51,e)),this.numericParameters.set(st.WebRTCFPS,new be(st.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&t.hasOwnProperty(st.WebRTCFPS)?t[st.WebRTCFPS]:60,e)),this.numericParameters.set(st.WebRTCMinBitrate,new be(st.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&t.hasOwnProperty(st.WebRTCMinBitrate)?t[st.WebRTCMinBitrate]:0,e)),this.numericParameters.set(st.WebRTCMaxBitrate,new be(st.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&t.hasOwnProperty(st.WebRTCMaxBitrate)?t[st.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(st.StreamerAutoJoinInterval,new be(st.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&t.hasOwnProperty(st.StreamerAutoJoinInterval)?t[st.StreamerAutoJoinInterval]:3e3,e))}_addOnNumericSettingChangedListener(e,t){this.numericParameters.has(e)&&this.numericParameters.get(e).addOnChangedListener(t)}_addOnOptionSettingChangedListener(e,t){this.optionParameters.has(e)&&this.optionParameters.get(e).addOnChangedListener(t)}getNumericSettingValue(e){if(this.numericParameters.has(e))return this.numericParameters.get(e).number;throw new Error(`There is no numeric setting with the id of ${e}`)}getTextSettingValue(e){if(this.textParameters.has(e))return this.textParameters.get(e).value;throw new Error(`There is no numeric setting with the id of ${e}`)}setNumericSetting(e,t){if(!this.numericParameters.has(e))throw new Error(`There is no numeric setting with the id of ${e}`);this.numericParameters.get(e).number=t}_addOnSettingChangedListener(e,t){this.flags.has(e)&&(this.flags.get(e).onChange=t)}_addOnTextSettingChangedListener(e,t){this.textParameters.has(e)&&(this.textParameters.get(e).onChange=t)}getSettingOption(e){return this.optionParameters.get(e)}isFlagEnabled(e){return this.flags.get(e).flag}setFlagEnabled(e,t){this.flags.has(e)?this.flags.get(e).flag=t:Q.Warning(Q.GetStackTrace(),`Cannot toggle flag called ${e} - it does not exist in the Config.flags map.`)}setTextSetting(e,t){this.textParameters.has(e)?this.textParameters.get(e).text=t:Q.Warning(Q.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(e,t){this.optionParameters.has(e)?this.optionParameters.get(e).options=t:Q.Warning(Q.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(this.optionParameters.has(e)){const n=this.optionParameters.get(e),r=n.options;r.includes(t)||(r.push(t),n.options=r),n.selected=t}else Q.Warning(Q.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(e,t){this.flags.has(e)?this.flags.get(e).label=t:Q.Warning(Q.GetStackTrace(),`Cannot set label for flag called ${e} - it does not exist in the Config.flags map.`)}setSettings(e){for(const t of Object.keys(e))ot(t)?this.setFlagEnabled(t,e[t]):at(t)?this.setNumericSetting(t,e[t]):lt(t)?this.setTextSetting(t,e[t]):dt(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){const e={};for(const[t,n]of this.flags.entries())e[t]=n.flag;for(const[t,n]of this.numericParameters.entries())e[t]=n.number;for(const[t,n]of this.textParameters.entries())e[t]=n.text;for(const[t,n]of this.optionParameters.entries())e[t]=n.selected;return e}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(e){for(const t of this.flags.keys()){const n=this.flags.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"flag",value:t,target:n})))}for(const t of this.numericParameters.keys()){const n=this.numericParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"number",value:t,target:n})))}for(const t of this.textParameters.keys()){const n=this.textParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"text",value:t,target:n})))}for(const t of this.optionParameters.keys()){const n=this.optionParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"option",value:t,target:n})))}}}var pt;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(pt||(pt={}));class ft{constructor(e,t,n){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=e,this.pixelStreaming=t,this.onDismissAfk=n,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new _e))}startAfkWarningTimer(){this.config.getNumericSettingValue(st.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(it.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(it.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(st.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new we({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(st.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new Se({countDown:this.countDown})),this.config.isFlagEnabled(it.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,0==this.countDown?(this.pixelStreaming.dispatchEvent(new Te),this.onAFKTimedOutCallback(),Q.Log(Q.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new Se({countDown:this.countDown}))}),1e3)}}class gt{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,n){this.peerConnection=e,this.label=t,this.datachannelOptions=n,null==n&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=e=>this.handleOnOpen(e),this.dataChannel.onclose=e=>this.handleOnClose(e),this.dataChannel.onmessage=e=>this.handleOnMessage(e),this.dataChannel.onerror=e=>this.handleOnError(e)}handleOnOpen(e){var t;Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) message: ${e}`,8)}handleOnError(e){var t;Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) error: ${e}`,7),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class mt{}class bt{}class yt{}class vt{}class wt{}class St{}class _t{}class Tt{constructor(){this.inboundVideoStats=new bt,this.inboundAudioStats=new mt,this.DataChannelStats=new yt,this.outBoundVideoStats=new wt,this.sessionStats=new St,this.streamStats=new _t,this.codecs=new Map}processStats(e){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,e.forEach((e=>{switch(e.type){case"candidate-pair":this.handleCandidatePair(e);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(e);break;case"data-channel":this.handleDataChannel(e);break;case"inbound-rtp":this.handleInBoundRTP(e);break;case"local-candidate":this.handleLocalCandidate(e);break;case"remote-candidate":this.handleRemoteCandidate(e);break;case"remote-outbound-rtp":this.handleRemoteOutBound(e);break;case"track":this.handleTrack(e);break;case"transport":this.handleTransport(e);break;case"stream":this.handleStream(e);break;default:Q.Error(Q.GetStackTrace(),"unhandled Stat Type"),Q.Log(Q.GetStackTrace(),e)}}))}handleStream(e){this.streamStats=e}handleCandidatePair(e){this.candidatePairs.push(e)}handleDataChannel(e){this.DataChannelStats.bytesReceived=e.bytesReceived,this.DataChannelStats.bytesSent=e.bytesSent,this.DataChannelStats.dataChannelIdentifier=e.dataChannelIdentifier,this.DataChannelStats.id=e.id,this.DataChannelStats.label=e.label,this.DataChannelStats.messagesReceived=e.messagesReceived,this.DataChannelStats.messagesSent=e.messagesSent,this.DataChannelStats.protocol=e.protocol,this.DataChannelStats.state=e.state,this.DataChannelStats.timestamp=e.timestamp}handleLocalCandidate(e){const t=new vt;t.label="local-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.candidateType=e.candidateType,t.id=e.id,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.localCandidates.push(t)}handleRemoteCandidate(e){const t=new vt;t.label="remote-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.id=e.id,t.candidateType=e.candidateType,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.remoteCandidates.push(t)}handleInBoundRTP(e){switch(e.kind){case"video":this.inboundVideoStats=e,null!=this.lastVideoStats&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=e,null!=this.lastAudioStats&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:Q.Log(Q.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(e){"video"===e.kind&&(this.outBoundVideoStats.bytesSent=e.bytesSent,this.outBoundVideoStats.id=e.id,this.outBoundVideoStats.localId=e.localId,this.outBoundVideoStats.packetsSent=e.packetsSent,this.outBoundVideoStats.remoteTimestamp=e.remoteTimestamp,this.outBoundVideoStats.timestamp=e.timestamp)}handleTrack(e){"track"!==e.type||"video_label"!==e.trackIdentifier&&"video"!==e.kind||(this.inboundVideoStats.framesDropped=e.framesDropped,this.inboundVideoStats.framesReceived=e.framesReceived,this.inboundVideoStats.frameHeight=e.frameHeight,this.inboundVideoStats.frameWidth=e.frameWidth)}handleTransport(e){this.transportStats=e}handleCodec(e){const t=e.id,n=`${e.mimeType.replace("video/","").replace("audio/","")}${e.sdpFmtpLine?` ${e.sdpFmtpLine}`:""}`;this.codecs.set(t,n)}handleSessionStatistics(e,t,n){const r=Date.now()-e;this.sessionStats.runTime=new Date(r).toISOString().substr(11,8).toString();const i=null===t?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=i,this.sessionStats.videoEncoderAvgQP=n}isNumber(e){return"number"==typeof e&&isFinite(e)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((e=>e.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((e=>e.selected),null)}}const xt=(Et={parseRtpParameters:()=>K.parseRtpParameters,splitSections:()=>K.splitSections},Ct={},X.d(Ct,Et),Ct);var Et,Ct;class Pt{static isVideoTransciever(e){return this.canTransceiverReceiveVideo(e)||this.canTransceiverSendVideo(e)}static canTransceiverReceiveVideo(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind}static canTransceiverSendVideo(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"video"===e.sender.track.kind}static isAudioTransciever(e){return this.canTransceiverReceiveAudio(e)||this.canTransceiverSendAudio(e)}static canTransceiverReceiveAudio(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind}static canTransceiverSendAudio(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"audio"===e.sender.track.kind}}var Ot,At,kt=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class It{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n)}createPeerConnection(e,t){this.config.isFlagEnabled(it.ForceTURN)&&(e.iceTransportPolicy="relay",Q.Log(Q.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(e),this.peerConnection.onsignalingstatechange=e=>this.handleSignalStateChange(e),this.peerConnection.oniceconnectionstatechange=e=>this.handleIceConnectionStateChange(e),this.peerConnection.onicegatheringstatechange=e=>this.handleIceGatheringStateChange(e),this.peerConnection.ontrack=e=>this.handleOnTrack(e),this.peerConnection.onicecandidate=e=>this.handleIceCandidate(e),this.peerConnection.ondatachannel=e=>this.handleDataChannel(e),this.aggregatedStats=new Tt,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return kt(this,void 0,void 0,(function*(){Q.Log(Q.GetStackTrace(),"Create Offer",6);const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,r="https:"===location.protocol;let i=t.isFlagEnabled(it.UseMic);!i||n||r||(i=!1,Q.Error(Q.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),Q.Error(Q.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(i).finally((()=>{var t;null===(t=this.peerConnection)||void 0===t||t.createOffer(e).then((e=>{var t;this.showTextOverlayConnecting(),e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t||t.setLocalDescription(e),this.onSendWebRTCOffer(e)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(e,t){var n;return kt(this,void 0,void 0,(function*(){Q.Log(Q.GetStackTrace(),"Receive Offer",6),null===(n=this.peerConnection)||void 0===n||n.setRemoteDescription(e).then((()=>{const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,r="https:"===location.protocol;let i=t.isFlagEnabled(it.UseMic);!i||n||r||(i=!1,Q.Error(Q.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),Q.Error(Q.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(ct.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(i).finally((()=>{var e;null===(e=this.peerConnection)||void 0===e||e.createAnswer().then((e=>{var t;return e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t?void 0:t.setLocalDescription(e)})).then((()=>{var e;this.onSendWebRTCAnswer(null===(e=this.peerConnection)||void 0===e?void 0:e.currentLocalDescription)})).catch((()=>{Q.Error(Q.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(ct.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){var e;null===(e=this.peerConnection)||void 0===e||e.getStats(null).then((e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(ct.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(e,t){let n=e.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,"$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r\n"),r="maxaveragebitrate=510000;";return t&&(r+="sprop-maxcapturerate=48000;"),r+=this.config.isFlagEnabled(it.ForceMonoAudio)?"stereo=0;":"stereo=1;",r+="useinbandfec=1",n=n.replace("useinbandfec=1",r),n}handleOnIce(e){var t;Q.Log(Q.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(it.ForceTURN)&&e.candidate.indexOf("relay")<0?Q.Info(Q.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${e.type} | Protocol= ${e.protocol} | Address=${e.address} | Port=${e.port} |`,6):null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}handleSignalStateChange(e){Q.Log(Q.GetStackTrace(),"signaling state change: "+e,6)}handleIceConnectionStateChange(e){Q.Log(Q.GetStackTrace(),"ice connection state change: "+e,6),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){Q.Log(Q.GetStackTrace(),"ice gathering state change: "+JSON.stringify(e),6)}handleOnTrack(e){this.onTrack(e)}handleIceCandidate(e){this.onPeerIceCandidate(e)}handleDataChannel(e){this.onDataChannel(e)}onTrack(e){}onIceConnectionStateChange(e){}onPeerIceCandidate(e){}onDataChannel(e){}fuzzyIntersectUEAndBrowserCodecs(e){const t=new Array,n=this.parseAvailableCodecs(e),r=this.config.getSettingOption(ct.PreferredCodec).options;for(const e of n)if(r.includes(e))t.push(e);else{const n=e.split(" ")[0];for(const e of r)if(e.includes(n)){t.push(e);break}}return t}setupTransceiversAsync(e){var t,n,r,i,o,s,a,u,l,c,d,h;return kt(this,void 0,void 0,(function*(){let p=!1;for(const e of null!==(n=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==n?n:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind){p=!0;break}if(p||null===(r=this.peerConnection)||void 0===r||r.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&""!=this.preferredCodec)for(const e of null!==(o=null===(i=this.peerConnection)||void 0===i?void 0:i.getTransceivers())&&void 0!==o?o:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind&&e.setCodecPreferences){const t=this.preferredCodec.split(" "),n={mimeType:"video/"+t[0],clockRate:9e4,sdpFmtpLine:t[1]?t[1]:""},r=[n];RTCRtpReceiver.getCapabilities("video").codecs.forEach((e=>{(e.mimeType!=n.mimeType||(null==e?void 0:e.sdpFmtpLine)!=(null==n?void 0:n.sdpFmtpLine))&&r.push(e)}));for(const e of r)void 0!==(null==e?void 0:e.sdpFmtpLine)&&""!==e.sdpFmtpLine||delete e.sdpFmtpLine;e.setCodecPreferences(r)}let f=!1;for(const e of null!==(a=null===(s=this.peerConnection)||void 0===s?void 0:s.getTransceivers())&&void 0!==a?a:[])if(e&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind){f=!0;break}if(e){const e={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},t=yield navigator.mediaDevices.getUserMedia(e);if(t)if(f){for(const e of null!==(c=null===(l=this.peerConnection)||void 0===l?void 0:l.getTransceivers())&&void 0!==c?c:[])if(Pt.canTransceiverReceiveAudio(e))for(const n of t.getTracks())n.kind&&"audio"==n.kind&&(e.sender.replaceTrack(n),e.direction="sendrecv")}else for(const e of t.getTracks())e.kind&&"audio"==e.kind&&(null===(d=this.peerConnection)||void 0===d||d.addTransceiver(e,{direction:"sendrecv"}));else f||null===(h=this.peerConnection)||void 0===h||h.addTransceiver("audio",{direction:"recvonly"})}else f||null===(u=this.peerConnection)||void 0===u||u.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(e){}onSendWebRTCOffer(e){}onSendWebRTCAnswer(e){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(e){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const t=[],n=(0,xt.splitSections)(e.sdp);return n.shift(),n.forEach((e=>{const{codecs:n}=(0,xt.parseRtpParameters)(e),r=/(VP\d|H26\d|AV1).*/;n.forEach((e=>{const n=e.name+" "+Object.keys(e.parameters||{}).map((t=>t+"="+e.parameters[t])).join(";");if(null!==r.exec(n)){"VP9"==e.name&&(e.parameters={"profile-id":"0"});const n=e.name+" "+Object.keys(e.parameters||{}).map((t=>t+"="+e.parameters[t])).join(";");t.push(n)}}))})),t}}class Mt{constructor(){this.PixelStreamingSettings=new Rt,this.EncoderSettings=new Dt,this.WebRTCSettings=new $t}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Rt{}class Dt{}class $t{}class Lt{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(e){0==this.frameDisplayDeltaTimeMs&&(this.frameDisplayDeltaTimeMs=Math.round(e))}processFields(){null!=this.EncodeMs||null==this.PreEncodeTimeMs&&null==this.PostEncodeTimeMs||(Q.Log(Q.GetStackTrace(),`Setting Encode Ms \n ${this.PostEncodeTimeMs} \n ${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),null!=this.CaptureToSendMs||null==this.PreCaptureTimeMs&&null==this.PostCaptureTimeMs||(Q.Log(Q.GetStackTrace(),`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class Ft{static setExtensionFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.size=0,t.data=[],t.timestampStart=(new Date).getTime(),Q.Log(Q.GetStackTrace(),"Received first chunk of file",6));const n=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),n,6),t.extension=n}static setMimeTypeFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.size=0,t.data=[],t.timestampStart=(new Date).getTime(),Q.Log(Q.GetStackTrace(),"Received first chunk of file",6));const n=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),n,6),t.mimetype=n}static setContentsFromBytes(e,t){if(!t.receiving)return;t.size=Math.ceil(new DataView(e.slice(1,5).buffer).getInt32(0,!0)/16379);const n=e.slice(5);if(t.data.push(n),Q.Log(Q.GetStackTrace(),`Received file chunk: ${t.data.length}/${t.size}`,6),t.data.length===t.size){t.receiving=!1,t.valid=!0,Q.Log(Q.GetStackTrace(),"Received complete file",6);const e=(new Date).getTime()-t.timestampStart,n=Math.round(16*t.size*1024/e);Q.Log(Q.GetStackTrace(),`Average transfer bitrate: ${n}kb/s over ${e/1e3} seconds`,6);const r=new Blob(t.data,{type:t.mimetype}),i=document.createElement("a");i.setAttribute("href",URL.createObjectURL(r)),i.setAttribute("download",`transfer.${t.extension}`),document.body.append(i),i.remove()}else t.data.length>t.size&&(t.receiving=!1,Q.Error(Q.GetStackTrace(),`Received bigger file than advertised: ${t.data.length}/${t.size}`))}}class Ut{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.size=0,this.data=[],this.valid=!1}}class Nt{}Nt.mainButton=0,Nt.auxiliaryButton=1,Nt.secondaryButton=2,Nt.fourthButton=3,Nt.fifthButton=4;class jt{}jt.primaryButton=1,jt.secondaryButton=2,jt.auxiliaryButton=4,jt.fourthButton=8,jt.fifthButton=16;class Bt{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(e){this.unregisterCallbacks.push(e)}unregisterAll(){for(const e of this.unregisterCallbacks)e();this.unregisterCallbacks=[]}}class zt{constructor(e,t,n){this.touchEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n;const r=e=>this.onTouchStart(e),i=e=>this.onTouchEnd(e),o=e=>this.onTouchMove(e);document.addEventListener("touchstart",r,{passive:!1}),document.addEventListener("touchend",i,{passive:!1}),document.addEventListener("touchmove",o,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",r))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",i))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",o)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(e){this.videoElementParentClientRect=e}onTouchStart(e){if(this.videoElementProvider.isVideoReady()&&e.target===this.videoElementProvider.getVideoElement()){if(null==this.fakeTouchFinger){const t=e.changedTouches[0];this.fakeTouchFinger=new Vt(t.identifier,t.clientX-this.videoElementParentClientRect.left,t.clientY-this.videoElementParentClientRect.top);const n=this.videoElementProvider.getVideoParentElement(),r=new MouseEvent("mouseenter",t);n.dispatchEvent(r);const i=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([Nt.mainButton,i.x,i.y])}e.preventDefault()}}onTouchEnd(e){if(!this.videoElementProvider.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.videoElementProvider.getVideoParentElement(),n=this.toStreamerMessagesProvider.toStreamerHandlers;for(let r=0;r<e.changedTouches.length;r++){const i=e.changedTouches[r];if(i.identifier===this.fakeTouchFinger.id){const e=i.clientX-this.videoElementParentClientRect.left,r=i.clientY-this.videoElementParentClientRect.top,o=this.coordinateConverter.normalizeAndQuantizeUnsigned(e,r);n.get("MouseUp")([Nt.mainButton,o.x,o.y]);const s=new MouseEvent("mouseleave",i);t.dispatchEvent(s),this.fakeTouchFinger=null;break}}e.preventDefault()}onTouchMove(e){if(!this.videoElementProvider.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.toStreamerMessagesProvider.toStreamerHandlers;for(let n=0;n<e.touches.length;n++){const r=e.touches[n];if(r.identifier===this.fakeTouchFinger.id){const e=r.clientX-this.videoElementParentClientRect.left,n=r.clientY-this.videoElementParentClientRect.top,i=this.coordinateConverter.normalizeAndQuantizeUnsigned(e,n),o=this.coordinateConverter.normalizeAndQuantizeSigned(e-this.fakeTouchFinger.x,n-this.fakeTouchFinger.y);t.get("MouseMove")([i.x,i.y,o.x,o.y]),this.fakeTouchFinger.x=e,this.fakeTouchFinger.y=n;break}}e.preventDefault()}}class Vt{constructor(e,t,n){this.id=e,this.x=t,this.y=n}}class Gt{}Gt.backSpace=8,Gt.shift=16,Gt.control=17,Gt.alt=18,Gt.rightShift=253,Gt.rightControl=254,Gt.rightAlt=255;class Ht{constructor(e,t,n){this.keyboardEventListenerTracker=new Bt,this.CodeToKeyCode={Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93},this.toStreamerMessagesProvider=e,this.config=t,this.activeKeysProvider=n}registerKeyBoardEvents(){const e=e=>this.handleOnCompositionEnd(e),t=e=>this.handleOnKeyDown(e),n=e=>this.handleOnKeyUp(e),r=e=>this.handleOnKeyPress(e);document.addEventListener("compositionend",e),document.addEventListener("keydown",t),document.addEventListener("keyup",n),document.addEventListener("keypress",r),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",e))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",t))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",n))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",r)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(e){const t=this.getKeycode(e);t&&229!==t&&(Q.Log(Q.GetStackTrace(),`key down ${t}, repeat = ${e.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(e),e.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(t),t===Gt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Gt.backSpace})),this.config.isFlagEnabled(it.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(t)&&e.preventDefault())}handleOnKeyUp(e){const t=this.getKeycode(e);t&&(Q.Log(Q.GetStackTrace(),`key up ${t}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([t]),this.config.isFlagEnabled(it.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(t)&&e.preventDefault())}handleOnKeyPress(e){if(!("charCode"in e))return void Q.Warning(Q.GetStackTrace(),"KeyboardEvent.charCode is deprecated in this browser, cannot send key press.");const t=e.charCode;Q.Log(Q.GetStackTrace(),`key press ${t}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([t])}handleOnCompositionEnd(e){e.data&&e.data.length&&e.data.split("").forEach((e=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:e.toUpperCase().charCodeAt(0),charCode:e.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:e.toUpperCase().charCodeAt(0),charCode:e.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:e.toUpperCase().charCodeAt(0),charCode:e.charCodeAt(0)}))}))}getKeycode(e){if(!("keyCode"in e)){const t=e;return t.code in this.CodeToKeyCode?this.CodeToKeyCode[t.code]:(Q.Warning(Q.GetStackTrace(),`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===Gt.shift&&"ShiftRight"===e.code?Gt.rightShift:e.keyCode===Gt.control&&"ControlRight"===e.code?Gt.rightControl:e.keyCode===Gt.alt&&"AltRight"===e.code?Gt.rightAlt:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||9===e}}class Wt{constructor(e,t,n){this.x=0,this.y=0,this.updateMouseMovePositionEvent=e=>{this.updateMouseMovePosition(e)},this.mouseEventListenerTracker=new Bt,this.videoElementProvider=e,this.mouseController=t,this.activeKeysProvider=n;const r=this.videoElementProvider.getVideoParentElement();this.x=r.getBoundingClientRect().width/2,this.y=r.getBoundingClientRect().height/2,this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y)}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}lockStateChange(){const e=this.videoElementProvider.getVideoParentElement(),t=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===e||document.mozPointerLockElement===e)Q.Log(Q.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{Q.Log(Q.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let e=this.activeKeysProvider.getActiveKeys();const n=new Set(e),r=[];n.forEach((e=>{r[e]})),r.forEach((e=>{t.get("KeyUp")([e])})),e=[]}}updateMouseMovePosition(e){if(!this.videoElementProvider.isVideoReady())return;const t=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,n=this.videoElementProvider.getVideoParentElement().clientWidth,r=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=e.movementX,this.y+=e.movementY,this.x>n&&(this.x-=n),this.y>r&&(this.y-=r),this.x<0&&(this.x=n+this.x),this.y<0&&(this.y=r-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const i=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(e.movementX,e.movementY);t.get("MouseMove")([this.coord.x,this.coord.y,i.x,i.y])}handleMouseDown(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([e.button,this.coord.x,this.coord.y])}handleMouseUp(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([e.button,this.coord.x,this.coord.y])}handleMouseWheel(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([e.button,this.coord.x,this.coord.y])}handlePressMouseButtons(e){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(e.buttons,this.x,this.y)}handleReleaseMouseButtons(e){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(e.buttons,this.x,this.y)}}class qt{constructor(e){this.mouseController=e}unregisterMouseEvents(){}updateMouseMovePosition(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),"MouseMove",6);const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY),n=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(e.movementX,e.movementY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseMove")([t.x,t.y,n.x,n.y]),e.preventDefault()}handleMouseDown(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),"onMouse Down",6);const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([e.button,t.x,t.y]),e.preventDefault()}handleMouseUp(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),"onMouse Up",6);const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y]),e.preventDefault()}handleContextMenu(e){this.mouseController.videoElementProvider.isVideoReady()&&e.preventDefault()}handleMouseWheel(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,t.x,t.y]),e.preventDefault()}handleMouseDouble(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([e.button,t.x,t.y])}handlePressMouseButtons(e){this.mouseController.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"onMouse press",6),this.mouseController.pressMouseButtons(e.buttons,e.offsetX,e.offsetY))}handleReleaseMouseButtons(e){this.mouseController.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"onMouse release",6),this.mouseController.releaseMouseButtons(e.buttons,e.offsetX,e.offsetY))}}class Kt{constructor(e,t,n,r){this.mouseEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.coordinateConverter=n,this.videoElementProvider=t,this.activeKeysProvider=r,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(e){const t=this.videoElementProvider.getVideoParentElement(),n=new Wt(this.videoElementProvider,e,this.activeKeysProvider);if(t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,t.requestPointerLock){const e=()=>{t.requestPointerLock()};t.addEventListener("click",e),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("click",e)))}const r=()=>n.lockStateChange();document.addEventListener("pointerlockchange",r,!1),document.addEventListener("mozpointerlockchange",r,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",r,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",r,!1)));const i=e=>n.handleMouseDown(e),o=e=>n.handleMouseUp(e),s=e=>n.handleMouseWheel(e),a=e=>n.handleMouseDouble(e);t.addEventListener("mousedown",i),t.addEventListener("mouseup",o),t.addEventListener("wheel",s),t.addEventListener("dblclick",a),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mousedown",i))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mouseup",o))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("wheel",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("dblclick",a))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==t&&document.mozPointerLockElement!==t||document.exitPointerLock()}))}registerHoveringMouseEvents(e){const t=this.videoElementProvider.getVideoParentElement(),n=new qt(e),r=e=>n.updateMouseMovePosition(e),i=e=>n.handleMouseDown(e),o=e=>n.handleMouseUp(e),s=e=>n.handleContextMenu(e),a=e=>n.handleMouseWheel(e),u=e=>n.handleMouseDouble(e);t.addEventListener("mousemove",r),t.addEventListener("mousedown",i),t.addEventListener("mouseup",o),t.addEventListener("contextmenu",s),t.addEventListener("wheel",a),t.addEventListener("dblclick",u),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mousemove",r))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mousedown",i))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mouseup",o))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("contextmenu",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("wheel",a))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("dblclick",u))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const e=this.videoElementProvider.getVideoParentElement(),t=e=>{this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(e.buttons,e.x,e.y))},n=e=>{this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(e.buttons,e.x,e.y))};e.addEventListener("mouseenter",t),e.addEventListener("mouseleave",n),this.mouseEventListenerTracker.addUnregisterCallback((()=>e.removeEventListener("mouseenter",t))),this.mouseEventListenerTracker.addUnregisterCallback((()=>e.removeEventListener("mouseleave",n)))}releaseMouseButtons(e,t,n){const r=this.coordinateConverter.normalizeAndQuantizeUnsigned(t,n);e&jt.primaryButton&&this.sendMouseUp(Nt.mainButton,r.x,r.y),e&jt.secondaryButton&&this.sendMouseUp(Nt.secondaryButton,r.x,r.y),e&jt.auxiliaryButton&&this.sendMouseUp(Nt.auxiliaryButton,r.x,r.y),e&jt.fourthButton&&this.sendMouseUp(Nt.fourthButton,r.x,r.y),e&jt.fifthButton&&this.sendMouseUp(Nt.fifthButton,r.x,r.y)}pressMouseButtons(e,t,n){if(!this.videoElementProvider.isVideoReady())return;const r=this.coordinateConverter.normalizeAndQuantizeUnsigned(t,n);e&jt.primaryButton&&this.sendMouseDown(Nt.mainButton,r.x,r.y),e&jt.secondaryButton&&this.sendMouseDown(Nt.secondaryButton,r.x,r.y),e&jt.auxiliaryButton&&this.sendMouseDown(Nt.auxiliaryButton,r.x,r.y),e&jt.fourthButton&&this.sendMouseDown(Nt.fourthButton,r.x,r.y),e&jt.fifthButton&&this.sendMouseDown(Nt.fifthButton,r.x,r.y)}sendMouseEnter(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseEnter")()}sendMouseLeave(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseLeave")()}sendMouseDown(e,t,n){this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),`mouse button ${e} down at (${t}, ${n})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([e,t,n]))}sendMouseUp(e,t,n){if(!this.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),`mouse button ${e} up at (${t}, ${n})`,6);const r=this.coordinateConverter.normalizeAndQuantizeUnsigned(t,n);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([e,r.x,r.y])}}class Xt{constructor(e,t,n){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n,this.videoElementParent=t.getVideoElement();const r=e=>this.onTouchStart(e),i=e=>this.onTouchEnd(e),o=e=>this.onTouchMove(e);this.videoElementParent.addEventListener("touchstart",r),this.videoElementParent.addEventListener("touchend",i),this.videoElementParent.addEventListener("touchmove",o),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",r))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",i))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",o))),Q.Log(Q.GetStackTrace(),"Touch Events Registered",6);const s=e=>{e.preventDefault()};document.addEventListener("touchmove",s),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",s)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}rememberTouch(e){const t=this.fingers.pop();void 0===t&&Q.Log(Q.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(e.identifier,t)}forgetTouch(e){this.fingers.push(this.fingerIds.get(e.identifier)),this.fingers.sort((function(e,t){return t-e})),this.fingerIds.delete(e.identifier)}onTouchStart(e){if(this.videoElementProvider.isVideoReady()){for(let t=0;t<e.changedTouches.length;t++)this.rememberTouch(e.changedTouches[t]);Q.Log(Q.GetStackTrace(),"touch start",6),this.emitTouchData("TouchStart",e.changedTouches),e.preventDefault()}}onTouchEnd(e){if(this.videoElementProvider.isVideoReady()){Q.Log(Q.GetStackTrace(),"touch end",6),this.emitTouchData("TouchEnd",e.changedTouches);for(let t=0;t<e.changedTouches.length;t++)this.forgetTouch(e.changedTouches[t]);e.preventDefault()}}onTouchMove(e){this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",e.touches),e.preventDefault())}emitTouchData(e,t){if(!this.videoElementProvider.isVideoReady())return;const n=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),r=this.toStreamerMessagesProvider.toStreamerHandlers;for(let i=0;i<t.length;i++){const o=1,s=t[i],a=s.clientX-n.left,u=s.clientY-n.top;Q.Log(Q.GetStackTrace(),`F${this.fingerIds.get(s.identifier)}=(${a}, ${u})`,6);const l=this.coordinateConverter.normalizeAndQuantizeUnsigned(a,u);switch(e){case"TouchStart":r.get("TouchStart")([o,l.x,l.y,this.fingerIds.get(s.identifier),this.maxByteValue*(s.force>0?s.force:1),l.inRange?1:0]);break;case"TouchEnd":r.get("TouchEnd")([o,l.x,l.y,this.fingerIds.get(s.identifier),this.maxByteValue*s.force,l.inRange?1:0]);break;case"TouchMove":r.get("TouchMove")([o,l.x,l.y,this.fingerIds.get(s.identifier),this.maxByteValue*(s.force>0?s.force:1),l.inRange?1:0])}}}}class Jt{constructor(e){this.gamePadEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const t=window;if(window.addEventListener("beforeunload",(e=>this.onBeforeUnload(e))),"GamepadEvent"in t){const e=e=>this.gamePadConnectHandler(e),t=e=>this.gamePadDisconnectHandler(e);window.addEventListener("gamepadconnected",e),window.addEventListener("gamepaddisconnected",t),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",e))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",t)))}else if("WebKitGamepadEvent"in t){const e=e=>this.gamePadConnectHandler(e),t=e=>this.gamePadDisconnectHandler(e);window.addEventListener("webkitgamepadconnected",e),window.addEventListener("webkitgamepaddisconnected",t),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",e))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",t)))}if(this.controllers=[],navigator.getGamepads)for(const e of navigator.getGamepads())e&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:e}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const e of this.controllers)void 0!==e.id&&this.onGamepadDisconnected(e.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(e){Q.Log(Q.GetStackTrace(),"Gamepad connect handler",6);const t=e.gamepad,n={currentState:t,prevState:t,id:void 0};this.controllers.push(n),this.controllers[t.index].currentState=t,this.controllers[t.index].prevState=t,Q.Log(Q.GetStackTrace(),"gamepad: "+t.id+" connected",6),window.requestAnimationFrame((()=>this.updateStatus())),this.onGamepadConnected()}gamePadDisconnectHandler(e){Q.Log(Q.GetStackTrace(),"Gamepad disconnect handler",6),Q.Log(Q.GetStackTrace(),"gamepad: "+e.gamepad.id+" disconnected",6);const t=this.controllers[e.gamepad.index];delete this.controllers[e.gamepad.index],this.controllers=this.controllers.filter((e=>void 0!==e)),this.onGamepadDisconnected(t.id)}scanGamePads(){const e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let t=0;t<e.length;t++)e[t]&&e[t].index in this.controllers&&(this.controllers[e[t].index].currentState=e[t])}updateStatus(){this.scanGamePads();const e=this.toStreamerMessagesProvider.toStreamerHandlers;for(const t of this.controllers){const n=void 0===t.id?this.controllers.indexOf(t):t.id,r=t.currentState;for(let r=0;r<t.currentState.buttons.length;r++){const i=t.currentState.buttons[r],o=t.prevState.buttons[r];i.pressed?r==Ot.LeftTrigger?e.get("GamepadAnalog")([n,5,i.value]):r==Ot.RightTrigger?e.get("GamepadAnalog")([n,6,i.value]):e.get("GamepadButtonPressed")([n,r,o.pressed?1:0]):!i.pressed&&o.pressed&&(r==Ot.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):r==Ot.RightTrigger?e.get("GamepadAnalog")([n,6,0]):e.get("GamepadButtonReleased")([n,r,0]))}for(let t=0;t<r.axes.length;t+=2){const i=parseFloat(r.axes[t].toFixed(4)),o=-parseFloat(r.axes[t+1].toFixed(4));e.get("GamepadAnalog")([n,t+1,i]),e.get("GamepadAnalog")([n,t+2,o])}this.controllers[n].prevState=r}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(e){for(const t of this.controllers)if(void 0===t.id){t.id=e;break}}onGamepadConnected(){}onGamepadDisconnected(e){}onBeforeUnload(e){for(const e of this.controllers)this.onGamepadDisconnected(e.id)}}!function(e){e[e.RightClusterBottomButton=0]="RightClusterBottomButton",e[e.RightClusterRightButton=1]="RightClusterRightButton",e[e.RightClusterLeftButton=2]="RightClusterLeftButton",e[e.RightClusterTopButton=3]="RightClusterTopButton",e[e.LeftShoulder=4]="LeftShoulder",e[e.RightShoulder=5]="RightShoulder",e[e.LeftTrigger=6]="LeftTrigger",e[e.RightTrigger=7]="RightTrigger",e[e.SelectOrBack=8]="SelectOrBack",e[e.StartOrForward=9]="StartOrForward",e[e.LeftAnalogPress=10]="LeftAnalogPress",e[e.RightAnalogPress=11]="RightAnalogPress",e[e.LeftClusterTopButton=12]="LeftClusterTopButton",e[e.LeftClusterBottomButton=13]="LeftClusterBottomButton",e[e.LeftClusterLeftButton=14]="LeftClusterLeftButton",e[e.LeftClusterRightButton=15]="LeftClusterRightButton",e[e.CentreButton=16]="CentreButton",e[e.LeftStickHorizontal=0]="LeftStickHorizontal",e[e.LeftStickVertical=1]="LeftStickVertical",e[e.RightStickHorizontal=2]="RightStickHorizontal",e[e.RightStickVertical=3]="RightStickVertical"}(Ot||(Ot={}));class Qt{constructor(e,t,n){this.activeKeys=new Yt,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){Q.Log(Q.GetStackTrace(),"Register Keyboard Events",7);const t=new Ht(this.toStreamerMessagesProvider,e,this.activeKeys);return t.registerKeyBoardEvents(),t}registerMouse(e){Q.Log(Q.GetStackTrace(),"Register Mouse Events",7);const t=new Kt(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(e){case pt.LockedMouse:t.registerLockedMouseEvents(t);break;case pt.HoveringMouse:t.registerHoveringMouseEvents(t);break;default:Q.Info(Q.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),t.registerLockedMouseEvents(t)}return t}registerTouch(e,t){if(Q.Log(Q.GetStackTrace(),"Registering Touch",6),e){const e=new zt(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return e.setVideoElementParentClientRect(t),e}return new Xt(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return Q.Log(Q.GetStackTrace(),"Register Game Pad",7),new Jt(this.toStreamerMessagesProvider)}}class Yt{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Zt{constructor(e,t){this.lastTimeResized=(new Date).getTime(),this.videoElement=document.createElement("video"),this.config=t,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",e.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{null!=this.audioElement&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",(()=>this.resizePlayerStyle()),!0),window.addEventListener("orientationchange",(()=>this.onOrientationChange()))}setAudioElement(e){this.audioElement=e}play(){return this.videoElement.muted=this.config.isFlagEnabled(it.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(it.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return void 0!==this.videoElement.readyState&&this.videoElement.readyState>0}hasVideoSource(){return void 0!==this.videoElement.srcObject&&null!==this.videoElement.srcObject}getVideoElement(){return this.videoElement}getVideoParentElement(){return this.videoElement.parentElement}setVideoEnabled(e){this.videoElement.srcObject.getTracks().forEach((t=>t.enabled=e))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const e=this.getVideoParentElement();e&&(this.updateVideoStreamSize(),e.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(it.MatchViewportResolution))if((new Date).getTime()-this.lastTimeResized>300){const e=this.getVideoParentElement();if(!e)return;this.onMatchViewportResolutionCallback(e.clientWidth,e.clientHeight),this.lastTimeResized=(new Date).getTime()}else Q.Log(Q.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class en{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(e,t,n){switch(e){case At.ToStreamer:this.toStreamerHandlers.set(t,n);break;case At.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:Q.Log(Q.GetStackTrace(),`Unknown message direction ${e}`)}}}!function(e){e[e.ToStreamer=0]="ToStreamer",e[e.FromStreamer=1]="FromStreamer"}(At||(At={}));class tn{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.Response",6);const t=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),t,6),this.responseEventListeners.forEach((e=>{e(t)}))}}class nn{constructor(e,t){this.dataChannelSender=e,this.toStreamerMessagesMapProvider=t}sendMessageToStreamer(e,t){void 0===t&&(t=[]);const n=this.toStreamerMessagesMapProvider.toStreamerMessages.get(e);if(void 0===n)return void Q.Error(Q.GetStackTrace(),`Attempted to send a message to the streamer with message type: ${e}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);if(n.structure&&t&&n.structure.length!==t.length)return void Q.Error(Q.GetStackTrace(),`Provided message data doesn't match expected layout. Expected [ ${n.structure.map((e=>{switch(e){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${t.map((e=>typeof e)).toString()} ]`);let r=0;const i=new TextEncoder;t.forEach(((e,t)=>{switch(n.structure[t]){case"uint8":r+=1;break;case"uint16":case"int16":r+=2;break;case"float":r+=4;break;case"double":r+=8;break;case"string":r+=2,r+=2*i.encode(e).length}}));const o=new DataView(new ArrayBuffer(r+1));o.setUint8(0,n.id);let s=1;t.forEach(((e,t)=>{switch(n.structure[t]){case"uint8":o.setUint8(s,e),s+=1;break;case"uint16":o.setUint16(s,e,!0),s+=2;break;case"int16":o.setInt16(s,e,!0),s+=2;break;case"float":o.setFloat32(s,e,!0),s+=4;break;case"double":o.setFloat64(s,e,!0),s+=8;break;case"string":o.setUint16(s,e.length,!0),s+=2;for(let t=0;t<e.length;t++)o.setUint16(s,e.charCodeAt(t),!0),s+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(o.buffer):Q.Info(Q.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(o.buffer)}`)}}class rn{constructor(e){this.sendMessageController=e}SendRequestQualityControl(){this.sendMessageController.sendMessageToStreamer("RequestQualityControl")}SendMaxFpsRequest(){this.sendMessageController.sendMessageToStreamer("FpsRequest")}SendAverageBitrateRequest(){this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")}SendStartStreaming(){this.sendMessageController.sendMessageToStreamer("StartStreaming")}SendStopStreaming(){this.sendMessageController.sendMessageToStreamer("StopStreaming")}SendRequestInitialSettings(){this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")}}class on{constructor(e){this.dataChannelProvider=e}canSend(){return void 0!==this.dataChannelProvider.getDataChannelInstance().dataChannel&&"open"==this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState}sendData(e){const t=this.dataChannelProvider.getDataChannelInstance();"open"==t.dataChannel.readyState?(t.dataChannel.send(e),Q.Log(Q.GetStackTrace(),`Message Sent: ${new Uint8Array(e)}`,6),this.resetAfkWarningTimerOnDataSend()):Q.Error(Q.GetStackTrace(),`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}}class sn{constructor(e){this.videoElementProvider=e,this.normalizeAndQuantizeUnsignedFunc=()=>{throw new Error("Normalize and quantize unsigned, method not implemented.")},this.normalizeAndQuantizeSignedFunc=()=>{throw new Error("Normalize and unquantize signed, method not implemented.")},this.denormalizeAndUnquantizeUnsignedFunc=()=>{throw new Error("Denormalize and unquantize unsigned, method not implemented.")}}normalizeAndQuantizeUnsigned(e,t){return this.normalizeAndQuantizeUnsignedFunc(e,t)}unquantizeAndDenormalizeUnsigned(e,t){return this.denormalizeAndUnquantizeUnsignedFunc(e,t)}normalizeAndQuantizeSigned(e,t){return this.normalizeAndQuantizeSignedFunc(e,t)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const e=this.videoElementParent.clientWidth||1,t=this.videoElementParent.clientHeight||1,n=this.videoElement.videoWidth||1,r=t/e,i=(this.videoElement.videoHeight||1)/n;r>i?(Q.Log(Q.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=r/i,this.normalizeAndQuantizeUnsignedFunc=(e,t)=>this.normalizeAndQuantizeUnsignedPlayerBigger(e,t),this.normalizeAndQuantizeSignedFunc=(e,t)=>this.normalizeAndQuantizeSignedPlayerBigger(e,t),this.denormalizeAndUnquantizeUnsignedFunc=(e,t)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(e,t)):(Q.Log(Q.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=i/r,this.normalizeAndQuantizeUnsignedFunc=(e,t)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(e,t),this.normalizeAndQuantizeSignedFunc=(e,t)=>this.normalizeAndQuantizeSignedPlayerSmaller(e,t),this.denormalizeAndUnquantizeUnsignedFunc=(e,t)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(e,t))}}normalizeAndQuantizeUnsignedPlayerBigger(e,t){const n=e/this.videoElementParent.clientWidth,r=this.ratio*(t/this.videoElementParent.clientHeight-.5)+.5;return n<0||n>1||r<0||r>1?new an(!1,65535,65535):new an(!0,65536*n,65536*r)}denormalizeAndUnquantizeUnsignedPlayerBigger(e,t){const n=e/65536,r=(t/65536-.5)/this.ratio+.5;return new un(n*this.videoElementParent.clientWidth,r*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(e,t){const n=e/(.5*this.videoElementParent.clientWidth),r=this.ratio*t/(.5*this.videoElementParent.clientHeight);return new ln(32767*n,32767*r)}normalizeAndQuantizeUnsignedPlayerSmaller(e,t){const n=this.ratio*(e/this.videoElementParent.clientWidth-.5)+.5,r=t/this.videoElementParent.clientHeight;return n<0||n>1||r<0||r>1?new an(!1,65535,65535):new an(!0,65536*n,65536*r)}denormalizeAndUnquantizeUnsignedPlayerSmaller(e,t){const n=(e/65536-.5)/this.ratio+.5,r=t/65536;return new un(n*this.videoElementParent.clientWidth,r*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(e,t){const n=this.ratio*e/(.5*this.videoElementParent.clientWidth),r=t/(.5*this.videoElementParent.clientHeight);return new ln(32767*n,32767*r)}}class an{constructor(e,t,n){this.inRange=e,this.x=t,this.y=n}}class un{constructor(e,t){this.x=e,this.y=t}}class ln{constructor(e,t){this.x=e,this.y=t}}class cn{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new tn,this.file=new Ut,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new ft(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new fe(this.pixelStreaming.videoElementParent),this.videoPlayer=new Zt(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(e,t)=>{const n={"Resolution.Width":e,"Resolution.Height":t};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(n)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new he(this.videoPlayer),this.coordinateConverter=new sn(this.videoPlayer),this.sendrecvDataChannelController=new gt,this.recvDataChannelController=new gt,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new on(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new en,this.webSocketController=new de,this.webSocketController.onConfig=e=>this.handleOnConfigMessage(e),this.webSocketController.onStreamerList=e=>this.handleStreamerListMessage(e),this.webSocketController.onStreamerIDChanged=e=>this.handleStreamerIDChangedMessage(e),this.webSocketController.onPlayerCount=e=>{this.pixelStreaming._onPlayerCount(e.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(it.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(e=>{const t=this.shouldReconnect&&1001!=e.detail.code&&this.config.getNumericSettingValue(st.MaxReconnectAttempts)>0,n=this.disconnectMessage?this.disconnectMessage:e.detail.reason;this.pixelStreaming._onDisconnect(n,!t&&!this.isReconnecting),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&void 0!==this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),t&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(e.detail.reason)}),2e3)})),this.sendMessageController=new nn(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new rn(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new Qt(this.streamMessageController,this.videoPlayer,this.coordinateConverter),this.isUsingSFU=!1,this.isQualityController=!1,this.preferredCodec="",this.shouldReconnect=!0,this.isReconnecting=!1,this.reconnectAttempt=0,this.config._addOnOptionSettingChangedListener(ct.StreamerId,(e=>{""!==e&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=e,this.webSocketController.sendSubscribe(e))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let e=this.config.getTextSettingValue(ut.SignallingServerUrl);return this.config.isFlagEnabled(it.BrowserSendOffer)&&(e+="?"+it.BrowserSendOffer+"=true"),e}}requestUnquantizedAndDenormalizeUnsigned(e,t){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(e,t)}handleOnMessage(e){const t=new Uint8Array(e.data);Q.Log(Q.GetStackTrace(),"Message incoming:"+t,6);const n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(At.FromStreamer,"QualityControlOwnership",(e=>this.onQualityControlOwnership(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"Response",(e=>this.responseController.onResponse(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"Command",(e=>{this.onCommand(e)})),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FreezeFrame",(e=>this.onFreezeFrameMessage(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler(At.FromStreamer,"VideoEncoderAvgQP",(e=>this.handleVideoEncoderAvgQP(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"LatencyTest",(e=>this.handleLatencyTestResult(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"DataChannelLatencyTest",(e=>this.handleDataChannelLatencyTestResponse(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"InitialSettings",(e=>this.handleInitialSettings(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FileExtension",(e=>this.onFileExtension(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FileMimeType",(e=>this.onFileMimeType(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FileContents",(e=>this.onFileContents(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(At.FromStreamer,"InputControlOwnership",(e=>this.onInputControlOwnership(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"GamepadResponse",(e=>this.onGamepadResponse(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"Protocol",(e=>this.onProtocolMessage(e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"LatencyTest",(e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(At.ToStreamer,"UIInteraction",(e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"Command",(e=>this.sendMessageController.sendMessageToStreamer("Command",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TextboxEntry",(e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"KeyDown",(e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"KeyUp",(e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"KeyPress",(e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseEnter",(e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseLeave",(e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseDown",(e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseUp",(e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseMove",(e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseWheel",(e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseDouble",(e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TouchStart",(e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TouchEnd",(e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TouchMove",(e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadButtonPressed",(e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadButtonReleased",(e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadAnalog",(e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadDisconnected",(e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XREyeViews",(e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRHMDTransform",(e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRControllerTransform",(e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRSystem",(e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonTouched",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonTouchReleased",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonPressed",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonReleased",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRAnalog",(e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)))}onCommand(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const t=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),"Data Channel Command: "+t,6);const n=JSON.parse(t);"onScreenKeyboard"===n.command&&this.pixelStreaming._activateOnScreenKeyboard(n)}onProtocolMessage(e){try{const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||Q.Error(Q.GetStackTrace(),"Malformed protocol received. Ensure the protocol message contains a direction");const r=n.Direction;delete n.Direction,Q.Log(Q.GetStackTrace(),`Received new ${r==At.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach((e=>{const t=n[e];switch(r){case At.ToStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Q.Error(Q.GetStackTrace(),`ToStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);if("UIInteraction"===e||"Command"===e||"LatencyTest"===e)return;this.streamMessageController.toStreamerHandlers.get(e)?this.streamMessageController.toStreamerMessages.set(e,t):Q.Error(Q.GetStackTrace(),`There was no registered handler for "${e}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${e}", myHandler)`);break;case At.FromStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Q.Error(Q.GetStackTrace(),`FromStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(e)?this.streamMessageController.fromStreamerMessages.set(t.id,e):Q.Error(Q.GetStackTrace(),`There was no registered handler for "${t}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${e}", myHandler)`);break;default:Q.Error(Q.GetStackTrace(),`Unknown direction: ${r}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(e){Q.Log(Q.GetStackTrace(),e)}}onInputControlOwnership(e){const t=new Uint8Array(e);Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const n=new Boolean(t[1]).valueOf();Q.Log(Q.GetStackTrace(),`Received input controller message - will your input control the stream: ${n}`),this.pixelStreaming._onInputControlOwnership(n)}onGamepadResponse(e){const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.gamePadController.onGamepadResponseReceived(n.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(e){e?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(e){this.webSocketController?(this.isReconnecting=!0,this.webSocketController.webSocket&&this.webSocketController.webSocket.readyState!=WebSocket.CLOSED?(this.closeSignalingServer(`${e} Restarting stream...`),setTimeout((()=>{this.tryReconnect(e)}),3e3)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):Q.Log(Q.GetStackTrace(),"The Web Socket Controller does not exist so this will not work right now.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new ze({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),!0===this.shouldShowPlayOverlay?(Q.Log(Q.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(Q.Log(Q.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const t=new Uint8Array(e);this.freezeFrameController.processFreezeFrameMessage(t,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Ve),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(e){const t=new Uint8Array(e);Ft.setExtensionFromBytes(t,this.file)}onFileMimeType(e){const t=new Uint8Array(e);Ft.setMimeTypeFromBytes(t,this.file)}onFileContents(e){const t=new Uint8Array(e);Ft.setContentsFromBytes(t,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const e="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Ne({message:e})),Q.Error(Q.GetStackTrace(),e),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(it.TouchInput)),this.pixelStreaming.dispatchEvent(new je),this.streamController.audioElement.srcObject){const e=this.config.isFlagEnabled(it.StartVideoMuted);this.streamController.audioElement.muted=e,e?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((e=>{Q.Log(Q.GetStackTrace(),e),Q.Log(Q.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Be({reason:e}))}))}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else Q.Warning(Q.GetStackTrace(),"Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch((e=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),Q.Log(Q.GetStackTrace(),e),Q.Log(Q.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Be({reason:e}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(it.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const e=this.signallingUrlBuilder();this.webSocketController.connect(e)}startSession(e){if(this.peerConfig=e,this.config.isFlagEnabled(it.ForceTURN)&&!this.checkTurnServerAvailability(e))return Q.Info(Q.GetStackTrace(),"No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.");this.peerConnectionController=new It(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=e=>this.handleVideoStats(e),this.peerConnectionController.onSendWebRTCOffer=e=>this.handleSendWebRTCOffer(e),this.peerConnectionController.onSendWebRTCAnswer=e=>this.handleSendWebRTCAnswer(e),this.peerConnectionController.onPeerIceCandidate=e=>this.handleSendIceCandidate(e),this.peerConnectionController.onDataChannel=e=>this.handleDataChannel(e),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let t=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!t&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),t=!0)},this.peerConnectionController.onTrack=e=>this.streamController.handleOnTrack(e),this.config.isFlagEnabled(it.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(e){if(!e.iceServers)return Q.Info(Q.GetStackTrace(),"A turn sever was not found"),!1;for(const t of e.iceServers)for(const e of t.urls)if(e.includes("turn"))return Q.Log(Q.GetStackTrace(),`A turn sever was found at ${e}`),!0;return Q.Info(Q.GetStackTrace(),"A turn sever was not found"),!1}handleOnConfigMessage(e){this.resizePlayerStyle(),this.startSession(e.peerConnectionOptions),this.webSocketController.onWebRtcAnswer=e=>this.handleWebRtcAnswer(e),this.webSocketController.onWebRtcOffer=e=>this.handleWebRtcOffer(e),this.webSocketController.onWebRtcPeerDataChannels=e=>this.handleWebRtcSFUPeerDatachannels(e),this.webSocketController.onIceCandidate=e=>this.handleIceCandidate(e)}handleStreamerListMessage(e){Q.Log(Q.GetStackTrace(),`Got streamer list ${e.ids}`,6);let t=null;var n=this.config.getSettingOption(ct.StreamerId);n.selected.toString().trim()&&(t=n.selected);const r=[...e.ids];r.unshift(""),this.config.setOptionSettingOptions(ct.StreamerId,r);let i=null;const o=this.config.isFlagEnabled(it.WaitForStreamer),s=this.config.getNumericSettingValue(st.MaxReconnectAttempts),a=this.config.getNumericSettingValue(st.StreamerAutoJoinInterval),u=this.config.useUrlParams,l=new URLSearchParams(window.location.search);u&&l.has(ct.StreamerId)?t=l.get(ct.StreamerId):this.subscribedStream&&(t=this.subscribedStream),t&&e.ids.includes(t)?i=t:t&&o||1!=e.ids.length||(i=e.ids[0]),i?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(ct.StreamerId,i)):o&&(this.reconnectAttempt<s?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),a)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new He({messageStreamerList:e,autoSelectedStreamerId:i,wantedStreamerId:t}))}handleStreamerIDChangedMessage(e){const t=e.newID;var n=this.config.getSettingOption(ct.StreamerId),r=n.onChange;n.onChange=()=>{};for(var i=n.options,o=0;o<i.length;++o)if(i[o]==this.subscribedStream){i[o]=t;break}n.options=i,n.selected=t,n.onChange=r,this.subscribedStream=e.newID,this.pixelStreaming.dispatchEvent(new We({newID:t}))}handleWebRtcAnswer(e){Q.Log(Q.GetStackTrace(),`Got answer sdp ${e.sdp}`,6);const t={sdp:e.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(t),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(e){Q.Log(Q.GetStackTrace(),`Got offer sdp ${e.sdp}`,6),this.isUsingSFU=!!e.sfu&&e.sfu,this.isUsingSFU&&(this.peerConnectionController.preferredCodec="");const t={sdp:e.sdp,type:"offer"};this.peerConnectionController.receiveOffer(t,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(e){const t={ordered:!0,negotiated:!0,id:e.sendStreamId},n=e.sendStreamId!=e.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,n?"send-datachannel":"datachannel",t),n){const t={ordered:!0,negotiated:!0,id:e.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",t),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}else this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&void 0!==this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval((()=>this.getStats()),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(it.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(it.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(it.GamepadInput))}handleIceCandidate(e){Q.Log(Q.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const t=new RTCIceCandidate(e);this.peerConnectionController.handleOnIce(t)}handleSendIceCandidate(e){Q.Log(Q.GetStackTrace(),"OnIceCandidate",6),e.candidate&&e.candidate.candidate&&this.webSocketController.sendIceCandidate(e.candidate)}handleDataChannel(e){Q.Log(Q.GetStackTrace(),"Data channel created for us by browser as we are a receiving peer.",6),this.sendrecvDataChannelController.dataChannel=e.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handleSendWebRTCOffer(e){Q.Log(Q.GetStackTrace(),"Sending the offer to the Server",6);const t={minBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(e,t)}handleSendWebRTCAnswer(e){Q.Log(Q.GetStackTrace(),"Sending the answer to the Server",6);const t={minBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(e,t),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(e){var t;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=e,null===(t=this.webSocketController)||void 0===t||t.close()}closePeerConnection(){var e;null===(e=this.peerConnectionController)||void 0===e||e.close()}close(){this.closeSignalingServer(""),this.closePeerConnection()}getStats(){this.peerConnectionController.generateStats()}sendLatencyTest(){this.latencyStartTime=Date.now(),this.streamMessageController.toStreamerHandlers.get("LatencyTest")([JSON.stringify({StartTime:this.latencyStartTime})])}sendDataChannelLatencyTest(e){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(e)])}sendEncoderMinQP(e){Q.Log(Q.GetStackTrace(),`MinQP=${e}\n`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":e})])}sendEncoderMaxQP(e){Q.Log(Q.GetStackTrace(),`MaxQP=${e}\n`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":e})])}sendWebRTCMinBitrate(e){Q.Log(Q.GetStackTrace(),`WebRTC Min Bitrate=${e}`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":e})])}sendWebRTCMaxBitrate(e){Q.Log(Q.GetStackTrace(),`WebRTC Max Bitrate=${e}`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":e})])}sendWebRTCFps(e){Q.Log(Q.GetStackTrace(),`WebRTC FPS=${e}`,6),null!=e&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":e})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":e})]))}sendShowFps(){Q.Log(Q.GetStackTrace(),"---- Sending show stat to UE ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){Q.Log(Q.GetStackTrace(),"---- Sending Request for an IFrame ----",6),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(e){Q.Log(Q.GetStackTrace(),"---- Sending custom UIInteraction message ----",6),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(e)])}emitCommand(e){Q.Log(Q.GetStackTrace(),"---- Sending custom Command message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(e)])}emitConsoleCommand(e){Q.Log(Q.GetStackTrace(),"---- Sending custom Command:ConsoleCommand message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:e})])}sendRequestQualityControlOwnership(){Q.Log(Q.GetStackTrace(),"---- Sending Request to Control Quality ----",6),this.toStreamerMessagesController.SendRequestQualityControl()}handleLatencyTestResult(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.latencyTest",6);const t=new TextDecoder("utf-16").decode(e.slice(1)),n=new Lt;Object.assign(n,JSON.parse(t)),n.processFields(),n.testStartTimeMs=this.latencyStartTime,n.browserReceiptTimeMs=Date.now(),n.latencyExcludingDecode=~~(n.browserReceiptTimeMs-n.testStartTimeMs),n.testDuration=~~(n.TransmissionTimeMs-n.ReceiptTimeMs),n.networkLatency=~~(n.latencyExcludingDecode-n.testDuration),n.frameDisplayDeltaTimeMs&&n.browserReceiptTimeMs&&(n.endToEndLatency=(n.frameDisplayDeltaTimeMs,n.networkLatency,~~+n.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(n)}handleDataChannelLatencyTestResponse(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.dataChannelLatencyResponse",6);const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.pixelStreaming._onDataChannelLatencyTestResponse(n)}handleInitialSettings(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t),r=new Mt;n.Encoder&&(r.EncoderSettings=n.Encoder),n.WebRTC&&(r.WebRTCSettings=n.WebRTC),n.PixelStreaming&&(r.PixelStreamingSettings=n.PixelStreaming),n.ConfigOptions&&void 0!==n.ConfigOptions.DefaultToHover&&this.config.setFlagEnabled(it.HoveringMouseMode,!!n.ConfigOptions.DefaultToHover),r.ueCompatible(),Q.Log(Q.GetStackTrace(),t,6),this.pixelStreaming._onInitialSettings(r)}handleVideoEncoderAvgQP(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const t=Number(new TextDecoder("utf-16").decode(e.slice(1)));this.setVideoEncoderAvgQP(t)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(e){const t=new Uint8Array(e);Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(t[1]).valueOf(),Q.Log(Q.GetStackTrace(),`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(e){this.pixelStreaming._onVideoStats(e)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(e){this.preferredCodec=e,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=e,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(e){this.videoAvgQp=e,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(e){var t;null===(t=this.keyboardController)||void 0===t||t.unregisterKeyBoardEvents(),e&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(e){var t;if(null===(t=this.mouseController)||void 0===t||t.unregisterMouseEvents(),e){const e=this.config.isFlagEnabled(it.HoveringMouseMode)?pt.HoveringMouse:pt.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(e)}}setTouchInputEnabled(e){var t;null===(t=this.touchController)||void 0===t||t.unregisterTouchEvents(),e&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(it.FakeMouseWithTouches),this.videoElementParentClientRect))}setGamePadInputEnabled(e){var t;null===(t=this.gamePadController)||void 0===t||t.unregisterGamePadEvents(),e&&(this.gamePadController=this.inputClassesFactory.registerGamePad(),this.gamePadController.onGamepadConnected=()=>{this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()},this.gamePadController.onGamepadDisconnected=e=>{this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e])})}registerDataChannelEventEmitters(e){e.onOpen=(e,t)=>this.pixelStreaming.dispatchEvent(new Ie({label:e,event:t})),e.onClose=(e,t)=>this.pixelStreaming.dispatchEvent(new Me({label:e,event:t})),e.onError=(e,t)=>this.pixelStreaming.dispatchEvent(new Re({label:e,event:t}))}registerMessageHandler(e,t,n){t===At.FromStreamer&&void 0===n&&Q.Warning(Q.GetStackTrace(),`Unable to register handler for ${e} as no handler was passed`),this.streamMessageController.registerMessageHandler(t,e,(r=>void 0===n&&t===At.ToStreamer?this.sendMessageController.sendMessageToStreamer(e,r):n(r)))}}class dn{constructor(e){this.toStreamerMessagesProvider=e,this.controllers=[]}static deepCopyGamepad(e){return JSON.parse(JSON.stringify({buttons:e.buttons.map((e=>JSON.parse(JSON.stringify({pressed:e.pressed,touched:e.touched,value:e.value})))),axes:e.axes}))}updateStatus(e,t,n){if(e.gamepad){const r=t.getPose(e.gripSpace,n);if(!r)return;let i=0;e.profiles.includes("htc-vive")?i=1:e.profiles.includes("oculus-touch")&&(i=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([i]);let o=2;switch(e.handedness){case"left":o=0;break;case"right":o=1}const s=r.transform.matrix,a=[];for(let e=0;e<16;e++)a[e]=new Float32Array([s[e]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],o]),void 0===this.controllers[o]&&(this.controllers[o]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[o].prevState=dn.deepCopyGamepad(e.gamepad)),this.controllers[o].currentState=dn.deepCopyGamepad(e.gamepad);const u=this.controllers[o],l=u.currentState,c=u.prevState;for(let e=0;e<l.buttons.length;e++){const t=l.buttons[e],n=c.buttons[e];if(t.pressed){let t=n.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([o,e,t])}else n.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([o,e,0]);if(t.touched){let t=n.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([o,e,t])}else n.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([o,e,0])}for(let e=0;e<l.axes.length;e++){let t=l.axes[e];t!=c.axes[e]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([o,e,t])}this.controllers[o].prevState=l}}}class hn{constructor(e){this.xrViewerPose=null,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.xrSession=null,this.webRtcController=e,this.xrGamepadController=new dn(this.webRtcController.streamMessageController),this.onSessionEnded=new EventTarget,this.onSessionStarted=new EventTarget,this.onFrame=new EventTarget}xrClicked(){if(this.xrSession)this.xrSession.end();else{if(!navigator.xr)return void Q.Error(Q.GetStackTrace(),"This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then((e=>{this.onXrSessionStarted(e)}))}}onXrSessionEnded(){Q.Log(Q.GetStackTrace(),"XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const e=document.createElement("canvas");this.gl=e.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const e=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(e,"\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n // varyings\n varying vec2 v_texCoord;\n\n void main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n // pass the texCoord to the fragment shader\n // The GPU will interpolate this value between points.\n v_texCoord = a_texCoord;\n }\n "),this.gl.compileShader(e);const t=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(t,"\n precision mediump float;\n\n // our texture\n uniform sampler2D u_image;\n\n // the texCoords passed in from the vertex shader.\n varying vec2 v_texCoord;\n\n void main() {\n gl_FragColor = texture2D(u_image, v_texCoord);\n }\n "),this.gl.compileShader(t);const n=this.gl.createProgram();this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),this.gl.useProgram(n),this.positionLocation=this.gl.getAttribLocation(n,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(n,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let e=this.webRtcController.videoPlayer.getVideoElement().videoHeight,t=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=e||this.prevVideoWidth!=t?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=e,this.prevVideoWidth=t}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(e){Q.Log(Q.GetStackTrace(),"XR Session started"),this.xrSession=e,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),e.requestReferenceSpace("local").then((t=>{if(this.xrRefSpace=t,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let t of this.xrSession.supportedFrameRates)90==t&&e.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))})),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}sendXRDataToUE(){if(null==this.leftView||null==this.rightView)return;const e=this.leftView.transform.matrix,t=this.leftView.projectionMatrix,n=this.rightView.transform.matrix,r=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([e[0],e[4],e[8],e[12],e[1],e[5],e[9],e[13],e[2],e[6],e[10],e[14],e[3],e[7],e[11],e[15],t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15],n[0],n[4],n[8],n[12],n[1],n[5],n[9],n[13],n[2],n[6],n[10],n[14],n[3],n[7],n[11],n[15],r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15]])}onXrFrame(e,t){if(this.xrViewerPose=t.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),null==this.leftView||null==this.rightView)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(it.XRControllerInput)&&this.xrSession.inputSources.forEach(((e,n,r)=>{this.xrGamepadController.updateStatus(e,t,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((e,t)=>this.onXrFrame(e,t))),this.onFrame.dispatchEvent(new et({time:e,frame:t}))}updateViews(){if(this.xrViewerPose)for(const e of this.xrViewerPose.views)"left"===e.eye?this.leftView=e:"right"===e.eye&&(this.rightView=e)}render(){if(!this.gl)return;const e=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e.framebuffer),this.gl.viewport(0,0,e.framebufferWidth,e.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(e){return"https:"!==location.protocol&&Q.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(e):new Promise((()=>!1))}}class pn{constructor(e){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(e)}unquantizeAndDenormalizeUnsigned(e,t){return null}createOnScreenKeyboardHelpers(e){this.hiddenInput||(this.hiddenInput=document.createElement("input"),this.hiddenInput.id="hiddenInput",this.hiddenInput.maxLength=0,this.hiddenInput.style.position="absolute",this.hiddenInput.style.left="-10%",this.hiddenInput.style.width="0px",this.hiddenInput.style.opacity="0",e.appendChild(this.hiddenInput)),this.editTextButton||(this.editTextButton=document.createElement("button"),this.editTextButton.id="editTextButton",this.editTextButton.innerHTML="edit text",e.appendChild(this.editTextButton),this.editTextButton.style.display="none",this.editTextButton.addEventListener("touchend",(e=>{this.hiddenInput.focus(),e.preventDefault()})))}showOnScreenKeyboard(e){if(e.showOnScreenKeyboard){this.editTextButton.style.display="default";const t=this.unquantizeAndDenormalizeUnsigned(e.x,e.y);this.editTextButton.style.top=t.y.toString()+"px",this.editTextButton.style.left=(t.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class fn{constructor(e){this.seq=e.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=e.Filler?e.Filler.length:0}update(e){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=e.ReceivedTimestamp,this.streamerSentTimestamp=e.SentTimestamp,this.responseFillerSize=e.Filler?e.Filler.length:0}}class gn{constructor(e,t){this.sink=e,this.callback=t,this.records=new Map,this.seq=0}start(e){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=e.duration?this.stop():this.sendRequest(e.requestSize,e.responseSize)}).bind(this),Math.floor(1e3/e.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const e=new Map(this.records);return{records:e,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((e,t)=>e+(t.playerReceivedTimestamp-t.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((e,t)=>e+(t.streamerReceivedTimestamp-t.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((e,t)=>e+(t.playerReceivedTimestamp-t.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let t="Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;\n";return e.forEach((e=>{t+=e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.streamerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.streamerSentTimestamp+";",t+="\n"})),t}}}isRunning(){return!!this.interval}receive(e){if(!this.isRunning())return;if(!e)return void Q.Error(Q.GetStackTrace(),"Undefined response from server");let t=this.records.get(e.Seq);t&&t.update(e)}sendRequest(e,t){let n=this.createRequest(e,t),r=new fn(n);this.records.set(r.seq,r),this.sink(n)}createRequest(e,t){return{Seq:this.seq++,FillResponseSize:t,Filler:e?"A".repeat(e):""}}}class mn{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,(null==t?void 0:t.videoElementParent)&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new rt,this.configureSettings(),this.setWebRtcPlayerController(new cn(this.config,this)),this.onScreenKeyboardHelper=new pn(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(e,t)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(e,t),this._activateOnScreenKeyboard=e=>this.onScreenKeyboardHelper.showOnScreenKeyboard(e),this._webXrController=new hn(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(e=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(it.IsQualityController,(e=>{!0!==e||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(it.AFKDetection,(e=>{this._webRtcController.setAfkEnabled(e)})),this.config._addOnSettingChangedListener(it.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(it.HoveringMouseMode,(e=>{this.config.setFlagLabel(it.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(it.MouseInput))})),this.config._addOnSettingChangedListener(it.KeyboardInput,(e=>{this._webRtcController.setKeyboardInputEnabled(e)})),this.config._addOnSettingChangedListener(it.MouseInput,(e=>{this._webRtcController.setMouseInputEnabled(e)})),this.config._addOnSettingChangedListener(it.FakeMouseWithTouches,(e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(it.TouchInput))})),this.config._addOnSettingChangedListener(it.TouchInput,(e=>{this._webRtcController.setTouchInputEnabled(e)})),this.config._addOnSettingChangedListener(it.GamepadInput,(e=>{this._webRtcController.setGamePadInputEnabled(e)})),this.config._addOnNumericSettingChangedListener(st.MinQP,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.MaxQP,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.WebRTCMinBitrate,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.WebRTCMaxBitrate,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.WebRTCFPS,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(ct.PreferredCodec,(e=>{this._webRtcController&&this._webRtcController.setPreferredCodec(e)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(e){throw new Error("Method not implemented.")}_onInputControlOwnership(e){this._inputController=e}setWebRtcPlayerController(e){this._webRtcController=e,this._webRtcController.setPreferredCodec(this.config.getSettingOption(ct.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Le),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Ue),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Fe),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(it.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(e=!1){if(!this.config.isFlagEnabled("UseMic"))return e?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void Q.Warning(Q.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):Q.Info(Q.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(e){var t,n,r,i;for(const o of null!==(i=null===(r=null===(n=null===(t=this._webRtcController)||void 0===t?void 0:t.peerConnectionController)||void 0===n?void 0:n.peerConnection)||void 0===r?void 0:r.getTransceivers())&&void 0!==i?i:[])Pt.canTransceiverSendAudio(o)&&(o.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Ce)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ee)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new $e)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new ke({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new Pe)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Oe)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Ae)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new De),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new qe({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new Ke({response:e}))}_onVideoStats(e){this._videoStartTime&&void 0!==this._videoStartTime||(this._videoStartTime=Date.now()),e.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Ge({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new xe({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Je({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=null!==(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)&&void 0!==t&&t,!1===this.allowConsoleCommands&&Q.Info(Q.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const n=this.config.useUrlParams,r=new URLSearchParams(window.location.search);Q.Info(Q.GetStackTrace(),`using URL parameters ${n}`),e.EncoderSettings&&(this.config.setNumericSetting(st.MinQP,n&&r.has(st.MinQP)?Number.parseFloat(r.get(st.MinQP)):e.EncoderSettings.MinQP),this.config.setNumericSetting(st.MaxQP,n&&r.has(st.MaxQP)?Number.parseFloat(r.get(st.MaxQP)):e.EncoderSettings.MaxQP)),e.WebRTCSettings&&(this.config.setNumericSetting(st.WebRTCMinBitrate,n&&r.has(st.WebRTCMinBitrate)?Number.parseFloat(r.get(st.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(st.WebRTCMaxBitrate,n&&r.has(st.WebRTCMaxBitrate)?Number.parseFloat(r.get(st.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(st.WebRTCFPS,n&&r.has(st.WebRTCFPS)?Number.parseFloat(r.get(st.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(it.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new tt({count:e}))}_setupWebRtcTCPRelayDetection(e){let t=e.data.aggregatedStats.getActiveCandidatePair();if(null!=t){let n=e.data.aggregatedStats.localCandidates.find((e=>e.id==t.localCandidateId),null);null!=n&&"relay"==n.candidateType&&"tcp"==n.relayProtocol&&this._eventEmitter.dispatchEvent(new nt),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new gn(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(e=>{this._eventEmitter.dispatchEvent(new Xe({result:e}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:e}})=>{this._dataChannelLatencyTestController.receive(e)}))),this._dataChannelLatencyTestController.start(e))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(e),!0)}emitCommand(e){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in e||(this._webRtcController.emitCommand(e),0))}emitConsoleCommand(e){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(e),0))}addResponseEventListener(e,t){this._webRtcController.responseController.addResponseEventListener(e,t)}removeResponseEventListener(e){this._webRtcController.responseController.removeResponseEventListener(e)}dispatchEvent(e){return this._eventEmitter.dispatchEvent(e)}addEventListener(e,t){this._eventEmitter.addEventListener(e,t)}removeEventListener(e,t){this._eventEmitter.removeEventListener(e,t)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(e){this._webRtcController.signallingUrlBuilder=e}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(e,t,n){t!==At.FromStreamer||void 0!==n?t===At.ToStreamer&&void 0===n?this._webRtcController.streamMessageController.registerMessageHandler(t,e,(t=>this._webRtcController.sendMessageController.sendMessageToStreamer(e,t))):this._webRtcController.streamMessageController.registerMessageHandler(t,e,(e=>n(e))):Q.Warning(Q.GetStackTrace(),`Unable to register an undefined handler for ${e}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class bn{}var yn,vn,wn,Sn,_n=J.De,Tn=J.vU,xn=J.g,En=J.x_;!function(e){e[e.VideoInitialised=0]="VideoInitialised",e[e.DataChannelOpen=1]="DataChannelOpen",e[e.DataChannelResponse=2]="DataChannelResponse",e[e.WaitingForRenderer=3]="WaitingForRenderer",e[e.RendererTaken=4]="RendererTaken",e[e.WebRtcStats=5]="WebRtcStats"}(yn||(yn={}));class Cn{constructor(){this.type=yn.VideoInitialised}}class Pn{constructor(){this.type=yn.DataChannelOpen}}class On{constructor(e){this.msg=e,this.type=yn.DataChannelResponse}}class An{constructor(e){this.stats=e,this.type=yn.WebRtcStats}}!function(e){e.IndexInQueue="index_in_queue",e.RendererTaken="renderer_taken",e.RendererGone="renderer_gone",e.RendererError="renderer_error",e.ClientGone="client_gone",e.SwitchRendererRequest="switch_renderer_request"}(vn||(vn={})),function(e){e.AvatarAnswer="AvatarAnswer",e.AvatarStartedSpeaking="AvatarStartedSpeaking",e.AvatarStoppedSpeaking="AvatarStoppedSpeaking",e.CallToActionDismissed="CallToActionDismissed",e.CustomMetadataUpdated="CustomMetadataUpdated",e.DataProcessingWarning="DataProcessingWarning",e.DeviceError="DeviceError",e.DigitalHumanMuted="DigitalHumanMuted",e.DigitalHumanPlayedInMutedModeSuccess="DigitalHumanPlayedInMutedModeSuccess",e.DigitalHumanUnmuted="DigitalHumanUnmuted",e.EnableMicrophoneUpdated="EnableMicrophoneUpdated",e.FrameReady="FrameReady",e.FrameResize="FrameResize",e.MicPermissionDenied="MicPermissionDenied",e.Notification="Notification",e.PromptRequest="PromptRequest",e.PromptResult="PromptResult",e.ReadyToStart="ReadyToStart",e.SceneReady="SceneReady",e.SessionBackendError="SessionBackendError",e.SessionConnecting="SessionConnecting",e.SessionDisconnected="SessionDisconnected",e.SessionEnded="SessionEnded",e.SessionError="SessionError",e.SessionLive="SessionLive",e.SessionReconnecting="SessionReconnecting",e.SessionReconnectingFinished="SessionReconnectingFinished",e.SessionStateUpdate="SessionStateUpdate",e.SoftSwitchFinished="SoftSwitchFinished",e.SoftSwitchStarting="SoftSwitchStarting",e.SpeechEvent="SpeechEvent",e.SpeechTranscription="SpeechTranscription",e.UnhandledMessage="UnhandledMessage",e.UserStartedSpeaking="UserStartedSpeaking",e.UserStoppedSpeaking="UserStoppedSpeaking",e.VadInterruptionAllowed="VadInterruptionAllowed",e.VideoLayoutConfiguring="VideoLayoutConfiguring",e.WaitingInQueue="WaitingInQueue",e.WebRtcStats="WebRtcStats"}(wn||(wn={}));class kn{constructor(e){this.error=e,this.uneeqMessageType=wn.DeviceError}}class In{constructor(e,t,n,r){this.answer=e,this.answerAvatar=t,this.answerSpeech=n,this.transcriptId=r,this.uneeqMessageType=wn.AvatarAnswer}}class Mn{constructor(e){this.speechTranscription=e,this.uneeqMessageType=wn.SpeechTranscription}}class Rn{constructor(e){this.interruptionAllowed=e,this.uneeqMessageType=wn.VadInterruptionAllowed}}class Dn{constructor(){this.uneeqMessageType=wn.UserStartedSpeaking}}class $n{constructor(){this.uneeqMessageType=wn.UserStoppedSpeaking}}class Ln{constructor(){this.uneeqMessageType=wn.AvatarStartedSpeaking}}class Fn{constructor(){this.uneeqMessageType=wn.AvatarStoppedSpeaking}}class Un{constructor(e){this.sessionId=e,this.uneeqMessageType=wn.SessionLive}}class Nn{constructor(e){this.position=e,this.uneeqMessageType=wn.WaitingInQueue}}class jn{constructor(e){this.stats=e,this.uneeqMessageType=wn.WebRtcStats}}class Bn{constructor(e){this.error=e,this.uneeqMessageType=wn.SessionError}}class zn{constructor(e){this.error=e,this.uneeqMessageType=wn.SessionBackendError}}class Vn{constructor(e){this.speechEvent=e,this.uneeqMessageType=wn.SpeechEvent}}class Gn{constructor(e){this.reason=e,this.uneeqMessageType=wn.SessionEnded}}class Hn{constructor(){this.uneeqMessageType=wn.DigitalHumanPlayedInMutedModeSuccess,this.msg="Digital Human was successfully played in muted mode. After the user interacts with the page you will need to call unmuteDigitalHuman() to unmute the video."}}class Wn{constructor(){this.uneeqMessageType=wn.DigitalHumanUnmuted}}class qn{constructor(){this.uneeqMessageType=wn.DigitalHumanMuted}}class Kn{constructor(e){this.enabled=e,this.uneeqMessageType=wn.EnableMicrophoneUpdated}}class Xn{constructor(e){this.chatMetadata=e,this.uneeqMessageType=wn.CustomMetadataUpdated}}class Jn{constructor(e){this.promptRequest=e,this.uneeqMessageType=wn.PromptRequest}}class Qn{constructor(e){this.promptResult=e,this.uneeqMessageType=wn.PromptResult}}class Yn{constructor(){this.uneeqMessageType=wn.SceneReady}}class Zn{constructor(e){this.rendererId=e,this.uneeqMessageType=wn.SessionConnecting}}class er{constructor(){this.uneeqMessageType=wn.SessionDisconnected}}class tr{constructor(){this.uneeqMessageType=wn.SessionReconnecting}}class nr{constructor(){this.uneeqMessageType=wn.SessionReconnectingFinished}}class rr{constructor(){this.uneeqMessageType=wn.SoftSwitchStarting}}class ir{constructor(){this.uneeqMessageType=wn.SoftSwitchFinished}}class or{constructor(){this.uneeqMessageType=wn.VideoLayoutConfiguring}}!function(e){e.CameraAnchor="camera_to_anchor",e.ChatPrompt="chat_prompt",e.InterimTranscript="interim_transcript",e.StopSpeaking="stop_speaking",e.Speak="speak",e.SpeechStream="speech_stream",e.UserSpeaking="user_speaking"}(Sn||(Sn={}));const sr="sessionEndedDueToConnectionLoss",ar="sessionEndedDueToVideoPlaybackError";var ur;class lr{constructor(e,t,n){this.stream=e,this.videoElement=t,this.audioElement=n}analyzeAudioStats(){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){const e=this.stream._webRtcController.peerConnectionController.peerConnection;if(!e)return void r.error("Stream appears to be down, RTCPeerConnection is not defined");const t=yield e.getStats(null),n=this.getInboundAudioStats(t);if(!n)return void r.warn("WebRTC Connection - No inbound audio RTP stats found.");const i=n.codecId,o=this.getCodecFromStats(t,i);this.logAudioStats(n,o),this.logElementStatus(o)}))}getInboundAudioStats(e){let t=null;return e.forEach((e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&(t=e)})),t}getCodecFromStats(e,t){let n;return e.forEach((e=>{"codec"===e.type&&e.id===t&&(n=e)})),n}logAudioStats(e,t){const{packetsReceived:n,packetsLost:i,bytesReceived:o,jitter:s,audioLevel:a}=e;r.info(`WebRTC Connection - Audio - \n Codec: ${t?t.mimeType+" ("+t.payloadType+")":"Unknown"}, \n Packets received: ${n},\n Packets lost: ${i}, \n Bytes received: ${o}, \n Jitter: ${s},\n Audio level (0-1): ${null!=a?a:"N/A"}`),0===n&&r.warn("WebRTC Connection - Audio - No audio packets received — remote is probably not sending audio."),i>0&&r.warn(`WebRTC Connection - Audio - packet loss detected: ${i} packets lost.`),void 0===a?r.warn("WebRTC Connection - Audio - Audio level not available in stats."):0===a?r.warn("WebRTC Connection - Audio - Audio level is zero — digital human might not be talking at this exact moment as audio is silent or muted."):a<.02?r.warn("WebRTC Connection - Audio - Audio level is very low — audio might be too quiet."):r.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){var t,n,i;r.debug(`Video element muted: ${null===(t=this.videoElement)||void 0===t?void 0:t.muted}, (should be true as part of avoiding auto play restrictions)`),r.debug(`Audio element muted: ${null===(n=this.audioElement)||void 0===n?void 0:n.muted}, (should be false to be able to hear the digital human)`),r.debug(`Audio element volume: ${null===(i=this.audioElement)||void 0===i?void 0:i.volume}, (should be greater than zero to be able to hear the digital human)`);const o=null==e?void 0:e.mimeType;o&&this.audioElement&&(r.debug(`Audio element can play webrtc audio codec (${o}) : ${this.audioElement.canPlayType(o)}, (should be 'probably' or 'maybe)'`),"audio/opus"===o&&r.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${this.audioElement.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}}class cr{constructor(e,t,n){this.session=e,this.connectionUrl=t,this.videoContainerElement=n,this.messages=new q,this.videoInitialized=!1,this.dataChannelOpen=!1,this.sceneReady=!1,this.maxReconnectAttempts=3,this.reconnectionAttempts=0,this.allowReconnection=!0,this.isReconnectInProgress=!1,this.freezeCount=0,this.lastDecodedFrames=0,this.lastCheckTime=Date.now(),this.config=e.config,this.clientMessages=e.messages}init(){var e;r.info("Connection config",{connectionUrl:this.connectionUrl,forceTURN:this.config.forceTURN}),this.videoContainerElement||(this.videoContainerElement=document.createElement("div"),document.body.appendChild(this.videoContainerElement)),null===(e=this.clientMessages)||void 0===e||e.next(new or);const t=new _n({initialSettings:{AutoConnect:!1,AutoPlayVideo:!1,ForceTURN:this.config.forceTURN,HoveringMouse:!1,KeyboardInput:!1,MaxReconnectAttempts:3,MouseInput:!1,OfferToReceive:!1,ss:this.connectionUrl,StartVideoMuted:!0,TouchInput:!1,WaitForStreamer:!0}});this.stream=new xn(t,{videoElementParent:this.videoContainerElement}),this.stream.setSignallingUrlBuilder((function(){let e=t.getTextSettingValue(En.SignallingServerUrl);return t.isFlagEnabled(Tn.BrowserSendOffer)&&(e+=(e.includes("?")?"&":"?")+Tn.BrowserSendOffer+"=true"),e})),this.addStreamHandlers(),this.stream.connect(),this.addWebSocketHandlers()}addStreamHandlers(){var e,t,n,i,o,s,a,u,l,c,d;null===(e=this.stream)||void 0===e||e.addEventListener("videoInitialized",this.handleVideoInitialized.bind(this)),null===(t=this.stream)||void 0===t||t.addEventListener("dataChannelOpen",this.handleDataChannelOpen.bind(this)),null===(n=this.stream)||void 0===n||n.addEventListener("webRtcFailed",this.handleWebRtcFailed.bind(this)),null===(i=this.stream)||void 0===i||i.addEventListener("webRtcDisconnected",this.handleWebRtcDisconnected.bind(this)),null===(o=this.stream)||void 0===o||o.addEventListener("statsReceived",this.handleWebRtcStats.bind(this)),null===(s=this.stream)||void 0===s||s.addResponseEventListener("response-listener",this.handleDataChannelMessage.bind(this)),null===(a=this.stream)||void 0===a||a.addEventListener("videoEncoderAvgQP",(({data:{avgQP:e}})=>{r.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)})),null===(u=this.stream)||void 0===u||u.addEventListener("webRtcAutoConnect",(()=>{r.debug("WebRTC: AutoConnect triggered")})),null===(l=this.stream)||void 0===l||l.addEventListener("webRtcConnected",(()=>{r.debug("WebRTC: connected")})),null===(c=this.stream)||void 0===c||c.addEventListener("statsReceived",(({data:{aggregatedStats:e}})=>{r.trace("WebRTC: StatsReceived",e)})),null===(d=this.stream)||void 0===d||d.addEventListener("webRtcTCPRelayDetected",(()=>{r.warn("WebRTC: Stream quailty likely degraded due to network enviroment, stream is relayed over TCP.")}))}addWebSocketHandlers(){var e,t,n,r,i;null===(e=this.stream)||void 0===e||e.webSocketController.webSocket.addEventListener("error",this.handleWebSocketError.bind(this)),null===(t=this.stream)||void 0===t||t.webSocketController.signallingProtocol.addMessageHandler(vn.IndexInQueue,this.handleIndexInQueueMessage.bind(this)),null===(n=this.stream)||void 0===n||n.webSocketController.signallingProtocol.addMessageHandler(vn.RendererTaken,this.handleRendererTakenMessage.bind(this)),null===(r=this.stream)||void 0===r||r.webSocketController.signallingProtocol.addMessageHandler(vn.RendererGone,this.handleRendererGoneEvent.bind(this)),null===(i=this.stream)||void 0===i||i.webSocketController.signallingProtocol.addMessageHandler(vn.SwitchRendererRequest,this.handleSwitchRendererRequestEvent.bind(this))}handleWebSocketError(e){r.error("Signaling: WebSocket error",r.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){var e,t,n,i,o;if(r.info("Video initialized."),this.videoElement=null===(e=this.videoContainerElement)||void 0===e?void 0:e.getElementsByTagName("video")[0],this.audioElement=null===(i=null===(n=null===(t=this.stream)||void 0===t?void 0:t._webRtcController)||void 0===n?void 0:n.streamController)||void 0===i?void 0:i.audioElement,this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then((()=>{this.playAudioElement()})).catch((e=>{var t,n;if(e instanceof DOMException&&"NotAllowedError"===e.name)r.error('Fatal Error: Video cannot be played. User interaction or client permissions update is required to be able to "play" the video element.',e),null===(t=this.clientMessages)||void 0===t||t.next(new kn(e)),this.endSession("sessionEndedDueToPermissionsError",!0);else{const t="Fatal Error: Digital Human video cannot be played.";r.error(t,r.serialiseError(e)),null===(n=this.clientMessages)||void 0===n||n.next(new Bn(t)),this.endSession(ar,!0)}})),this.videoInitialized=!0,this.messages.next(new Cn),this.reconnectionAttempts=0;else{const e="Fatal Error: Video element not found.";r.error(e),null===(o=this.clientMessages)||void 0===o||o.next(new Bn(e)),this.endSession(ar,!0)}this.isReconnectInProgress=!1,setTimeout((()=>{var e;null===(e=this.clientMessages)||void 0===e||e.next(new nr)}),to)}playAudioElement(){this.audioElement?this.audioElement.play().then((()=>{var e;r.info("Audio played successfully."),null===(e=this.clientMessages)||void 0===e||e.next(new Wn)})).catch((e=>{var t,n;r.warn("Audio cannot be played.",e),null===(t=this.clientMessages)||void 0===t||t.next(new qn),null===(n=this.clientMessages)||void 0===n||n.next(new Hn)})):this.handleMissingAudioElement()}pauseAudioElement(){var e;this.audioElement?(this.audioElement.pause(),null===(e=this.clientMessages)||void 0===e||e.next(new qn)):this.handleMissingAudioElement()}handleMissingAudioElement(){var e;const t="Error: Digital Human audio element not found, cannot play audio.";r.error(t),null===(e=this.clientMessages)||void 0===e||e.next(new Bn(t))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),r.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new lr(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval((()=>{var e;null===(e=this.audioStatsAnalyzer)||void 0===e||e.analyzeAudioStats().catch((e=>{r.error("Error analyzing audio stats",r.serialiseError(e))}))}),e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}handleDataChannelOpen(){r.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new Pn)}handleWebRtcFailed(e){r.error("WebRTC failed",e),this.reconnectIfSafe(e)}handleWebRtcDisconnected(e){var t,n;r.warn(`WebRTC disconnected, message: ${null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.eventString}, allowClickToReconnect: ${null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.allowClickToReconnect}`),this.reconnectIfSafe(e)}handleWebRtcStats(e){var t,n;const r=new An(e.data.aggregatedStats);this.messages.next(r);const i=null!==(n=null===(t=e.data.aggregatedStats.inboundVideoStats)||void 0===t?void 0:t.framesDecoded)&&void 0!==n?n:0;this.checkForFreeze(i)}checkForFreeze(e){const t=Date.now();if(0!==this.lastDecodedFrames||0!==e)if(e===this.lastDecodedFrames){this.freezeCount++;const e=((t-this.lastCheckTime)/1e3).toFixed(1);r.warn(`[WebRTC] Video FROZEN for ${e}s (count=${this.freezeCount})`),this.freezeCount>=3&&(r.error("[WebRTC] Video frozen 3 times in a row, transferring session..."),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t;else r.debug("[WebRTC] Waiting for first video frame...")}reconnectIfSafe(e){var t,n,i,o;try{this.allowReconnection&&!this.isReconnectInProgress?(this.isReconnectInProgress=!0,r.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,r.info("Attempting to reconnect to signaling server. Attempt "+this.reconnectionAttempts),null===(t=this.stream)||void 0===t||t.reconnect(),null===(n=this.clientMessages)||void 0===n||n.next(new tr)):(r.info("Max reconnection attempts reached. Ending session."),null===(i=this.clientMessages)||void 0===i||i.next(new er),this.isReconnectInProgress=!1,this.endSession(sr,!1))):r.warn("Reconnection attempt already in progress or reconnecting is disabled")}catch(e){r.error("Error during reconnection attempt",r.serialiseError(e)),null===(o=this.clientMessages)||void 0===o||o.next(new Bn("Error during reconnection attempt")),this.isReconnectInProgress=!1,this.endSession(sr,!1)}}handleDataChannelMessage(e){r.trace("Signaling: Received data channel message",e);try{const t=JSON.parse(e);if(void 0===t.type)throw new Error("Signaling: Engine response missing type");this.messages.next(new On(t))}catch(e){r.error("Signaling: Failed to parse engine response",r.serialiseError(e))}}handleIndexInQueueMessage(e){var t;try{const n=JSON.parse(e),r=Number(n.message);null===(t=this.clientMessages)||void 0===t||t.next(new Nn(r))}catch(e){r.error("Signaling: Failed to parse position in queue message",r.serialiseError(e))}}handleRendererTakenMessage(e){var t;try{const n=JSON.parse(e);null===(t=this.clientMessages)||void 0===t||t.next(new Zn(n.message)),r.info("Signaling: Renderer taken event",n.message)}catch(e){r.error("Signaling: Failed to parse renderer taken message",r.serialiseError(e))}}handleRendererGoneEvent(e){r.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e)}handleSwitchRendererRequestEvent(e){r.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession()}socketSend(e){var t,n;r.trace("Signaling: Sending socket message",e),null===(n=null===(t=this.stream)||void 0===t?void 0:t.webSocketController)||void 0===n||n.webSocket.send(JSON.stringify(e))}dataSend(e){var t,n;const i=e.toJSON();r.info("Signaling: Sending data channel message",JSON.stringify(i)),i.action===Sn.ChatPrompt&&(null===(t=this.clientMessages)||void 0===t||t.next(new Jn(i.data))),null===(n=this.stream)||void 0===n||n.emitUIInteraction(e)}dataSendBinary(e){var t;r.info("Signaling: Sending data channel binary message");const n=this.uint8ToBase64(e);null===(t=this.stream)||void 0===t||t.emitUIInteraction(n)}uint8ToBase64(e){let t="";const n=e.byteLength;for(let r=0;r<n;r++)t+=String.fromCharCode(e[r]);return btoa(t)}endSession(e="sessionEndedByUser",t=!0){var n,i;r.info("Signaling: Ending session"),this.allowReconnection=!1,this.socketSend({message:e,type:vn.ClientGone,sessionId:this.config.sessionId}),null===(n=this.stream)||void 0===n||n.disconnect(),r.info("Session has ended, reason: "+e),t&&(null===(i=this.clientMessages)||void 0===i||i.next(new Gn(e)))}streamDisconnect(){var e;r.info("Signaling: Disconnecting stream"),this.allowReconnection=!1,null===(e=this.stream)||void 0===e||e.disconnect()}startSoftSwitch(){var e;r.info("Signaling: Start soft switching"),null===(e=this.clientMessages)||void 0===e||e.next(new rr)}stopSoftSwitch(){var e;r.info("Signaling: Stop soft switching"),null===(e=this.clientMessages)||void 0===e||e.next(new ir)}}!function(e){e.Google="google",e.Deepgram="deepgram"}(ur||(ur={}));var dr,hr=__webpack_require__(955),pr=__webpack_require__(603);!function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END"}(dr||(dr={}));const fr=[512,1024,1536];function gr(e){fr.includes(e.frameSamples)||r.warn("You are using an unusual frame size"),(e.positiveSpeechThreshold<0||e.negativeSpeechThreshold>1)&&r.error("postiveSpeechThreshold should be a number between 0 and 1"),(e.negativeSpeechThreshold<0||e.negativeSpeechThreshold>e.positiveSpeechThreshold)&&r.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),e.preSpeechPadFrames<0&&r.error("preSpeechPadFrames should be positive"),e.redemptionFrames<0&&r.error("preSpeechPadFrames should be positive")}const mr=e=>{const t=e.reduce(((e,t)=>(e.push(e[e.length-1]+t.length),e)),[0]),n=new Float32Array(t[t.length-1]);return e.forEach(((e,r)=>{const i=t[r];n.set(e,i)})),n};class br{constructor(e,t,n){this.modelProcessFunc=e,this.modelResetFunc=t,this.options=n,this.speaking=!1,this.redemptionCounter=0,this.active=!1,this.reset=()=>{this.speaking=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0},this.pause=()=>{this.active=!1,this.reset()},this.resume=()=>{this.active=!0},this.endSegment=()=>{const e=this.audioBuffer;this.audioBuffer=[];const t=this.speaking;this.reset();const n=e.reduce(((e,t)=>e+ +t.isSpeech),0);if(t){if(n>=this.options.minSpeechFrames){const t=mr(e.map((e=>e.frame)));return{msg:dr.SpeechEnd,audio:t}}return{msg:dr.VADMisfire}}return{}},this.process=e=>function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(!this.active)return{};const t=yield this.modelProcessFunc(e);if(this.audioBuffer.push({frame:e,isSpeech:t.isSpeech>=this.options.positiveSpeechThreshold}),t.isSpeech>=this.options.positiveSpeechThreshold&&this.redemptionCounter&&(this.redemptionCounter=0),t.isSpeech>=this.options.positiveSpeechThreshold&&!this.speaking)return this.speaking=!0,{probs:t,msg:dr.SpeechStart};if(t.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.options.redemptionFrames){this.redemptionCounter=0,this.speaking=!1;const e=this.audioBuffer;if(this.audioBuffer=[],e.reduce(((e,t)=>e+ +t.isSpeech),0)>=this.options.minSpeechFrames){const n=mr(e.map((e=>e.frame)));return{probs:t,msg:dr.SpeechEnd,audio:n}}return{probs:t,msg:dr.VADMisfire}}if(!this.speaking)for(;this.audioBuffer.length>this.options.preSpeechPadFrames;)this.audioBuffer.shift();return{probs:t}})),this.audioBuffer=[],this.reset()}}var yr,vr=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class wr{constructor(e,t){this.ort=e,this.modelFetcher=t,this.init=()=>vr(this,void 0,void 0,(function*(){r.debug("[VAD] initializing");const e=yield this.modelFetcher();this._session=yield this.ort.InferenceSession.create(e),this._sr=new this.ort.Tensor("int64",[BigInt(16e3)]),this.reset_state(),r.debug("[VAD] is initialized")})),this.reset_state=()=>{const e=Array(128).fill(0);this._h=new this.ort.Tensor("float32",e,[2,1,64]),this._c=new this.ort.Tensor("float32",e,[2,1,64])},this.process=e=>vr(this,void 0,void 0,(function*(){const t={input:new this.ort.Tensor("float32",e,[1,e.length]),h:this._h,c:this._c,sr:this._sr},n=yield this._session.run(t);this._h=n.hn,this._c=n.cn;const[r]=n.output.data;return{notSpeech:1-r,isSpeech:r}}))}}yr=wr,wr.new=(e,t)=>vr(void 0,void 0,void 0,(function*(){const n=new yr(e,t);return yield n.init(),n}));var Sr=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const _r=Object.assign(Object.assign({},{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,preSpeechPadFrames:1,redemptionFrames:8,frameSamples:1536,minSpeechFrames:3}),{onFrameProcessed:e=>{},onVADMisfire:()=>{r.debug("VAD misfire")},onSpeechStart:()=>{r.debug("Detected speech start")},onSpeechEnd:()=>{r.debug("Detected speech end")},stream:new MediaStream,assetBasePath:""});class Tr{static new(){return Sr(this,arguments,void 0,(function*(e={}){const t=new Tr(Object.assign(Object.assign({},_r),e));return yield t.init(),t}))}constructor(e){this.options=e,this.listening=!1,this.init=()=>Sr(this,void 0,void 0,(function*(){r.info("Initializing real time vad."),void 0===this.options.stream?this.stream=yield navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}):this.stream=this.options.stream,this.audioContext=new AudioContext;const e=new MediaStreamAudioSourceNode(this.audioContext,{mediaStream:this.stream});this.audioNodeVAD=yield xr.new(this.audioContext,this.options),this.audioNodeVAD.receive(e)})),this.pause=()=>{this.audioNodeVAD.pause(),this.listening=!1},this.start=()=>{this.audioNodeVAD.start(),this.listening=!0},gr(e)}}class xr{static new(e){return Sr(this,arguments,void 0,(function*(e,t={}){const n=new xr(e,Object.assign(Object.assign({},_r),t));return yield n.init(),n}))}constructor(e,t){this.ctx=e,this.options=t,this.pause=()=>{this.frameProcessor.pause()},this.start=()=>{this.frameProcessor.resume()},this.receive=e=>{e.connect(this.entryNode)},this.processFrame=e=>Sr(this,void 0,void 0,(function*(){const{probs:t,msg:n,audio:r}=yield this.frameProcessor.process(e);switch(void 0!==t&&this.options.onFrameProcessed(t),n){case dr.SpeechStart:this.options.onSpeechStart();break;case dr.VADMisfire:this.options.onVADMisfire();break;case dr.SpeechEnd:this.options.onSpeechEnd(r)}})),this.init=()=>Sr(this,void 0,void 0,(function*(){yield this.ctx.audioWorklet.addModule(this.options.assetBasePath+"vad.worklet.bundle.min.js");const e=new AudioWorkletNode(this.ctx,"vad-helper-worklet",{processorOptions:{frameSamples:this.options.frameSamples}});this.entryNode=e,pr.env.wasm.wasmPaths=this.options.assetBasePath;const t=yield wr.new(pr,this.modelFetcher);this.frameProcessor=new br(t.process,t.reset_state,{frameSamples:this.options.frameSamples,positiveSpeechThreshold:this.options.positiveSpeechThreshold,negativeSpeechThreshold:this.options.negativeSpeechThreshold,redemptionFrames:this.options.redemptionFrames,preSpeechPadFrames:this.options.preSpeechPadFrames,minSpeechFrames:this.options.minSpeechFrames}),e.port.onmessage=e=>Sr(this,void 0,void 0,(function*(){var t;if((null===(t=e.data)||void 0===t?void 0:t.message)===dr.AudioFrame){const t=e.data.data,n=new Float32Array(t);yield this.processFrame(n)}}))})),this.modelFetcher=()=>Sr(this,void 0,void 0,(function*(){const e=this.options.assetBasePath+"silero_vad.onnx";return yield fetch(e).then((e=>e.arrayBuffer()))})),gr(t)}}var Er;!function(e){e.startTranscription="startTranscription",e.stopTranscription="stopTranscription"}(Er||(Er={}));const Cr={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Pr;const Or=new Uint8Array(16),Ar=[];for(let e=0;e<256;++e)Ar.push((e+256).toString(16).slice(1));const kr=function(e,t,n){if(Cr.randomUUID&&!t&&!e)return Cr.randomUUID();const r=(e=e||{}).random??e.rng?.()??function(){if(!Pr){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pr=crypto.getRandomValues.bind(crypto)}return Pr(Or)}();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return function(e,t=0){return(Ar[e[t+0]]+Ar[e[t+1]]+Ar[e[t+2]]+Ar[e[t+3]]+"-"+Ar[e[t+4]]+Ar[e[t+5]]+"-"+Ar[e[t+6]]+Ar[e[t+7]]+"-"+Ar[e[t+8]]+Ar[e[t+9]]+"-"+Ar[e[t+10]]+Ar[e[t+11]]+Ar[e[t+12]]+Ar[e[t+13]]+Ar[e[t+14]]+Ar[e[t+15]]).toLowerCase()}(r)};class Ir{constructor(e=kr()){this.requestId=e}toJSON(){return{action:Sn.StopSpeaking,data:{requestId:this.requestId}}}}class Mr{constructor(e,t,n=kr()){this.prompt=e,this.metadata=t,this.requestId=n}toJSON(){return{action:Sn.ChatPrompt,data:{requestId:this.requestId,prompt:this.prompt,metadata:this.metadata}}}}var Rr;!function(e){e.Start="start",e.Stop="stop"}(Rr||(Rr={}));class Dr{constructor(e,t=kr()){this.state=e,this.requestId=t}toJSON(){return{action:Sn.UserSpeaking,data:{requestId:this.requestId,event:this.state}}}}class $r{constructor(e,t,n,r,i,o=kr()){this.transcript=e,this.stability=t,this.confidence=n,this.languageCode=r,this.isFinal=i,this.requestId=o}toJSON(){return{action:Sn.InterimTranscript,data:{requestId:this.requestId,transcript:this.transcript,stability:this.stability,confidence:this.confidence,languageCode:this.languageCode,isFinal:this.isFinal}}}}var Lr=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const Fr=48e3;class Ur{constructor(e){var t,n,r;this.options=e,this.speechBuffer=new hr.RingBuffer(5),this.recordingLive=!1,this.reconnectWs=!0,this.wsReconnectMessageQueue=[],this.awaitingFinalTranscript=!1,this.digitalHumanSpeaking=!1,this.interruptionBlocked=!1,this.options.assetBasePath=null!==(t=this.options.assetBasePath)&&void 0!==t?t:"https://cdn.uneeq.io/assets/platform/speech-recognition/",this.options.enableVad=null===(n=this.options.enableVad)||void 0===n||n,this.options.enableInterrupt=null!==(r=this.options.enableInterrupt)&&void 0!==r&&r,this.loadSavedAudioHeaders(),this.loadScripts(),this.handleAppMessages()}startRecognition(){this.initWebsocket(this.options)}stopRecognition(){this.mediaRecorder&&"recording"===this.mediaRecorder.state&&this.mediaRecorder.stop(),this.stream&&(this.stream.getTracks().forEach((e=>{e.stop()})),this.stream=void 0,this.clientMsgSend(new Kn(!1))),this.pauseMicVad()}pause(){var e;return this.stream&&this.micVad||r.warn(`[Speech Recognition] Problem pausing speech recognition, stream live: ${void 0!==this.stream} or microphone voice detection live: ${void 0!==this.micVad}.`),this.sendStoredTranscriptionIfReady(),null===(e=this.stream)||void 0===e||e.getTracks().forEach((e=>{e.enabled=!1})),this.pauseMicVad(),this.onVadSpeechEnd(),r.info("[Speech Recognition] paused"),!0}resume(){if(this.interruptionBlocked&&(this.digitalHumanSpeaking=!1,this.interruptionBlocked=!1,this.clientMsgSend(new Rn(!0))),!this.options.enableVad&&this.digitalHumanSpeaking&&(this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1),this.storedTranscription=void 0,this.stream&&this.micVad){this.stream.getTracks().forEach((e=>{e.enabled=!0}));const e=this.startMicVad();return r.info("[Speech Recognition] resumed: "+e),e}return r.warn(`[Speech Recognition] Could not resume speech recognition, stream live: ${void 0!==this.stream} or microphone voice detection live: ${void 0!==this.micVad}.`),!1}setChatMetadata(e){this.options.promptMetadata=e}pauseVadIfInterruptNotAllowed(){this.micVad&&!this.options.enableInterrupt&&(this.micVad.pause(),this.clientMsgSend(new Rn(!1))),this.options.enableInterrupt||(this.interruptionBlocked=!0)}loadScript(e){return Lr(this,void 0,void 0,(function*(){return yield new Promise((t=>{const n=document.createElement("script");n.src=e,n.onload=()=>{t(null)},document.body.appendChild(n)}))}))}loadScripts(){this.scriptsLoadedPromise=new Promise((e=>{this.loadScript(this.options.assetBasePath+"OpusMediaRecorder.umd.js").then((()=>{this.loadScript(this.options.assetBasePath+"encoderWorker.umd.js").then((()=>{e(null)})).catch((e=>{r.error("Error loading encoderWorker.umd.js",r.serialiseError(e))}))})).catch((e=>{r.error("Error loading OpusMediaRecorder.umd.js",r.serialiseError(e))}))}))}handleAppMessages(){this.options.messages.subscribe((e=>{switch(e.uneeqMessageType){case wn.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0,this.pauseVadIfInterruptNotAllowed();break;case wn.PromptResult:e.promptResult.success||this.handleSpeakingEnd();break;case wn.AvatarAnswer:""===e.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case wn.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case wn.SessionEnded:this.reconnectWs=!1,this.endRecognition();break;case wn.SessionReconnecting:this.handleSpeakingEnd(),this.reconnectWs=!1,this.endRecognition();break;case wn.CustomMetadataUpdated:this.options.promptMetadata=e.chatMetadata;break;case wn.SessionBackendError:this.handleSpeakingEnd()}}))}endRecognition(){this.stopRecognition(),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close()}handleSpeakingEnd(){this.digitalHumanSpeaking=!1,this.interruptionBlocked=!1,this.startMicVad(),this.options.enableInterrupt||this.clientMsgSend(new Rn(!0))}initWebsocket(e){this.endRecognition();let t=e.apiUrl.replace("https://","wss://").replace("http://","ws://");t+=`/speech-recognition-service/ws/recognize?jwt=${e.jwtToken}&session_id=${e.sessionId}`,r.info("[Speech Recognition] Initializing speech recognition websocket to "+t),this.ws=new WebSocket(t),this.ws.onopen=()=>{r.info("[Speech Recognition] Speech recognition web socket opened"),this.sendWebsocketMessageQueue(),this.initMicrophone()},this.ws.onclose=e=>{this.handleWebsocketClose(e)},this.ws.onerror=e=>{r.error("WebSocket error",r.serialiseError(e))},this.ws.onmessage=e=>{this.handleWebsocketMessage(e)}}sendWebsocketMessageQueue(){r.info("[Speech Recognition] Sending all queued websocket messages, queue length: "+this.wsReconnectMessageQueue.length),this.wsReconnectMessageQueue.forEach((e=>{this.wsSend(e,!1,!1)})),this.wsReconnectMessageQueue=[]}loadSavedAudioHeaders(){return Lr(this,void 0,void 0,(function*(){const e=this.options.assetBasePath+"opus-media-recorder-header.webm",t=yield fetch(e),n=yield t.arrayBuffer();this.headerBlob=new Blob([n],{type:"audio/webm;codecs=opus"})}))}initVoiceActivityDetection(e){r.info("[VAD] Going to initialize VAD module, with enableVad = "+this.options.enableVad),Tr.new({onSpeechStart:()=>{this.onVadSpeechStart()},onSpeechEnd:()=>{this.onVadSpeechEnd()},minSpeechFrames:1,positiveSpeechThreshold:this.options.enableVad?.5:0,negativeSpeechThreshold:this.options.enableVad?.35:0,redemptionFrames:8,assetBasePath:this.options.assetBasePath,stream:e}).then((e=>{this.micVad=e,this.interruptionBlocked?this.clientMsgSend(new Rn(!1)):this.startMicVad(),r.info("[VAD] module has started")})).catch((e=>{r.error("[VAD] could not start module",r.serialiseError(e))}))}startMicVad(){return!this.micVad||!this.options.enableInterrupt&&this.digitalHumanSpeaking?(r.info(`[VAD] VAD has not been started, microphone voice detection live: ${void 0!==this.micVad}, enableInterrupt: ${this.options.enableInterrupt}, isDigitalHumanSpeaking: ${this.digitalHumanSpeaking}.`),!1):(this.micVad.start(),r.info("[VAD] VAD has been started / unpaused"),!0)}pauseMicVad(){return this.micVad?(this.micVad.pause(),r.info("[VAD] has been paused"),!0):(r.info("[VAD] has not been initialized so has not been paused "),!1)}onVadSpeechStart(){r.info("[VAD] User started speaking"),this.dataChannelMsgSend(new Dr(Rr.Start)),this.clientMsgSend(new Dn),this.sendStartMessage(),this.wsSend(this.headerBlob),r.info("[VAD] Sending buffered speech audio");const e=new Blob(this.speechBuffer.toArray(),{type:"audio/webm;codecs=opus"});this.wsSend(e),this.recordingLive=!0,this.speechBuffer.clear()}onVadSpeechEnd(){r.info("[VAD] User has stopped speaking or intentionally ending current VAD"),this.dataChannelMsgSend(new Dr(Rr.Stop)),this.clientMsgSend(new $n),this.recordingLive=!1,this.sendStopMessage()}sendStoredTranscriptionIfReady(){this.options.enableVad||void 0===this.storedTranscription||this.awaitingFinalTranscript||(this.sendChatPrompt(this.storedTranscription.transcript),this.clientMsgSend(new Mn(this.storedTranscription)),this.storedTranscription=void 0)}handleWebsocketMessage(e){r.debug("[Speech Recognition] Got a websocket message: ",e);try{if("string"==typeof e.data){const t=JSON.parse(e.data),n=t.results?t.results[0]:null;"response"===t.state&&n&&(r.info(`[Speech Recognition] Speech transcription result ${JSON.stringify(n)}`),this.options.enableVad?this.handleVadTranscriptionResult(n):this.handlePttTranscriptionResult(n))}}catch(e){r.error("[Speech Recognition] Error processing message speech recognition socket message",r.serialiseError(e))}}handleWebsocketClose(e){r.warn("[Speech Recognition] WebSocket closed",e),this.reconnectWs&&this.initWebsocket(this.options)}sendStartMessage(){var e,t;const n={action:Er.startTranscription,channels:1,sampleRate:Fr,interimResults:!0,lang:this.options.locales||"en-US",phrases:null!==(e=this.options.hintPhrases)&&void 0!==e?e:"",phraseBoost:null!==(t=this.options.hintPhrasesBoost)&&void 0!==t?t:0};this.wsSend(JSON.stringify(n))}sendStopMessage(){const e={action:Er.stopTranscription};this.wsSend(JSON.stringify(e),!0)}wsSend(e,t=!1,n=!0){this.ws.readyState===WebSocket.OPEN&&this.ws.send(e),this.reconnectWs&&n&&(this.wsReconnectMessageQueue.push(e),t&&this.ws.readyState===WebSocket.OPEN&&(this.wsReconnectMessageQueue=[]),this.wsReconnectMessageQueue.length>3e3&&this.handleWsReconnectQueueOverflow())}handleWsReconnectQueueOverflow(){r.warn("[Speech Recognition] The websocket reconnection queue has exceeded maximum length of 3000. The audio reconnection queue will be reset, speech transcription performance may be impacted in the event of a reconnection."),this.wsReconnectMessageQueue=[]}initMicrophone(){this.stream?r.warn("[Microphone] Microphone already initialized, stream already exists, skipping initialization."):navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,sampleRate:Fr,channelCount:1}}).then((e=>{this.stream=e,this.initVoiceActivityDetection(e),this.initMediaRecorder(e),this.clientMsgSend(new Kn(!0))})).catch((e=>{r.error("[Microphone] Error starting recording",r.serialiseError(e)),this.clientMsgSend(new kn(new Error(JSON.stringify(e))))}))}getMediaRecorder(e,t,n){return new window.OpusMediaRecorder(e,t,n)}initMediaRecorder(e){const t={OggOpusEncoderWasmPath:this.options.assetBasePath+"OggOpusEncoder.wasm",WebMOpusEncoderWasmPath:this.options.assetBasePath+"WebMOpusEncoder.wasm"},n={mimeType:"audio/webm",audioBitsPerSecond:Fr};this.scriptsLoadedPromise.then((()=>{this.mediaRecorder=this.getMediaRecorder(e,n,t),this.mediaRecorder.ondataavailable=e=>{this.mediaRecorderOnData(e)},this.mediaRecorder.onstop=()=>{this.sendStopMessage()},this.mediaRecorder.start(100)})).catch((e=>{r.error("[Microphone] Error initializing media recorder",r.serialiseError(e))}))}mediaRecorderOnData(e){e.data&&e.data.size>0&&(this.recordingLive?this.wsSend(e.data):this.speechBuffer.add(e.data))}handlePttTranscriptionResult(e){var t;this.awaitingFinalTranscript=!e.final;try{this.recordingLive?e.final?void 0===this.storedTranscription?this.storedTranscription=e:this.storedTranscription.transcript+=e.transcript:this.digitalHumanSpeaking&&(this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1):e.final&&(void 0!==this.storedTranscription&&(e.transcript=this.storedTranscription.transcript+e.transcript),this.options.promptMetadata.userSpokenLocale=e.language_code,this.sendChatPrompt(e.transcript),this.sendInterimTranscription(e),this.clientMsgSend(new Mn(e)),this.storedTranscription=void 0),(null!==(t=e.stability)&&void 0!==t?t:1)>.5&&!e.final&&(void 0!==this.storedTranscription&&(e.transcript=this.storedTranscription.transcript+e.transcript),this.clientMsgSend(new Mn(e)),this.sendInterimTranscription(e))}catch(e){this.clientMsgSend(new Bn("Error processing speech transcription result")),this.storedTranscription=void 0}}handleVadTranscriptionResult(e){var t;""!==e.transcript&&(e.final?(this.options.promptMetadata.userSpokenLocale=e.language_code,this.sendChatPrompt(e.transcript)):this.digitalHumanSpeaking&&(this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1),this.sendInterimTranscription(e)),((null!==(t=e.stability)&&void 0!==t?t:1)>.5||e.final)&&this.clientMsgSend(new Mn(e))}sendChatPrompt(e){e&&""!==e.trim()&&(this.pauseVadIfInterruptNotAllowed(),this.dataChannelMsgSend(new Mr(e,this.options.promptMetadata)))}sendInterimTranscription(e){var t;if(e.transcript&&""!==e.transcript.trim()){const n=null!==(t=e.stability)&&void 0!==t?t:1;this.dataChannelMsgSend(new $r(e.transcript,n,e.confidence,e.language_code,e.final))}}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}}class Nr extends Error{constructor(e){super(e),this.__dgError=!0,this.name="DeepgramError"}}function jr(e){return"object"==typeof e&&null!==e&&"__dgError"in e}class Br extends Nr{constructor(e,t){super(e),this.name="DeepgramApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class zr extends Nr{constructor(e,t){super(e),this.name="DeepgramUnknownError",this.originalError=t}}class Vr extends Nr{constructor(){super("You are attempting to use an old format for a newer SDK version. Read more here: https://dpgr.am/js-v3"),this.name="DeepgramVersionError"}}class Gr extends Nr{constructor(e,t={}){super(e),this.name="DeepgramWebSocketError",this.originalEvent=t.originalEvent,this.statusCode=t.statusCode,this.requestId=t.requestId,this.responseHeaders=t.responseHeaders,this.url=t.url,this.readyState=t.readyState}toJSON(){return{name:this.name,message:this.message,statusCode:this.statusCode,requestId:this.requestId,responseHeaders:this.responseHeaders,url:this.url,readyState:this.readyState,originalEvent:this.originalEvent?{type:this.originalEvent.type,timeStamp:this.originalEvent.timeStamp}:void 0}}}var Hr=__webpack_require__(7),Wr=__webpack_require__(945),qr=__webpack_require__.n(Wr),Kr=__webpack_require__(744),Xr=__webpack_require__.n(Kr);const Jr="undefined"!=typeof process&&process.versions&&process.versions.node?process.versions.node:"unknown",Qr="undefined"!=typeof process&&process.versions&&process.versions.bun?process.versions.bun:"unknown",Yr="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent?window.navigator.userAgent:"unknown",Zr=()=>"unknown"!==Yr,ei=()=>"unknown"!==Qr;function ti(e={},t={}){return Xr()(t,e)}const ni=e=>!(!e||!e.url),ri=e=>!(!e||!e.text),ii=e=>!(!si(e)&&!oi(e)),oi=e=>null!=e&&Buffer.isBuffer(e),si=e=>null!=e&&!Zr()&&"object"==typeof e&&"function"==typeof e.pipe&&"function"==typeof e.read&&"object"==typeof e._readableState;URL;const ai="4.11.2",ui={"Content-Type":"application/json","X-Client-Info":`@deepgram/sdk; ${Zr()?"browser":"server"}; v${ai}`,"User-Agent":`@deepgram/sdk/${ai} ${"unknown"!==Jr?`node/${Jr}`:ei()?`bun/${Qr}`:Zr()?`javascript ${Yr}`:"unknown"}`},li="https://api.deepgram.com",ci="wss://agent.deepgram.com";var di;const hi={global:{fetch:{options:{url:li,headers:ui}},websocket:{options:{url:(di=li,di.toLowerCase().replace(/^http/,"ws")),_nodeOnlyHeaders:ui}}},agent:{fetch:{options:{url:li,headers:ui}},websocket:{options:{url:ci,_nodeOnlyHeaders:ui}}}};var pi,fi;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(pi||(pi={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(fi||(fi={}));const gi=()=>{};class mi extends Hr.EventEmitter{constructor(e){if(super(),this.factory=void 0,this.key=void 0,this.accessToken=void 0,this.namespace="global",this.version="v1",this.baseUrl=li,this.logger=gi,"function"==typeof e.accessToken?(this.factory=e.accessToken,this.accessToken=this.factory()):this.accessToken=e.accessToken,"function"==typeof e.key?(this.factory=e.key,this.key=this.factory()):this.key=e.key,this.key||this.accessToken||(this.accessToken=process.env.DEEPGRAM_ACCESS_TOKEN,this.accessToken||(this.key=process.env.DEEPGRAM_API_KEY)),!this.key&&!this.accessToken)throw new Nr("A deepgram API key or access token is required.");e=(e=>{var t,n,r,i,o,s;const a={};return e._experimentalCustomFetch&&(a.global={fetch:{client:e._experimentalCustomFetch}}),(null===(t=(e=Xr()(e,a)).restProxy)||void 0===t?void 0:t.url)&&(a.global={fetch:{options:{proxy:{url:null===(n=e.restProxy)||void 0===n?void 0:n.url}}}}),(null===(r=(e=Xr()(e,a)).global)||void 0===r?void 0:r.url)&&(a.global={fetch:{options:{url:e.global.url}},websocket:{options:{url:e.global.url}}}),(null===(i=(e=Xr()(e,a)).global)||void 0===i?void 0:i.headers)&&(a.global={fetch:{options:{headers:null===(o=e.global)||void 0===o?void 0:o.headers}},websocket:{options:{_nodeOnlyHeaders:null===(s=e.global)||void 0===s?void 0:s.headers}}}),Xr()(e,a)})(e),this.options=ti(e,hi)}v(e="v1"){return this.version=e,this}get namespaceOptions(){const e=ti(this.options[this.namespace],this.options.global);return Object.assign(Object.assign({},e),{key:this.key})}getRequestUrl(e,t={version:this.version},n){t.version=this.version,e=e.replace(/:(\w+)/g,(function(e,n){return t[n]}));const r=new URL(e,this.baseUrl);return n&&(i=r.searchParams,o=n,Object.keys(o).forEach((e=>{Array.isArray(o[e])?o[e].forEach((t=>{i.append(e,String(t))})):i.append(e,String(o[e]))}))),r;var i,o}log(e,t,n){this.logger(e,t,n)}}var bi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const yi=e=>{let t;return t=e||("undefined"==typeof fetch?qr():fetch),(...e)=>t(...e)};var vi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class wi extends mi{constructor(e){if(super(e),Zr()&&!this.proxy)throw new Nr("Due to CORS we are unable to support REST-based API calls to our API from the browser. Please consider using a proxy: https://dpgr.am/js-proxy for more information.");const{accessToken:t,key:n,fetch:r}=this;this.fetch=(({apiKey:e,customFetch:t,accessToken:n})=>{const r=yi(t),i="undefined"==typeof Headers?Wr.Headers:Headers;return(t,o)=>bi(void 0,void 0,void 0,(function*(){const s=new i(null==o?void 0:o.headers);return s.has("Authorization")||s.set("Authorization",n?`Bearer ${n}`:`Token ${e}`),r(t,Object.assign(Object.assign({},o),{headers:s}))}))})({accessToken:t,apiKey:n,customFetch:r}),this.proxy?this.baseUrl=this.namespaceOptions.fetch.options.proxy.url:this.baseUrl=this.namespaceOptions.fetch.options.url}_getErrorMessage(e){return e.msg||e.message||e.error_description||e.error||JSON.stringify(e)}_handleError(e,t){return vi(this,void 0,void 0,(function*(){const n=yield bi(void 0,void 0,void 0,(function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,945,23))).Response:Response}));e instanceof n?e.json().then((n=>{t(new Br(this._getErrorMessage(n),e.status||500))})).catch((e=>{t(new zr(this._getErrorMessage(e),e))})):t(new zr(this._getErrorMessage(e),e))}))}_getRequestOptions(e,t,n){let r={method:e};return r="GET"===e||"DELETE"===e?Object.assign(Object.assign({},r),t):Object.assign(Object.assign({duplex:"half",body:t},r),n),Xr()(this.namespaceOptions.fetch.options,r,{clone:!1})}_handleRequest(e,t,n,r){return vi(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{(0,this.fetch)(t,this._getRequestOptions(e,n,r)).then((e=>{if(!e.ok)throw e;i(e)})).catch((e=>this._handleError(e,o)))}))}))}get(e,t){return vi(this,void 0,void 0,(function*(){return this._handleRequest("GET",e,t)}))}post(e,t,n){return vi(this,void 0,void 0,(function*(){return this._handleRequest("POST",e,t,n)}))}put(e,t,n){return vi(this,void 0,void 0,(function*(){return this._handleRequest("PUT",e,t,n)}))}patch(e,t,n){return vi(this,void 0,void 0,(function*(){return this._handleRequest("PATCH",e,t,n)}))}delete(e,t){return vi(this,void 0,void 0,(function*(){return this._handleRequest("DELETE",e,t)}))}get proxy(){var e;return"proxy"===this.key&&!!(null===(e=this.namespaceOptions.fetch.options.proxy)||void 0===e?void 0:e.url)}}class Si extends wi{constructor(){super(...arguments),this.namespace="auth"}grantToken(e={},t=":version/auth/grant"){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t),r=JSON.stringify(e);return{result:yield this.post(n,r,{headers:{"Content-Type":"application/json"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}const _i="undefined"!=typeof WebSocket;class Ti extends mi{constructor(e){super(e),this.conn=null,this.sendBuffer=[],this.reconnect=gi;const{key:t,websocket:{options:n,client:r}}=this.namespaceOptions;this.proxy?this.baseUrl=n.proxy.url:this.baseUrl=n.url,this.transport=r||null,n._nodeOnlyHeaders?this.headers=n._nodeOnlyHeaders:this.headers={},"Authorization"in this.headers||(this.accessToken?this.headers.Authorization=`Bearer ${this.accessToken}`:this.headers.Authorization=`Token ${t}`)}connect(e,t){if(this.conn)return;this.reconnect=(n=e)=>{this.connect(n,t)};const n=this.getRequestUrl(t,{},e),r=this.accessToken,i=this.key;if(!r&&!i)throw new Error("No key or access token provided for WebSocket connection.");if(this.transport)return this.conn=new this.transport(n,void 0,{headers:this.headers}),void this.setupConnection();if(ei())__webpack_require__.e(591).then(__webpack_require__.t.bind(__webpack_require__,591,23)).then((({default:e})=>{this.conn=new e(n,{headers:this.headers}),console.log("Using WS package"),this.setupConnection()}));else{if(_i)return this.conn=new WebSocket(n,r?["bearer",r]:["token",i]),void this.setupConnection();this.conn=new xi(n,void 0,{close:()=>{this.conn=null}}),__webpack_require__.e(591).then(__webpack_require__.t.bind(__webpack_require__,591,23)).then((({default:e})=>{this.conn=new e(n,void 0,{headers:this.headers}),this.setupConnection()}))}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null)}connectionState(){switch(this.conn&&this.conn.readyState){case pi.connecting:return fi.Connecting;case pi.open:return fi.Open;case pi.closing:return fi.Closing;default:return fi.Closed}}getReadyState(){var e,t;return null!==(t=null===(e=this.conn)||void 0===e?void 0:e.readyState)&&void 0!==t?t:pi.closed}isConnected(){return this.connectionState()===fi.Open}send(e){const t=()=>function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){var t;if(e instanceof Blob){if(0===e.size)return void this.log("warn","skipping `send` for zero-byte blob",e);e=yield e.arrayBuffer()}"string"==typeof e||(null==e?void 0:e.byteLength)?null===(t=this.conn)||void 0===t||t.send(e):this.log("warn","skipping `send` for zero-byte payload",e)}));this.isConnected()?t():this.sendBuffer.push(t)}get proxy(){var e;return"proxy"===this.key&&!!(null===(e=this.namespaceOptions.websocket.options.proxy)||void 0===e?void 0:e.url)}extractErrorInformation(e,t){var n;const r={};if(t&&(r.readyState=t.readyState,r.url="string"==typeof t.url?t.url:null===(n=t.url)||void 0===n?void 0:n.toString()),t&&"object"==typeof t){const n=t;if(n._req&&n._req.res&&(r.statusCode=n._req.res.statusCode,n._req.res.headers)){r.responseHeaders=Object.assign({},n._req.res.headers);const e=n._req.res.headers["dg-request-id"]||n._req.res.headers["x-dg-request-id"];e&&(r.requestId=e)}if(e&&"target"in e&&e.target){const t=e.target;t.url&&(r.url=t.url),void 0!==t.readyState&&(r.readyState=t.readyState)}}return r}createEnhancedError(e,t){const n=new Gr(e.message||"WebSocket connection error",Object.assign({originalEvent:e},t));return Object.assign(Object.assign({},e),{error:n,statusCode:t.statusCode,requestId:t.requestId,responseHeaders:t.responseHeaders,url:t.url,readyState:t.readyState,message:this.buildEnhancedErrorMessage(e,t)})}buildEnhancedErrorMessage(e,t){let n=e.message||"WebSocket connection error";const r=[];if(t.statusCode&&r.push(`Status: ${t.statusCode}`),t.requestId&&r.push(`Request ID: ${t.requestId}`),void 0!==t.readyState){const e=["CONNECTING","OPEN","CLOSING","CLOSED"][t.readyState]||`Unknown(${t.readyState})`;r.push(`Ready State: ${e}`)}return t.url&&r.push(`URL: ${t.url}`),r.length>0&&(n+=` (${r.join(", ")})`),n}setupConnectionEvents(e){this.conn&&(this.conn.onopen=()=>{this.emit(e.Open,this)},this.conn.onclose=t=>{this.emit(e.Close,t)},this.conn.onerror=t=>{const n=this.extractErrorInformation(t,this.conn||void 0),r=this.createEnhancedError(t,n);this.emit(e.Error,r)})}}class xi{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=pi.connecting,this.send=()=>{},this.url=null,this.url=e.toString(),this.close=n.close}}var Ei;!function(e){e.Open="open",e.Close="close",e.Error="error",e.Transcript="Results",e.Metadata="Metadata",e.UtteranceEnd="UtteranceEnd",e.SpeechStarted="SpeechStarted",e.Unhandled="Unhandled"}(Ei||(Ei={}));class Ci extends Ti{constructor(e,t={},n=":version/listen"){var r,i;if(super(e),this.namespace="listen",(null===(r=t.keyterm)||void 0===r?void 0:r.length)&&!(null===(i=t.model)||void 0===i?void 0:i.startsWith("nova-3")))throw new Nr("Keyterms are only supported with the Nova 3 models.");this.connect(t,n)}setupConnection(){this.setupConnectionEvents({Open:Ei.Open,Close:Ei.Close,Error:Ei.Error}),this.conn&&(this.conn.onmessage=e=>{var t,n,r,i;try{const t=JSON.parse(e.data.toString());t.type===Ei.Metadata?this.emit(Ei.Metadata,t):t.type===Ei.Transcript?this.emit(Ei.Transcript,t):t.type===Ei.UtteranceEnd?this.emit(Ei.UtteranceEnd,t):t.type===Ei.SpeechStarted?this.emit(Ei.SpeechStarted,t):this.emit(Ei.Unhandled,t)}catch(o){this.emit(Ei.Error,{event:e,message:"Unable to parse `data` as JSON.",error:o,url:null===(t=this.conn)||void 0===t?void 0:t.url,readyState:null===(n=this.conn)||void 0===n?void 0:n.readyState,data:(null===(r=e.data)||void 0===r?void 0:r.toString().substring(0,200))+((null===(i=e.data)||void 0===i?void 0:i.toString().length)>200?"...":"")})}})}configure(e){this.send(JSON.stringify({type:"Configure",processors:e}))}keepAlive(){this.send(JSON.stringify({type:"KeepAlive"}))}finalize(){this.send(JSON.stringify({type:"Finalize"}))}finish(){this.requestClose()}requestClose(){this.send(JSON.stringify({type:"CloseStream"}))}}var Pi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Oi extends wi{constructor(){super(...arguments),this.namespace="listen"}transcribeUrl(e,t,n=":version/listen"){var r,i;return Pi(this,void 0,void 0,(function*(){try{let o;if(!ni(e))throw new Nr("Unknown transcription source type");if(o=JSON.stringify(e),void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");if((null===(r=null==t?void 0:t.keyterm)||void 0===r?void 0:r.length)&&!(null===(i=t.model)||void 0===i?void 0:i.startsWith("nova-3")))throw new Nr("Keyterms are only supported with the Nova 3 models.");const s=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(s,o).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}transcribeFile(e,t,n=":version/listen"){return Pi(this,void 0,void 0,(function*(){try{let r;if(!ii(e))throw new Nr("Unknown transcription source type");if(r=e,void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");const i=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(i,r,{headers:{"Content-Type":"deepgram/audio+video"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}transcribeUrlCallback(e,t,n,r=":version/listen"){return Pi(this,void 0,void 0,(function*(){try{let i;if(!ni(e))throw new Nr("Unknown transcription source type");i=JSON.stringify(e);const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}transcribeFileCallback(e,t,n,r=":version/listen"){return Pi(this,void 0,void 0,(function*(){try{let i;if(!ii(e))throw new Nr("Unknown transcription source type");i=e;const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i,{headers:{"Content-Type":"deepgram/audio+video"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}class Ai extends mi{constructor(){super(...arguments),this.namespace="listen"}get prerecorded(){return new Oi(this.options)}live(e={},t=":version/listen"){return new Ci(this.options,e,t)}}var ki=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Ii extends wi{constructor(){super(...arguments),this.namespace="manage"}getTokenDetails(e=":version/auth/token"){return ki(this,void 0,void 0,(function*(){try{const t=this.getRequestUrl(e);return{result:yield this.get(t).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjects(e=":version/projects"){return ki(this,void 0,void 0,(function*(){try{const t=this.getRequestUrl(e);return{result:yield this.get(t).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProject(e,t=":version/projects/:projectId"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}updateProject(e,t,n=":version/projects/:projectId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t),i=JSON.stringify(t);return{result:yield this.patch(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteProject(e,t=":version/projects/:projectId"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return yield this.delete(n),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}getProjectKeys(e,t=":version/projects/:projectId/keys"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectKey(e,t,n=":version/projects/:projectId/keys/:keyId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,keyId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}createProjectKey(e,t,n=":version/projects/:projectId/keys"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t),i=JSON.stringify(t);return{result:yield this.post(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteProjectKey(e,t,n=":version/projects/:projectId/keys/:keyId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,keyId:t});return yield this.delete(r),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}getProjectMembers(e,t=":version/projects/:projectId/members"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}removeProjectMember(e,t,n=":version/projects/:projectId/members/:memberId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,memberId:t});return yield this.delete(r),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}getProjectMemberScopes(e,t,n=":version/projects/:projectId/members/:memberId/scopes"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,memberId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}updateProjectMemberScope(e,t,n,r=":version/projects/:projectId/members/:memberId/scopes"){return ki(this,void 0,void 0,(function*(){try{const i=this.getRequestUrl(r,{projectId:e,memberId:t},n),o=JSON.stringify(n);return{result:yield this.put(i,o).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectInvites(e,t=":version/projects/:projectId/invites"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}sendProjectInvite(e,t,n=":version/projects/:projectId/invites"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t),i=JSON.stringify(t);return{result:yield this.post(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteProjectInvite(e,t,n=":version/projects/:projectId/invites/:email"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,email:t});return yield this.delete(r),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}leaveProject(e,t=":version/projects/:projectId/leave"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.delete(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageRequests(e,t,n=":version/projects/:projectId/requests"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageRequest(e,t,n=":version/projects/:projectId/requests/:requestId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,requestId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageSummary(e,t,n=":version/projects/:projectId/usage"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageFields(e,t,n=":version/projects/:projectId/usage/fields"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectBalances(e,t=":version/projects/:projectId/balances"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectBalance(e,t,n=":version/projects/:projectId/balances/:balanceId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,balanceId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getAllModels(e,t={},n=":version/projects/:projectId/models"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getModel(e,t,n=":version/projects/:projectId/models/:modelId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,modelId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}var Mi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Ri extends wi{constructor(){super(...arguments),this.namespace="models"}getAll(e=":version/models",t={}){return Mi(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(e,{},t);return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getModel(e,t=":version/models/:modelId"){return Mi(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{modelId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}var Di=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class $i extends wi{constructor(){super(...arguments),this.namespace="selfhosted"}listCredentials(e,t=":version/projects/:projectId/onprem/distribution/credentials"){return Di(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getCredentials(e,t,n=":version/projects/:projectId/onprem/distribution/credentials/:credentialsId"){return Di(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,credentialsId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}createCredentials(e,t,n=":version/projects/:projectId/onprem/distribution/credentials"){return Di(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e}),i=JSON.stringify(t);return{result:yield this.post(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteCredentials(e,t,n=":version/projects/:projectId/onprem/distribution/credentials/:credentialsId"){return Di(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,credentialsId:t});return{result:yield this.delete(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}var Li,Fi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Ui extends wi{constructor(){super(...arguments),this.namespace="read"}analyzeUrl(e,t,n=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let r;if(!ni(e))throw new Nr("Unknown source type");if(r=JSON.stringify(e),void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous transcription. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");const i=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(i,r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}analyzeText(e,t,n=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let r;if(!ri(e))throw new Nr("Unknown source type");if(r=JSON.stringify(e),void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous requests. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");const i=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(i,r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}analyzeUrlCallback(e,t,n,r=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let i;if(!ni(e))throw new Nr("Unknown source type");i=JSON.stringify(e);const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}analyzeTextCallback(e,t,n,r=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let i;if(!ri(e))throw new Nr("Unknown source type");i=JSON.stringify(e);const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i,{headers:{"Content-Type":"deepgram/audio+video"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}!function(e){e.Open="Open",e.Close="Close",e.Error="Error",e.Metadata="Metadata",e.Flushed="Flushed",e.Warning="Warning",e.Audio="Audio",e.Unhandled="Unhandled"}(Li||(Li={}));class Ni extends Ti{constructor(e,t={},n=":version/speak"){super(e),this.namespace="speak",this.connect(t,n)}setupConnection(){this.setupConnectionEvents({Open:Li.Open,Close:Li.Close,Error:Li.Error}),this.conn&&(this.conn.onmessage=e=>{this.handleMessage(e)})}handleTextMessage(e){e.type===Li.Metadata?this.emit(Li.Metadata,e):e.type===Li.Flushed?this.emit(Li.Flushed,e):e.type===Li.Warning?this.emit(Li.Warning,e):this.emit(Li.Unhandled,e)}handleBinaryMessage(e){this.emit(Li.Audio,e)}sendText(e){this.send(JSON.stringify({type:"Speak",text:e}))}flush(){this.send(JSON.stringify({type:"Flush"}))}clear(){this.send(JSON.stringify({type:"Clear"}))}requestClose(){this.send(JSON.stringify({type:"Close"}))}handleMessage(e){var t,n,r,i,o,s;if("string"==typeof e.data)try{const t=JSON.parse(e.data);this.handleTextMessage(t)}catch(o){this.emit(Li.Error,{event:e,message:"Unable to parse `data` as JSON.",error:o,url:null===(t=this.conn)||void 0===t?void 0:t.url,readyState:null===(n=this.conn)||void 0===n?void 0:n.readyState,data:(null===(r=e.data)||void 0===r?void 0:r.toString().substring(0,200))+((null===(i=e.data)||void 0===i?void 0:i.toString().length)>200?"...":"")})}else e.data instanceof Blob?e.data.arrayBuffer().then((e=>{this.handleBinaryMessage(Buffer.from(e))})):e.data instanceof ArrayBuffer?this.handleBinaryMessage(Buffer.from(e.data)):Buffer.isBuffer(e.data)?this.handleBinaryMessage(e.data):(console.log("Received unknown data type",e.data),this.emit(Li.Error,{event:e,message:"Received unknown data type.",url:null===(o=this.conn)||void 0===o?void 0:o.url,readyState:null===(s=this.conn)||void 0===s?void 0:s.readyState,dataType:typeof e.data}))}}var ji,Bi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class zi extends wi{constructor(){super(...arguments),this.namespace="speak"}request(e,t,n=":version/speak"){return Bi(this,void 0,void 0,(function*(){let r;if(!ri(e))throw new Nr("Unknown transcription source type");r=JSON.stringify(e);const i=this.getRequestUrl(n,{},Object.assign({model:"aura-2-thalia-en"},t));return this.result=yield this.post(i,r,{headers:{Accept:"audio/*","Content-Type":"application/json"}}),this}))}getStream(){return Bi(this,void 0,void 0,(function*(){if(!this.result)throw new zr("Tried to get stream before making request","");return this.result.body}))}getHeaders(){return Bi(this,void 0,void 0,(function*(){if(!this.result)throw new zr("Tried to get headers before making request","");return this.result.headers}))}}class Vi extends mi{constructor(){super(...arguments),this.namespace="speak"}request(e,t,n=":version/speak"){return new zi(this.options).request(e,t,n)}live(e={},t=":version/speak"){return new Ni(this.options,e,t)}}!function(e){e.Open="Open",e.Close="Close",e.Error="Error",e.Audio="Audio",e.Welcome="Welcome",e.SettingsApplied="SettingsApplied",e.ConversationText="ConversationText",e.UserStartedSpeaking="UserStartedSpeaking",e.AgentThinking="AgentThinking",e.FunctionCallRequest="FunctionCallRequest",e.AgentStartedSpeaking="AgentStartedSpeaking",e.AgentAudioDone="AgentAudioDone",e.InjectionRefused="InjectionRefused",e.PromptUpdated="PromptUpdated",e.SpeakUpdated="SpeakUpdated",e.Unhandled="Unhandled"}(ji||(ji={}));class Gi extends Ti{constructor(e,t="/:version/agent/converse"){var n,r,i,o;super(e),this.namespace="agent",this.baseUrl=null!==(o=null===(i=null===(r=null===(n=e.agent)||void 0===n?void 0:n.websocket)||void 0===r?void 0:r.options)||void 0===i?void 0:i.url)&&void 0!==o?o:ci,this.connect({},t)}setupConnection(){this.setupConnectionEvents({Open:ji.Open,Close:ji.Close,Error:ji.Error}),this.conn&&(this.conn.onmessage=e=>{this.handleMessage(e)})}handleMessage(e){var t,n,r,i,o,s;if("string"==typeof e.data)try{const t=JSON.parse(e.data);this.handleTextMessage(t)}catch(o){this.emit(ji.Error,{event:e,data:(null===(t=e.data)||void 0===t?void 0:t.toString().substring(0,200))+((null===(n=e.data)||void 0===n?void 0:n.toString().length)>200?"...":""),message:"Unable to parse `data` as JSON.",error:o,url:null===(r=this.conn)||void 0===r?void 0:r.url,readyState:null===(i=this.conn)||void 0===i?void 0:i.readyState})}else e.data instanceof Blob?e.data.arrayBuffer().then((e=>{this.handleBinaryMessage(Buffer.from(e))})):e.data instanceof ArrayBuffer?this.handleBinaryMessage(Buffer.from(e.data)):Buffer.isBuffer(e.data)?this.handleBinaryMessage(e.data):(console.log("Received unknown data type",e.data),this.emit(ji.Error,{event:e,message:"Received unknown data type.",url:null===(o=this.conn)||void 0===o?void 0:o.url,readyState:null===(s=this.conn)||void 0===s?void 0:s.readyState,dataType:typeof e.data}))}handleBinaryMessage(e){this.emit(ji.Audio,e)}handleTextMessage(e){e.type in ji?this.emit(e.type,e):this.emit(ji.Unhandled,e)}configure(e){const t=JSON.stringify(Object.assign({type:"Settings"},e));this.send(t)}updatePrompt(e){this.send(JSON.stringify({type:"UpdatePrompt",prompt:e}))}updateSpeak(e){this.send(JSON.stringify({type:"UpdateSpeak",speak:e}))}injectAgentMessage(e){this.send(JSON.stringify({type:"InjectAgentMessage",content:e}))}injectUserMessage(e){this.send(JSON.stringify({type:"InjectUserMessage",content:e}))}functionCallResponse(e){this.send(JSON.stringify(Object.assign({type:"FunctionCallResponse"},e)))}keepAlive(){this.send(JSON.stringify({type:"KeepAlive"}))}}class Hi extends mi{get auth(){return new Si(this.options)}get listen(){return new Ai(this.options)}get manage(){return new Ii(this.options)}get models(){return new Ri(this.options)}get onprem(){return this.selfhosted}get selfhosted(){return new $i(this.options)}get read(){return new Ui(this.options)}get speak(){return new Vi(this.options)}agent(e="/:version/agent/converse"){return new Gi(this.options,e)}get transcription(){throw new Vr}get projects(){throw new Vr}get keys(){throw new Vr}get members(){throw new Vr}get scopes(){throw new Vr}get invitation(){throw new Vr}get usage(){throw new Vr}get billing(){throw new Vr}}var Wi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const qi="[Deepgram STT]";class Ki{constructor(e){var t,n,r,i,o,s,a,u,l,c;this.options=e,this.connection=null,this.isConnected=!1,this.isPaused=!1,this.shouldReconnect=!0,this.isConnecting=!1,this.microphone=null,this.stream=null,this.reconnectAttempts=0,this.reconnectDelay=1e3,this.reconnectTimeoutId=null,this.digitalHumanSpeaking=!1,this.isUserCurrentlySpeaking=!1,this.isUiShowingSpeaking=!1,this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.options.model=this.options.model||"nova-2",this.options.language=this.options.language||"en",this.options.smartFormat=null===(t=this.options.smartFormat)||void 0===t||t,this.options.interimResults=null===(n=this.options.interimResults)||void 0===n||n,this.options.utteranceEndMs=null!==(r=this.options.utteranceEndMs)&&void 0!==r?r:1e3,this.options.vadEvents=null===(i=this.options.vadEvents)||void 0===i||i,this.options.fillerWords=null!==(o=this.options.fillerWords)&&void 0!==o&&o,this.options.endpointing=null!==(s=this.options.endpointing)&&void 0!==s?s:10,this.options.echoCancellation=null===(a=this.options.echoCancellation)||void 0===a||a,this.options.noiseSuppression=null===(u=this.options.noiseSuppression)||void 0===u||u,this.options.autoGainControl=null===(l=this.options.autoGainControl)||void 0===l||l,this.options.interruptionWordThreshold=null!==(c=this.options.interruptionWordThreshold)&&void 0!==c?c:1,this.handleAppMessages()}startRecognition(){return Wi(this,void 0,void 0,(function*(){r.info(`${qi} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),yield this.connect()}))}stopRecognition(){return Wi(this,void 0,void 0,(function*(){r.info(`${qi} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),yield this.disconnect()}))}pause(){return Wi(this,void 0,void 0,(function*(){return r.info(`${qi} Pausing speech recognition`),this.isPaused=!0,this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.isUserCurrentlySpeaking&&(this.dataChannelMsgSend(new Dr(Rr.Stop)),this.isUserCurrentlySpeaking=!1),this.isUiShowingSpeaking&&(this.clientMsgSend(new $n),this.isUiShowingSpeaking=!1),this.stream&&(this.stream.getTracks().forEach((e=>{e.enabled=!1})),r.debug(`${qi} Audio tracks disabled`)),!0}))}resume(){return Wi(this,void 0,void 0,(function*(){return r.info(`${qi} Resuming speech recognition`),this.isPaused=!1,this.stream?(this.stream.getTracks().forEach((e=>{e.enabled=!0})),r.debug(`${qi} Audio tracks re-enabled`),!0):(r.debug(`${qi} No stream available, initiating connection`),yield this.connect(),!0)}))}setChatMetadata(e){this.options.promptMetadata=e}connect(){return Wi(this,void 0,void 0,(function*(){if(this.isConnected)r.warn(`${qi} Already connected`);else if(this.isConnecting)r.warn(`${qi} Connection already in progress`);else{this.isConnecting=!0;try{const e=yield this.getToken();r.info(`${qi} Connecting to Deepgram`);const t=function(e,t){let n={};return"string"==typeof e||"function"==typeof e?n.key=e:"object"==typeof e&&(n=e),new Hi(n)}({accessToken:e.token,global:{url:e.api_url}}),n={model:this.options.model,language:this.options.language,smart_format:this.options.smartFormat,interim_results:this.options.interimResults,utterance_end_ms:this.options.utteranceEndMs,vad_events:this.options.vadEvents,filler_words:this.options.fillerWords,endpointing:this.options.endpointing};this.connection=t.listen.live(n),yield new Promise(((e,t)=>{var n,i;const o=setTimeout((()=>{t(new Error("Connection timeout"))}),1e4),s=()=>{var t,n;clearTimeout(o),this.isConnected=!0,r.info(`${qi} Connection opened`),null===(t=this.connection)||void 0===t||t.off(Ei.Open,s),null===(n=this.connection)||void 0===n||n.off(Ei.Error,a),e()},a=e=>{var n,i;clearTimeout(o),r.error(`${qi} Connection error during open`,r.serialiseError(e)),null===(n=this.connection)||void 0===n||n.off(Ei.Open,s),null===(i=this.connection)||void 0===i||i.off(Ei.Error,a),t(e)};null===(n=this.connection)||void 0===n||n.on(Ei.Open,s),null===(i=this.connection)||void 0===i||i.on(Ei.Error,a)})),this.setupEventHandlers(),yield this.startMicrophone(),r.info(`${qi} Connected successfully`),this.isConnecting=!1,this.resetReconnectionState()}catch(e){this.isConnected=!1,this.isConnecting=!1,r.error(`${qi} Connection error`,r.serialiseError(e)),this.handleError(e),this.shouldReconnect&&!this.isPaused&&this.scheduleReconnect()}}}))}disconnect(){return Wi(this,void 0,void 0,(function*(){if(this.isConnected||this.connection){r.info(`${qi} Disconnecting`);try{this.stopMicrophone(),this.connection&&(this.connection.requestClose(),this.connection=null)}catch(e){r.error(`${qi} Disconnect error`,r.serialiseError(e))}this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.isUserCurrentlySpeaking&&(this.dataChannelMsgSend(new Dr(Rr.Stop)),this.isUserCurrentlySpeaking=!1),this.isUiShowingSpeaking&&(this.clientMsgSend(new $n),this.isUiShowingSpeaking=!1),this.isConnected=!1,this.clientMsgSend(new Kn(!1))}}))}scheduleReconnect(){if(this.reconnectAttempts>=5)return r.error(`${qi} Max reconnection attempts (5) reached`),void this.clientMsgSend(new Bn("Unable to connect to speech recognition service after 5 attempts"));this.reconnectAttempts++,r.info(`${qi} Scheduling reconnection attempt ${this.reconnectAttempts}/5 in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout((()=>{this.connect()}),this.reconnectDelay),this.reconnectDelay=Math.min(2*this.reconnectDelay,3e4)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=1e3,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}getToken(){return Wi(this,void 0,void 0,(function*(){const e=this.options.model||"nova-2",t=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(e)}`,n=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!n.ok)throw new Error(`Token fetch failed: ${n.status} ${n.statusText}`);return yield n.json()}))}startMicrophone(){return Wi(this,void 0,void 0,(function*(){try{r.info(`${qi} Starting microphone`),this.stream=yield navigator.mediaDevices.getUserMedia({audio:{echoCancellation:this.options.echoCancellation,noiseSuppression:this.options.noiseSuppression,autoGainControl:this.options.autoGainControl}}),this.microphone=new MediaRecorder(this.stream,{mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:48e3}),this.microphone.ondataavailable=e=>{e.data.size>0&&this.connection&&this.isConnected&&!this.isPaused&&e.data.arrayBuffer().then((e=>{var t;null===(t=this.connection)||void 0===t||t.send(e)})).catch((e=>{r.error(`${qi} Error converting audio data`,r.serialiseError(e))}))},this.microphone.start(250),r.debug(`${qi} Microphone started`),this.clientMsgSend(new Kn(!0))}catch(e){r.error(`${qi} Microphone error`,r.serialiseError(e)),this.clientMsgSend(new kn(new Error(JSON.stringify(e))))}}))}stopMicrophone(){this.microphone&&"recording"===this.microphone.state&&(this.microphone.stop(),this.microphone=null),this.stream&&(this.stream.getTracks().forEach((e=>{e.stop()})),this.stream=null),r.debug(`${qi} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on(Ei.Open,(()=>{this.handleConnectionOpen()})),this.connection.on(Ei.Transcript,(e=>{this.handleTranscript(e)})),this.connection.on(Ei.Close,(()=>{this.handleConnectionClose()})),this.connection.on(Ei.Error,(e=>{this.handleError(e)})),this.connection.on(Ei.Metadata,(e=>{r.debug(`${qi} Metadata`,e)})))}handleAppMessages(){this.options.messages.subscribe((e=>{switch(e.uneeqMessageType){case wn.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0;break;case wn.PromptResult:e.promptResult.success||this.handleSpeakingEnd();break;case wn.AvatarAnswer:""===e.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case wn.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case wn.SessionEnded:this.shouldReconnect=!1,this.stopRecognition();break;case wn.SessionReconnecting:this.handleSpeakingEnd(),this.shouldReconnect=!1,this.stopRecognition();break;case wn.CustomMetadataUpdated:this.options.promptMetadata=e.chatMetadata;break;case wn.SessionBackendError:this.handleSpeakingEnd()}}))}handleTranscript(e){var t,n,i;try{const o=e.channel;if(!(null==o?void 0:o.alternatives)||0===o.alternatives.length)return;const s=o.alternatives[0],a=String(s.transcript||""),u=!0===e.is_final,l=!0===e.speech_final;if(""===a&&l){if(""!==this.accumulatedTranscript.trim()){r.info(`${qi} Final transcript (from accumulated): "${this.accumulatedTranscript}"`),this.sendChatPrompt(this.accumulatedTranscript);const e=this.accumulatedWordCount>0?this.accumulatedConfidenceSum/this.accumulatedWordCount:1,t={transcript:this.accumulatedTranscript,final:!0,confidence:e,language_code:this.options.language||""};this.clientMsgSend(new Mn(t))}return this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new Dr(Rr.Stop))),void(this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new $n)))}if(""===a)return;if(u&&!l){""!==this.accumulatedTranscript&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=a;const e=a.trim().split(/\s+/).length,n=null!==(t=s.confidence)&&void 0!==t?t:1;this.accumulatedConfidenceSum+=n*e,this.accumulatedWordCount+=e,r.debug(`${qi} Accumulated transcript: "${this.accumulatedTranscript}"`)}const c=(""!==this.accumulatedTranscript?this.accumulatedTranscript:a).trim().split(/\s+/).length,d=null!==(n=this.options.interruptionWordThreshold)&&void 0!==n?n:1;!this.isUiShowingSpeaking&&c>=d&&(this.isUiShowingSpeaking=!0,this.clientMsgSend(new Dn)),!this.isUserCurrentlySpeaking&&c>=d&&(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new Dr(Rr.Start))),this.digitalHumanSpeaking&&c>=d&&(r.debug(`${qi} Interrupting digital human`),this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1),this.isUserCurrentlySpeaking&&l&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new Dr(Rr.Stop))),this.isUiShowingSpeaking&&l&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new $n));const h={transcript:l?this.accumulatedTranscript+(""!==this.accumulatedTranscript?" ":"")+a:a,final:l,confidence:null!==(i=s.confidence)&&void 0!==i?i:1,language_code:this.options.language||""};if(this.clientMsgSend(new Mn(h)),l){const e=""!==this.accumulatedTranscript?this.accumulatedTranscript+" "+a:a;r.info(`${qi} Final transcript: "${e}"`),this.sendChatPrompt(e),this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0}}catch(e){r.error(`${qi} Error processing transcript`,r.serialiseError(e))}}handleConnectionOpen(){this.isConnected=!0}handleConnectionClose(){r.info(`${qi} Connection closed`),this.isConnected=!1,this.clientMsgSend(new Kn(!1)),this.shouldReconnect&&!this.isPaused&&(r.info(`${qi} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}handleError(e){var t;r.error(`${qi} Error occurred`,e);const n=String((null==e?void 0:e.message)||(null===(t=null==e?void 0:e.toString)||void 0===t?void 0:t.call(e))||"Unknown error");n.includes("microphone")||n.includes("permission")||n.includes("getUserMedia")?this.clientMsgSend(new kn(new Error(n))):this.clientMsgSend(new Bn(n))}sendChatPrompt(e){e&&""!==e.trim()&&(this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language),this.dataChannelMsgSend(new Mr(e,this.options.promptMetadata)))}handleSpeakingEnd(){this.digitalHumanSpeaking=!1,this.isPaused&&!this.isUserCurrentlySpeaking&&this.resume()}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}}var Xi,Ji,Qi;!function(e){e.NlpPromptResult="nlp_prompt_result",e.AvatarStartedSpeaking="avatar_started_speaking",e.AvatarStoppedSpeaking="avatar_stopped_speaking",e.Error="error",e.SceneReady="scene_ready",e.SpeechEvent="speech_event",e.SessionEnded="session_ended",e.SpeechStreamOpened="speech_stream_opened",e.SpeechStreamClosed="speech_stream_closed"}(Xi||(Xi={})),function(e){e.CloseUp="close_up",e.LooseCloseUp="loose_close_up",e.TightMediumShot="tight_medium_shot",e.MediumShot="medium_shot",e.MediumFullShot="medium_full_shot",e.FullShot="full_shot"}(Ji||(Ji={})),function(e){e.Left="left",e.Right="right",e.Center="center",e.Centre="centre"}(Qi||(Qi={}));class Yi{constructor(e,t=2e3,n=kr()){this.position=e,this.duration=t,this.requestId=n}toJSON(){return{action:Sn.CameraAnchor,data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}}class Zi{constructor(e){this.session=e,this.isTransferSessionInProgress=!1,this.addTransferSessionListener()}addTransferSessionListener(){this.isTransferSessionInProgress=!1,document.addEventListener("keydown",(e=>{e.ctrlKey&&e.shiftKey&&"y"===e.key.toLowerCase()&&this.transferSession()}))}transferSession(){this.isTransferSessionInProgress?r.warn("Transfer already in progress, skipping"):(this.isTransferSessionInProgress=!0,r.info("Beginning session transfer"),this.session.createSignaling(document.createElement("div")).init())}switchLiveVideo(e,t){r.info("New signaling video is ready for transfer"),this.session.signaling&&e&&t.videoElement&&(t.videoElement.classList.add("incoming-video"),this.session.signaling.videoElement&&t.videoElement&&(null==e||e.appendChild(t.videoElement)),this.session.signaling.startSoftSwitch(),setTimeout((()=>{var e,n;null===(e=this.session.signaling)||void 0===e||e.streamDisconnect(),this.session.signaling=t,this.isTransferSessionInProgress=!1,null===(n=this.session.signaling)||void 0===n||n.stopSoftSwitch(),r.info("Session transfer complete")}),1e3))}}const eo=[1200,1402],to=750;class no{constructor(e){this.config=e,this.messages=new G,this.promptMetadata={},this.welcomeRequested=!1,this.resolutionLogged=!1,this.sessionTransferManager=new Zi(this)}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new Xn(this.promptMetadata))}catch(t){r.error("Error parsing custom metadata",e,r.serialiseError(t))}}setEnableMicrophone(e){this.speechRec?e?this.speechRec.startRecognition():this.speechRec.stopRecognition():r.warn("setEnableMicrophone called but speech recognition is not initialized")}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,null==n||n.dataSend(new Yi(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,null==n||n.dataSend(new Yi(e,t))}createSession(){this.messages.subscribe((e=>{this.config.messageHandler&&this.config.messageHandler(e)})),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,r.info("Session created with id: "+this.id),this.updatePromptMetadata(this.config.customMetadata||{}),this.promptMetadata=this.initMetadata(),this.listenForTabClosure(),this.signaling=this.createSignaling(this.config.videoContainerElement),this.signaling.init()}createSignaling(e=document.createElement("div")){const t=new URLSearchParams({token:this.jwt});this.config.backgroundUrl&&t.append("backgroundUrl",this.config.backgroundUrl);const n=(this.config.connectionUrl+`/session-service/v1/ws/session?${t.toString()}`).replace("http://","ws://").replace("https://","wss://");r.debug("Socket URL:",n);const i=new cr(this,n,e);return i.messages.subscribe((e=>{this.signalingEventHandler(e,i)})),i}signalingEventHandler(e,t){var n,i;switch(e.type){case yn.VideoInitialised:case yn.DataChannelOpen:this.handleSessionReady(t);break;case yn.DataChannelResponse:this.handleDataChannelMessage(e);break;case yn.WebRtcStats:{const t=e.stats;!this.resolutionLogged&&(null===(n=t.inboundVideoStats)||void 0===n?void 0:n.frameWidth)&&(null===(i=t.inboundVideoStats)||void 0===i?void 0:i.frameHeight)&&(r.info("Video resolution:",`${t.inboundVideoStats.frameWidth}x${t.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new jn(t)),this.config.webRtcStatsLogMessages&&r.info("WebRTC stats",t);break}}}handleSessionReady(e){r.debug("Session ready check - video:",e.videoInitialized,"dataChannel:",e.dataChannelOpen,"scene:",e.sceneReady),e.videoInitialized&&e.dataChannelOpen&&e.sceneReady&&(this.setCameraAnchorDistance(this.config.cameraAnchorDistance,0,e),this.setCameraAnchorHorizontal(this.config.cameraAnchorHorizontal,0,e),setTimeout((()=>{this.sessionTransferManager.isTransferSessionInProgress&&this.config.videoContainerElement?this.sessionTransferManager.switchLiveVideo(this.config.videoContainerElement,e):(this.initSpeechRecognition(this.jwt),this.sendWelcomePrompt(),document.body.classList.add("uneeq-streaming-live")),this.messages.next(new Un(this.id))}),to))}initSpeechRecognition(e){if(this.speechRec)return void r.warn("Speech recognition already initialized");let t=this.config.speechRecognitionProvider||ur.Google;r.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!==ur.Google&&t!==ur.Deepgram&&(r.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t=ur.Google,this.config.speechRecognitionProvider=ur.Google),r.info(`[STT] Using provider: ${t}`),t===ur.Deepgram?this.createDeepgramSTT(e):this.createGoogleSTT(e),this.config.enableMicrophone&&this.speechRec&&this.speechRec.startRecognition()}createGoogleSTT(e){const t=this.getSpeechOptions(e);r.debug("Initializing Google STT (speech-recognition-service)"),this.speechRec=new Ur(t)}createDeepgramSTT(e){var t,n,i;r.warn("Deepgram STT is currently in beta, is subject to change, and is not suitable for production use"),r.debug("Initializing Deepgram STT");const o=this.config.deepgramConfig||{},s={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:o.model,language:o.language,smartFormat:o.smartFormat,interimResults:o.interimResults,utteranceEndMs:o.utteranceEndMs,vadEvents:o.vadEvents,encoding:o.encoding,sampleRate:o.sampleRate,channels:o.channels,fillerWords:o.fillerWords,endpointing:o.endpointing,interruptionWordThreshold:o.interruptionWordThreshold,echoCancellation:null===(t=o.microphone)||void 0===t?void 0:t.echoCancellation,noiseSuppression:null===(n=o.microphone)||void 0===n?void 0:n.noiseSuppression,autoGainControl:null===(i=o.microphone)||void 0===i?void 0:i.autoGainControl,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{var t;null===(t=this.signaling)||void 0===t||t.dataSend(e)},enableInterrupt:this.config.enableInterruptBySpeech};this.speechRec=new Ki(s)}getSpeechOptions(e){return{apiUrl:this.config.connectionUrl,assetBasePath:this.config.assetBasePath,enableInterrupt:this.config.enableInterruptBySpeech,enableVad:this.config.enableVad,jwtToken:e,hintPhrases:this.config.speechRecognitionHintPhrases,hintPhrasesBoost:this.config.speechRecognitionHintPhrasesBoost,locales:this.config.speechRecognitionLocales,messages:this.messages,promptMetadata:this.promptMetadata,sessionId:this.id,sendMessage:e=>{var t;null===(t=this.signaling)||void 0===t||t.dataSend(e)}}}initMetadata(){return{userSpokenLocale:"",browserDetectedLocales:this.config.speechRecognitionLocales,userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userScreenWidth:window.screen.availWidth,userScreenHeight:window.screen.availHeight,userAgent:navigator.userAgent,personaId:this.config.personaId,custom:this.config.customMetadata}}handleDataChannelMessage(e){var t;switch(r.debug("Processing data channel message",e),e.msg.type){case Xi.NlpPromptResult:this.messages.next(new Qn(e.msg));break;case Xi.AvatarStartedSpeaking:this.messages.next(new Ln);break;case Xi.AvatarStoppedSpeaking:this.messages.next(new Fn);break;case Xi.Error:{const t=e.msg;r.error(`an error has occurred - ${JSON.stringify(t)}`),this.handleChannelMessageError(t);break}case Xi.SceneReady:this.signaling&&(r.debug("Scene is ready"),this.signaling.sceneReady=!0,this.handleSessionReady(this.signaling),this.messages.next(new Yn));break;case Xi.SpeechEvent:this.messages.next(new Vn(e.msg));break;case Xi.SessionEnded:{const n=e.msg.reason;null===(t=this.signaling)||void 0===t||t.endSession(n);break}case Xi.SpeechStreamOpened:{const t=e.msg;this.audioStreamId=t.streamId;break}case Xi.SpeechStreamClosed:{const t=e.msg;t.streamId===this.audioStreamId?this.audioStreamId=void 0:r.warn("Received SpeechStreamClosed message for unexpected streamId",t.streamId);break}}}handleChannelMessageError(e){var t;const n=(null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.trim())||"An unknown error occurred";e&&eo.includes(e.code)?this.messages.next(new zn(e)):this.messages.next(new Bn(n))}sendWelcomePrompt(){var e;r.debug("Checking if the welcome prompt should be sent. Welcome requested already = "+this.welcomeRequested+". Prompt = ",this.config.welcomePrompt),this.config.welcomePrompt&&this.config.welcomePrompt.length>0&&!this.welcomeRequested&&(this.welcomeRequested=!0,null===(e=this.signaling)||void 0===e||e.dataSend(new Mr(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",(()=>{var e;r.info("Window unload detected, ending session."),null===(e=this.signaling)||void 0===e||e.endSession()}))}}class ro{constructor(e,t=kr()){this.prompt=e,this.requestId=t}toJSON(){return{action:Sn.Speak,data:{requestId:this.requestId,prompt:this.prompt}}}}var io;!function(e){e.Open="open",e.Close="close",e.Interrupt="interrupt"}(io||(io={}));class oo{constructor(e,t,n={},r=kr()){this.action=e,this.streamId=t,this.metadata=n,this.requestId=r}toJSON(){return{action:Sn.SpeechStream,data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}}class so{constructor(e){var t;this.config=e,r.setLevel(null!==(t=e.logLevel)&&void 0!==t?t:"info")}init(){r.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new no(this.config),this.session.createSession()}ensureSessionExists(){var e;return!!(null===(e=this.session)||void 0===e?void 0:e.id)||(r.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){var t,n,r;e&&""!==e.trim()&&this.ensureSessionExists()&&(null===(n=null===(t=this.session)||void 0===t?void 0:t.signaling)||void 0===n||n.dataSend(new Mr(e,null===(r=this.session)||void 0===r?void 0:r.promptMetadata)))}speak(e){var t,n;e&&""!==e.trim()&&this.ensureSessionExists()&&(null===(n=null===(t=this.session)||void 0===t?void 0:t.signaling)||void 0===n||n.dataSend(new ro(e)))}openAudioStream(){var e;const t=this.session;this.ensureSessionExists()&&(null===(e=null==t?void 0:t.signaling)||void 0===e||e.dataSend(new oo(io.Open,null==t?void 0:t.audioStreamId)))}closeAudioStream(){var e;const t=this.session;this.ensureSessionExists()&&void 0!==(null==t?void 0:t.audioStreamId)&&(null===(e=t.signaling)||void 0===e||e.dataSend(new oo(io.Close,t.audioStreamId)))}interruptAudioStream(){var e;const t=this.session;this.ensureSessionExists()&&void 0!==(null==t?void 0:t.audioStreamId)&&(null===(e=t.signaling)||void 0===e||e.dataSend(new oo(io.Interrupt,t.audioStreamId)))}speakAudio(e){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){this.ensureSessionExists()&&(yield function(e,t){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){var n;try{if(void 0===(null==e?void 0:e.audioStreamId))return void r.warn("Audio stream is not open | Call openAudioStream() first");let i;if("string"==typeof t){const e="undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("binary");i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else if(t instanceof Uint8Array)i=t;else{if(!("undefined"!=typeof Blob&&t instanceof Blob))return void r.error("speakAudio: Unsupported audio type",t);{const e=yield t.arrayBuffer();i=new Uint8Array(e)}}const o=Uint8Array.from([1]),s=Uint8Array.from([e.audioStreamId]),a=new Uint8Array(2+i.length);a.set(o,0),a.set(s,1),a.set(i,2),null===(n=e.signaling)||void 0===n||n.dataSendBinary(a)}catch(e){r.error("speakAudioSend: Error sending audio",e)}}))}(this.session,e))}))}cameraAnchorDistance(e,t){var n;this.ensureSessionExists()&&(null===(n=this.session)||void 0===n||n.setCameraAnchorDistance(e,t))}cameraAnchorHorizontal(e,t){var n;this.ensureSessionExists()&&(null===(n=this.session)||void 0===n||n.setCameraAnchorHorizontal(e,t))}endSession(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.endSession())}unmuteDigitalHuman(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.playAudioElement(),r.debug("Unmuted digital human."))}muteDigitalHuman(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.pauseAudioElement(),r.debug("Muted digital human."))}stopSpeaking(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.dataSend(new Ir))}setCustomPromptMetadata(e){var t;this.ensureSessionExists()&&(null===(t=this.session)||void 0===t||t.updatePromptMetadata(e))}enableMicrophone(e=!0){var t;this.ensureSessionExists()&&(null===(t=this.session)||void 0===t||t.setEnableMicrophone(e))}pauseSpeechRecognition(){var e,t,n;if(this.ensureSessionExists()){const r=null!==(n=null===(t=null===(e=this.session)||void 0===e?void 0:e.speechRec)||void 0===t?void 0:t.pause())&&void 0!==n&&n;return r instanceof Promise||r}return!1}resumeSpeechRecognition(){var e,t,n;if(this.ensureSessionExists()){const r=null!==(n=null===(t=null===(e=this.session)||void 0===e?void 0:e.speechRec)||void 0===t?void 0:t.resume())&&void 0!==n&&n;return r instanceof Promise||r}return!1}setWebRtcStatsEnabled(e,t){var n,r,i;(null===(n=this.session)||void 0===n?void 0:n.config)&&(this.session.config.webRtcStatsEmitMessages=e,this.session.config.webRtcStatsLogMessages=t,t?null===(r=this.session.signaling)||void 0===r||r.startAudioStatsMonitor():null===(i=this.session.signaling)||void 0===i||i.stopAudioStatsMonitor())}}window.Uneeq=so})(),__webpack_exports__})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Uneeq",[],t):"object"==typeof exports?exports.Uneeq=t():e.Uneeq=t()}("undefined"!=typeof self?self:this,(()=>(()=>{var __webpack_modules__={945:function(e,t){var n="undefined"!=typeof self?self:this,r=function(){function e(){this.fetch=!1,this.DOMException=n.DOMException}return e.prototype=n,new e}();!function(e){!function(t){var n="URLSearchParams"in e,r="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in e,s="ArrayBuffer"in e;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function l(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function c(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function p(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new Promise((function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function g(e){var t=new FileReader,n=f(t);return t.readAsArrayBuffer(e),n}function m(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=m(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=m(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=p(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,n,r=p(this);if(r)return r;if(this._bodyBlob)return e=this._bodyBlob,n=f(t=new FileReader),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o&&(this.formData=function(){return this.text().then(w)}),this.json=function(){return this.text().then(JSON.parse)},this}h.prototype.append=function(e,t){e=l(e),t=c(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},h.prototype.delete=function(e){delete this.map[l(e)]},h.prototype.get=function(e){return e=l(e),this.has(e)?this.map[e]:null},h.prototype.has=function(e){return this.map.hasOwnProperty(l(e))},h.prototype.set=function(e,t){this.map[l(e)]=c(t)},h.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},h.prototype.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),d(e)},h.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),d(e)},h.prototype.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),d(e)},r&&(h.prototype[Symbol.iterator]=h.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(e,t){var n,r,i=(t=t||{}).body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new h(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new h(t.headers)),this.method=(r=(n=t.method||this.method||"GET").toUpperCase(),y.indexOf(r)>-1?r:n),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}})),t}function S(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},b.call(v.prototype),b.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},S.error=function(){var e=new S(null,{status:0,statusText:""});return e.type="error",e};var _=[301,302,303,307,308];S.redirect=function(e,t){if(-1===_.indexOf(t))throw new RangeError("Invalid status code");return new S(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,n){return new Promise((function(r,o){var s=new v(e,n);if(s.signal&&s.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function u(){a.abort()}a.onload=function(){var e,t,n={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();t.append(r,i)}})),t)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new S(i,n))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",u),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",u)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=h,e.Request=v,e.Response=S),t.Headers=h,t.Request=v,t.Response=S,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t},744:e=>{"use strict";var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===n}(e)}(e)},n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function r(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function i(e,t,n){return e.concat(t).map((function(e){return r(e,n)}))}function o(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return Object.propertyIsEnumerable.call(e,t)})):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}function a(e,n,u){(u=u||{}).arrayMerge=u.arrayMerge||i,u.isMergeableObject=u.isMergeableObject||t,u.cloneUnlessOtherwiseSpecified=r;var l=Array.isArray(n);return l===Array.isArray(e)?l?u.arrayMerge(e,n,u):function(e,t,n){var i={};return n.isMergeableObject(e)&&o(e).forEach((function(t){i[t]=r(e[t],n)})),o(t).forEach((function(o){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,o)||(s(e,o)&&n.isMergeableObject(t[o])?i[o]=function(e,t){if(!t.customMerge)return a;var n=t.customMerge(e);return"function"==typeof n?n:a}(o,n)(e[o],t[o],n):i[o]=r(t[o],n))})),i}(e,n,u):r(n,u)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,n){return a(e,n,t)}),{})};var u=a;e.exports=u},7:e=>{"use strict";var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}g(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function l(e,t,n,r){var i,o,s,l;if(a(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,l=c,console&&console.warn&&console.warn(l)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=c.bind(r);return i.listener=n,r.wrapFn=i,i}function h(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function g(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(void 0===u)return!1;if("function"==typeof u)r(u,this,t);else{var l=u.length,c=f(u,l);for(n=0;n<l;++n)r(c[n],this,t)}return!0},o.prototype.addListener=function(e,t){return l(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return l(this,e,t,!0)},o.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,r,i,o,s;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return h(this,e,!0)},o.prototype.rawListeners=function(e){return h(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},603:module=>{var t;self,t=()=>(()=>{var __webpack_modules__={8453:(e,t,n)=>{"use strict";n.r(t),n.d(t,{InferenceSession:()=>p,Tensor:()=>d,env:()=>s,registerBackend:()=>o});const r={},i=[],o=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createSessionHandler)throw new TypeError("not a valid backend");{const o=r[e];if(void 0===o)r[e]={backend:t,priority:n};else{if(o.priority>n)return;if(o.priority===n&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){const t=i.indexOf(e);-1!==t&&i.splice(t,1);for(let t=0;t<i.length;t++)if(r[i[t]].priority<=n)return void i.splice(t,0,e);i.push(e)}}},s=new class{constructor(){this.wasm={},this.webgl={},this.webgpu={},this.logLevelInternal="warning"}set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);this.logLevelInternal=e}}get logLevel(){return this.logLevelInternal}},a=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"]]);let l=!1;class c{constructor(e,t,n){let r,i,o;if((()=>{if(!l){l=!0;const e="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from;e&&(a.set("int64",BigInt64Array),u.set(BigInt64Array,"int64")),t&&(a.set("uint64",BigUint64Array),u.set(BigUint64Array,"uint64"))}})(),"string"==typeof e)if(r=e,o=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{const n=a.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t))i=n.from(t);else{if(!(t instanceof n))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);i=t}}else if(o=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");const t=typeof e[0];if("string"===t)r="string",i=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",i=Uint8Array.from(e)}}else{const t=u.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,i=e}if(void 0===o)o=[i.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");const s=(e=>{let t=1;for(let n=0;n<e.length;n++){const r=e[n];if("number"!=typeof r||!Number.isSafeInteger(r))throw new TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t})(o);if(s!==i.length)throw new Error(`Tensor's size(${s}) does not match data length(${i.length}).`);this.dims=o,this.type=r,this.data=i,this.size=s}static bufferToTensor(e,t){if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");const{height:n,width:r}=t,i=t.norm??{mean:255,bias:0};let o,s;o="number"==typeof i.mean?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],s="number"==typeof i.bias?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const a=void 0!==t.bitmapFormat?t.bitmapFormat:"RGBA",u=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",l=n*r,d="RGBA"===u?new Float32Array(4*l):new Float32Array(3*l);let h=4,p=0,f=1,g=2,m=3,b=0,y=l,v=2*l,w=-1;"RGB"===a&&(h=3,p=0,f=1,g=2,m=-1),"RGBA"===u?w=3*l:"RBG"===u?(b=0,v=l,y=2*l):"BGR"===u&&(v=0,y=l,b=2*l);for(let t=0;t<l;t++,p+=h,g+=h,f+=h,m+=h)d[b++]=(e[p]+s[0])/o[0],d[y++]=(e[f]+s[1])/o[1],d[v++]=(e[g]+s[2])/o[2],-1!==w&&-1!==m&&(d[w++]=(e[m]+s[3])/o[3]);return new c("float32",d,"RGBA"===u?[1,4,n,r]:[1,3,n,r])}static async fromImage(e,t){const n="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,r="undefined"!=typeof ImageData&&e instanceof ImageData,i="undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap,o="string"==typeof e;let s,a=t??{};if(n){const n=document.createElement("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");if(null==r)throw new Error("Can not access image data");{let n=e.height,i=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(n=t.resizedHeight,i=t.resizedWidth),void 0!==t){if(a=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");if(a.tensorFormat="RGBA",void 0!==t.height&&t.height!==n)throw new Error("Image input config height doesn't match HTMLImageElement height");if(a.height=n,void 0!==t.width&&t.width!==i)throw new Error("Image input config width doesn't match HTMLImageElement width");a.width=i}else a.tensorFormat="RGBA",a.height=n,a.width=i;r.drawImage(e,0,0),s=r.getImageData(0,0,i,n).data}}else{if(!r){if(i){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");if(void 0!==t.bitmapFormat)throw new Error("Image input config format must be defined for ImageBitmap");const n=document.createElement("canvas").getContext("2d");if(null!=n){const r=e.height,i=e.width;if(n.drawImage(e,0,0,i,r),s=n.getImageData(0,0,i,r).data,void 0!==t){if(void 0!==t.height&&t.height!==r)throw new Error("Image input config height doesn't match ImageBitmap height");if(a.height=r,void 0!==t.width&&t.width!==i)throw new Error("Image input config width doesn't match ImageBitmap width");a.width=i}else a.height=r,a.width=i;return c.bufferToTensor(s,a)}throw new Error("Can not access image data")}if(o)return new Promise(((n,r)=>{const i=document.createElement("canvas"),o=i.getContext("2d");if(!e||!o)return r();const s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=()=>{i.width=s.width,i.height=s.height,o.drawImage(s,0,0,i.width,i.height);const e=o.getImageData(0,0,i.width,i.height);if(void 0!==t){if(void 0!==t.height&&t.height!==i.height)throw new Error("Image input config height doesn't match height");if(a.height=i.height,void 0!==t.width&&t.width!==i.width)throw new Error("Image input config width doesn't match width");a.width=i.width}else a.height=i.height,a.width=i.width;n(c.bufferToTensor(e.data,a))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{const n="RGBA";let r,i;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,i=t.resizedWidth):(r=e.height,i=e.width),void 0!==t){if(a=t,void 0!==t.bitmapFormat&&t.bitmapFormat!==n)throw new Error("Image input config format must be RGBA for ImageData");a.bitmapFormat="RGBA"}else a.bitmapFormat="RGBA";if(a.height=r,a.width=i,void 0!==t){const t=document.createElement("canvas");t.width=i,t.height=r;const n=t.getContext("2d");if(null==n)throw new Error("Can not access image data");n.putImageData(e,0,0),s=n.getImageData(0,0,i,r).data}else s=e.data}}if(void 0!==s)return c.bufferToTensor(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")}toDataURL(e){const t=document.createElement("canvas");t.width=this.dims[3],t.height=this.dims[2];const n=t.getContext("2d");if(null!=n){let r,i;void 0!==e?.tensorLayout&&"NHWC"===e.tensorLayout?(r=this.dims[2],i=this.dims[3]):(r=this.dims[3],i=this.dims[2]);const o=void 0!==e?.format?e.format:"RGB",s=e?.norm;let a,u;void 0===s||void 0===s.mean?a=[255,255,255,255]:"number"==typeof s.mean?a=[s.mean,s.mean,s.mean,s.mean]:(a=[s.mean[0],s.mean[1],s.mean[2],0],void 0!==s.mean[3]&&(a[3]=s.mean[3])),void 0===s||void 0===s.bias?u=[0,0,0,0]:"number"==typeof s.bias?u=[s.bias,s.bias,s.bias,s.bias]:(u=[s.bias[0],s.bias[1],s.bias[2],0],void 0!==s.bias[3]&&(u[3]=s.bias[3]));const l=i*r;let c=0,d=l,h=2*l,p=-1;"RGBA"===o?(c=0,d=l,h=2*l,p=3*l):"RGB"===o?(c=0,d=l,h=2*l):"RBG"===o&&(c=0,h=l,d=2*l);for(let e=0;e<i;e++)for(let t=0;t<r;t++){const r=(this.data[c++]-u[0])*a[0],i=(this.data[d++]-u[1])*a[1],o=(this.data[h++]-u[2])*a[2],s=-1===p?255:(this.data[p++]-u[3])*a[3];n.fillStyle="rgba("+r+","+i+","+o+","+s+")",n.fillRect(t,e,1,1)}return t.toDataURL()}throw new Error("Can not access image data")}toImageData(e){const t=document.createElement("canvas").getContext("2d");let n;if(null==t)throw new Error("Can not access image data");{let r,i,o;void 0!==e?.tensorLayout&&"NHWC"===e.tensorLayout?(r=this.dims[2],i=this.dims[1],o=this.dims[3]):(r=this.dims[3],i=this.dims[2],o=this.dims[1]);const s=void 0!==e&&void 0!==e.format?e.format:"RGB",a=e?.norm;let u,l;void 0===a||void 0===a.mean?u=[255,255,255,255]:"number"==typeof a.mean?u=[a.mean,a.mean,a.mean,a.mean]:(u=[a.mean[0],a.mean[1],a.mean[2],255],void 0!==a.mean[3]&&(u[3]=a.mean[3])),void 0===a||void 0===a.bias?l=[0,0,0,0]:"number"==typeof a.bias?l=[a.bias,a.bias,a.bias,a.bias]:(l=[a.bias[0],a.bias[1],a.bias[2],0],void 0!==a.bias[3]&&(l[3]=a.bias[3]));const c=i*r;if(void 0!==e){if(void 0!==e.height&&e.height!==i)throw new Error("Image output config height doesn't match tensor height");if(void 0!==e.width&&e.width!==r)throw new Error("Image output config width doesn't match tensor width");if(void 0!==e.format&&4===o&&"RGBA"!==e.format||3===o&&"RGB"!==e.format&&"BGR"!==e.format)throw new Error("Tensor format doesn't match input tensor dims")}const d=4;let h=0,p=1,f=2,g=3,m=0,b=c,y=2*c,v=-1;"RGBA"===s?(m=0,b=c,y=2*c,v=3*c):"RGB"===s?(m=0,b=c,y=2*c):"RBG"===s&&(m=0,y=c,b=2*c),n=t.createImageData(r,i);for(let e=0;e<i*r;h+=d,p+=d,f+=d,g+=d,e++)n.data[h]=(this.data[m++]-l[0])*u[0],n.data[p]=(this.data[b++]-l[1])*u[1],n.data[f]=(this.data[y++]-l[2])*u[2],n.data[g]=-1===v?255:(this.data[v++]-l[3])*u[3]}return n}reshape(e){return new c(this.type,this.data,e)}}const d=c;class h{constructor(e){this.handler=e}async run(e,t,n){const r={};let i={};if("object"!=typeof e||null===e||e instanceof d||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof d)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else{let e=!1;const s=Object.getOwnPropertyNames(t);for(const n of this.outputNames)if(-1!==s.indexOf(n)){const i=t[n];(null===i||i instanceof d)&&(e=!0,o=!1,r[n]=i)}if(e){if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else i=t}}else if(void 0!==t)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of this.inputNames)if(void 0===e[t])throw new Error(`input '${t}' is missing in 'feeds'.`);if(o)for(const e of this.outputNames)r[e]=null;const s=await this.handler.run(e,r,i),a={};for(const e in s)Object.hasOwnProperty.call(s,e)&&(a[e]=new d(s[e].type,s[e].data,s[e].dims));return a}static async create(e,t,n,o){let s,a={};if("string"==typeof e){if(s=e,"object"==typeof t&&null!==t)a=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,"object"==typeof t&&null!==t)a=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else{if(!(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{const r=e;let i=0,u=e.byteLength;if("object"==typeof t&&null!==t)a=t;else if("number"==typeof t){if(i=t,!Number.isSafeInteger(i))throw new RangeError("'byteOffset' must be an integer.");if(i<0||i>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(u=e.byteLength-i,"number"==typeof n){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||i+u>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-i}].`);if("object"==typeof o&&null!==o)a=o;else if(void 0!==o)throw new TypeError("'options' must be an object.")}else if(void 0!==n)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw new TypeError("'options' must be an object.");s=new Uint8Array(r,i,u)}}const u=(a.executionProviders||[]).map((e=>"string"==typeof e?e:e.name)),l=await(async e=>{const t=0===e.length?i:e,n=[];for(const e of t){const t=r[e];if(t){if(t.initialized)return t.backend;if(t.aborted)continue;const r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init()),await t.initPromise,t.initialized=!0,t.backend}catch(i){r||n.push({name:e,err:i}),t.aborted=!0}finally{delete t.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`)})(u),c=await l.createSessionHandler(s,a);return new h(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}const p=h},5716:(e,t,n)=>{"use strict";t.R=void 0;const r=n(6027),i=n(1723);t.R=new class{async init(){}async createSessionHandler(e,t){const n=new r.Session(t);return await n.loadModel(e),new i.OnnxjsSessionHandler(n)}}},2818:(e,t,n)=>{"use strict";t.c8=t.rX=void 0;const r=n(8453),i=n(5381),o=n(9544),s=n(6640);t.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=!0),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=!1),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const e="undefined"==typeof navigator?(0,i.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},t.c8=new class{async init(){(0,t.rX)(),await(0,o.initWasm)()}async createSessionHandler(e,t){const n=new s.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(e,t),Promise.resolve(n)}}},1057:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(8453),t);const o=n(8453);{const e=n(5716).R;(0,o.registerBackend)("webgl",e,-10)}{const e=n(2818).c8;(0,o.registerBackend)("cpu",e,10),(0,o.registerBackend)("wasm",e,10),(0,o.registerBackend)("xnnpack",e,9)}},4910:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAttributeWithCacheKey=void 0;class n{constructor(e){Object.assign(this,e)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this._cacheKey}}t.createAttributeWithCacheKey=e=>new n(e)},6874:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Attribute=void 0;const r=n(1446),i=n(1287),o=n(9240),s=n(7273);var a=i.onnxruntime.experimental.fbs;class u{constructor(e){if(this._attributes=new Map,null!=e){for(const t of e)t instanceof r.onnx.AttributeProto?this._attributes.set(t.name,[u.getValue(t),u.getType(t)]):t instanceof a.Attribute&&this._attributes.set(t.name(),[u.getValue(t),u.getType(t)]);if(this._attributes.size<e.length)throw new Error("duplicated attribute names")}}set(e,t,n){this._attributes.set(e,[n,t])}delete(e){this._attributes.delete(e)}getFloat(e,t){return this.get(e,"float",t)}getInt(e,t){return this.get(e,"int",t)}getString(e,t){return this.get(e,"string",t)}getTensor(e,t){return this.get(e,"tensor",t)}getFloats(e,t){return this.get(e,"floats",t)}getInts(e,t){return this.get(e,"ints",t)}getStrings(e,t){return this.get(e,"strings",t)}getTensors(e,t){return this.get(e,"tensors",t)}get(e,t,n){const r=this._attributes.get(e);if(void 0===r){if(void 0!==n)return n;throw new Error(`required attribute not found: ${e}`)}if(r[1]!==t)throw new Error(`type mismatch: expected ${t} but got ${r[1]}`);return r[0]}static getType(e){const t=e instanceof r.onnx.AttributeProto?e.type:e.type();switch(t){case r.onnx.AttributeProto.AttributeType.FLOAT:return"float";case r.onnx.AttributeProto.AttributeType.INT:return"int";case r.onnx.AttributeProto.AttributeType.STRING:return"string";case r.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case r.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case r.onnx.AttributeProto.AttributeType.INTS:return"ints";case r.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case r.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[t]}`)}}static getValue(e){const t=e instanceof r.onnx.AttributeProto?e.type:e.type();if(t===r.onnx.AttributeProto.AttributeType.GRAPH||t===r.onnx.AttributeProto.AttributeType.GRAPHS)throw new Error("graph attribute is not supported yet");const n=this.getValueNoCheck(e);if(t===r.onnx.AttributeProto.AttributeType.INT&&s.LongUtil.isLong(n))return s.LongUtil.longToNumber(n);if(t===r.onnx.AttributeProto.AttributeType.INTS){const e=n,t=new Array(e.length);for(let n=0;n<e.length;n++){const r=e[n];t[n]=s.LongUtil.longToNumber(r)}return t}if(t===r.onnx.AttributeProto.AttributeType.TENSOR)return e instanceof r.onnx.AttributeProto?o.Tensor.fromProto(n):o.Tensor.fromOrtTensor(n);if(t===r.onnx.AttributeProto.AttributeType.TENSORS){if(e instanceof r.onnx.AttributeProto)return n.map((e=>o.Tensor.fromProto(e)));if(e instanceof a.Attribute)return n.map((e=>o.Tensor.fromOrtTensor(e)))}if(t===r.onnx.AttributeProto.AttributeType.STRING&&e instanceof r.onnx.AttributeProto){const e=n;return(0,s.decodeUtf8String)(e)}return t===r.onnx.AttributeProto.AttributeType.STRINGS&&e instanceof r.onnx.AttributeProto?n.map(s.decodeUtf8String):n}static getValueNoCheck(e){return e instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(e):this.getValueNoCheckFromOrtFormat(e)}static getValueNoCheckFromOnnxFormat(e){switch(e.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return e.f;case r.onnx.AttributeProto.AttributeType.INT:return e.i;case r.onnx.AttributeProto.AttributeType.STRING:return e.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return e.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return e.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return e.floats;case r.onnx.AttributeProto.AttributeType.INTS:return e.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return e.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return e.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return e.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[e.type]}`)}}static getValueNoCheckFromOrtFormat(e){switch(e.type()){case a.AttributeType.FLOAT:return e.f();case a.AttributeType.INT:return e.i();case a.AttributeType.STRING:return e.s();case a.AttributeType.TENSOR:return e.t();case a.AttributeType.GRAPH:return e.g();case a.AttributeType.FLOATS:return e.floatsArray();case a.AttributeType.INTS:{const t=[];for(let n=0;n<e.intsLength();n++)t.push(e.ints(n));return t}case a.AttributeType.STRINGS:{const t=[];for(let n=0;n<e.stringsLength();n++)t.push(e.strings(n));return t}case a.AttributeType.TENSORS:{const t=[];for(let n=0;n<e.tensorsLength();n++)t.push(e.tensors(n));return t}default:throw new Error(`unsupported attribute type: ${a.AttributeType[e.type()]}`)}}}t.Attribute=u},1975:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveBackend=t.backend=void 0;const r=n(4418),i=new Map;async function o(e){const n=t.backend;if(void 0!==n[e]&&function(e){const t=e;return"initialize"in t&&"function"==typeof t.initialize&&"createSessionHandler"in t&&"function"==typeof t.createSessionHandler&&"dispose"in t&&"function"==typeof t.dispose}(n[e])){const t=n[e];let r=t.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return i.set(e,t),t}}t.backend={webgl:new r.WebGLBackend},t.resolveBackend=async function e(t){if(!t)return e(["webgl"]);{const e="string"==typeof t?[t]:t;for(const t of e){const e=i.get(t);if(e)return e;const n=await o(t);if(n)return n}}throw new Error("no available backend to use")}},4418:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLBackend=void 0;const r=n(8453),i=n(1315),o=n(2171),s=n(3389);t.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(e){r.env.webgl.contextId=e}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){r.env.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(e){r.env.webgl.textureCacheMode=e}get pack(){return r.env.webgl.pack}set pack(e){r.env.webgl.pack=e}get async(){return r.env.webgl.async}set async(e){r.env.webgl.async=e}initialize(){try{return this.glContext=(0,s.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=!1),"boolean"!=typeof this.async&&(this.async=!1),i.Logger.setWithEnv(r.env),i.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return i.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new o.WebGLSessionHandler(this,e)}dispose(){this.glContext.dispose()}}},6859:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CoordsGlslLib=void 0;const r=n(7273),i=n(1997),o=n(6757),s=n(7618),a=n(432);class u extends i.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ")}}coordsToOffset(){return{coordsToOffset:new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ")}}getOutputSamplingSnippet(){const e=this.context.outputTextureLayout;return e.isPacked?this.getPackedOutputSamplingSnippet(e):this.getUnpackedOutputSamplingSnippet(e)}getPackedOutputSamplingSnippet(e){const t=e.unpackedShape,n=[e.width,e.height],r={},s="getOutputCoords";switch(t.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(t,n);break;case 2:r[s]=this.getOutputPacked2DCoords(t,n);break;case 3:r[s]=this.getOutputPacked3DCoords(t,n);break;default:r[s]=this.getOutputPackedNDCoords(t,n)}const a=`\n void setOutput(vec4 val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = val;\n }\n `;return r.floatTextureSetRGBA=new i.GlslLibRoutine(a),r}getUnpackedOutputSamplingSnippet(e){const t=e.unpackedShape,n=[e.width,e.height],r={},s="getOutputCoords";switch(t.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(t,n);break;case 2:r[s]=this.getOutputUnpacked2DCoords(t,n);break;case 3:r[s]=this.getOutputUnpacked3DCoords(t,n);break;case 4:r[s]=this.getOutputUnpacked4DCoords(t,n);break;case 5:r[s]=this.getOutputUnpacked5DCoords(t,n);break;case 6:r[s]=this.getOutputUnpacked6DCoords(t,n);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}const a=`\n void setOutput(float val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n }\n `;return r.floatTextureSetR=new i.GlslLibRoutine(a),r}getOutputScalarCoords(){return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ")}getOutputPacked1DCoords(e,t){const n=t;let r="";return 1===n[0]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.y * ${n[1]}.0);\n }\n `,new i.GlslLibRoutine(r)):1===n[1]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.x * ${n[0]}.0);\n }\n `,new i.GlslLibRoutine(r)):(r=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n }\n `,new i.GlslLibRoutine(r))}getOutputPacked2DCoords(e,t){let n="";if(r.ArrayUtil.arraysEqual(e,t))return n=`\n ivec2 getOutputCoords() {\n return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]}));\n }\n `,new i.GlslLibRoutine(n);const o=t,s=Math.ceil(e[1]/2);return n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${o[0]}, ${o[1]}));\n\n int index = resTexRC.y * ${o[0]} + resTexRC.x;\n\n // reverse r and c order for packed texture\n int r = imod(index, ${s}) * 2;\n int c = 2 * (index / ${s});\n\n return ivec2(r, c);\n }\n `,new i.GlslLibRoutine(n)}getOutputPacked3DCoords(e,t){const n=[t[0],t[1]],r=Math.ceil(e[2]/2),o=r*Math.ceil(e[1]/2),s=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec3(b, r, c);\n }\n `;return new i.GlslLibRoutine(s)}getOutputPackedNDCoords(e,t){const n=[t[0],t[1]],r=Math.ceil(e[e.length-1]/2),o=r*Math.ceil(e[e.length-2]/2);let s=o,a="",u="b, r, c";for(let t=2;t<e.length-1;t++)s*=e[e.length-t-1],a=`\n int b${t} = index / ${s};\n index -= b${t} * ${s};\n `+a,u=`b${t}, `+u;const l=`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n ${a}\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec${e.length}(${u});\n }\n `;return new i.GlslLibRoutine(l)}getOutputUnpacked1DCoords(e,t){const n=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.y * ${t[0]} + resTexRC.x;\n }\n `;return new i.GlslLibRoutine(n)}getOutputUnpacked2DCoords(e,t){const n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `;return new i.GlslLibRoutine(n)}getOutputUnpacked3DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec3(r, c, d);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked4DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d","d2"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec4(r, c, d, d2);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked5DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d","d2","d3"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec5(r, c, d, d2, d3);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked6DCoords(e,t){let n="";const r=e.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=e[r-1];for(let t=r-3;t>=0;--t)o[t]=o[t+1]*e[t+1];const s=["r","c","d","d2","d3","d4"],a=o.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===o.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec6(r, c, d, d2, d3, d4);\n }\n `,new i.GlslLibRoutine(n)}getCommonUtilFuncs(){const e={};let t="uvFromFlat";e[t]=new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "),t="packedUVfrom1D",e[t]=new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="packedUVfrom2D",e[t]=new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="packedUVfrom3D",e[t]=new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="sampleTexture";const n=(0,o.getGlsl)(this.context.glContext.version);return e[t]=new i.GlslLibRoutine(`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }`),e}getInputsSamplingSnippets(){const e={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach(((n,r)=>{const i=this.context.inputTextureLayouts[r],o=(0,a.generateShaderFuncNameFromInputSamplerName)(n);i.isPacked?e[o]=this.getPackedSamplerFromInput(o,n,i):e[o]=this.getUnpackedSamplerFromInput(o,n,i);const s=(0,a.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);i.unpackedShape.length<=t.unpackedShape.length&&(i.isPacked?e[s]=this.getPackedSamplerAtOutputCoords(s,i,t,n):e[s]=this.getUnpackedSamplerAtOutputCoords(s,i,t,n))})),e}getPackedSamplerAtOutputCoords(e,t,n,o){const s=t.unpackedShape,u=n.unpackedShape,l=o,c=(0,a.generateShaderFuncNameFromInputSamplerName)(l),d=s.length,h=u.length,p=r.BroadcastUtil.getBroadcastDims(s,u),f=(0,a.getCoordsDataType)(h),g=h-d;let m;const b=(0,a.getGlChannels)();m=0===d?"":h<2&&p.length>=1?"coords = 0;":p.map((e=>`coords.${b[e+g]} = 0;`)).join("\n");let y="";y=h<2&&d>0?"coords":s.map(((e,t)=>`coords.${b[t+g]}`)).join(", ");let v="return outputValue;";const w=1===r.ShapeUtil.size(s),S=1===r.ShapeUtil.size(u);if(1!==d||w||S){if(w&&!S)v=1===h?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(p.length){const e=d-2,t=d-1;p.indexOf(e)>-1&&p.indexOf(t)>-1?v="return vec4(outputValue.x);":p.indexOf(e)>-1?v="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":p.indexOf(t)>-1&&(v="return vec4(outputValue.xx, outputValue.zz);")}}else v="\n return vec4(outputValue.xy, outputValue.xy);\n ";const _=`\n vec4 ${e}() {\n ${f} coords = getOutputCoords();\n \n int lastDim = coords.${b[h-1]};\n coords.${b[h-1]} = coords.${b[h-2]};\n coords.${b[h-2]} = lastDim;\n \n ${m}\n vec4 outputValue = ${c}(${y});\n ${v}\n }\n `;return new i.GlslLibRoutine(_,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(e,t,n,o){const s=[n.width,n.height],u=[t.width,t.height],l=t.unpackedShape.length,c=n.unpackedShape.length,d=t.unpackedShape,h=n.unpackedShape,p=(0,a.generateShaderFuncNameFromInputSamplerName)(o);if(l===c&&r.ArrayUtil.arraysEqual(u,s)){const t=`\n float ${e}() {\n return sampleTexture(${o}, TexCoords);\n }\n `;return new i.GlslLibRoutine(t,["coordinates.sampleTexture"])}const f=(0,a.getCoordsDataType)(c),g=r.BroadcastUtil.getBroadcastDims(d,h),m=c-l;let b;const y=(0,a.getGlChannels)();b=0===l?"":c<2&&g.length>=1?"coords = 0;":g.map((e=>`coords.${y[e+m]} = 0;`)).join("\n");let v="";v=c<2&&l>0?"coords":t.unpackedShape.map(((e,t)=>`coords.${y[t+m]}`)).join(", ");const w=`\n float ${e}() {\n ${f} coords = getOutputCoords();\n ${b}\n return ${p}(${v});\n }\n `;return new i.GlslLibRoutine(w,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(e,t,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(e,t);case 1:return this.getPackedSampler1D(e,t,n);case 2:return this.getPackedSampler2D(e,t,n);case 3:return this.getPackedSampler3D(e,t,n);default:return this.getPackedSamplerND(e,t,n)}}getUnpackedSamplerFromInput(e,t,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(e,t,n);case 1:return this.getUnpackedSampler1D(e,t,n);case 2:return this.getUnpackedSampler2D(e,t,n);case 3:return this.getUnpackedSampler3D(e,t,n);case 4:return this.getUnpackedSampler4D(e,t,n);case 5:return this.getUnpackedSampler5D(e,t,n);case 6:return this.getUnpackedSampler6D(e,t,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(e,t){const n=`\n vec4 ${e}() {\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR);\n }\n `;return new i.GlslLibRoutine(n)}getPackedSampler1D(e,t,n){const r=[n.width,n.height],s=[r[1],r[0]],a=(0,o.getGlsl)(this.context.glContext.version),u=`vec4 ${e}(int index) {\n vec2 uv = packedUVfrom1D(\n ${s[0]}, ${s[1]}, index);\n return ${a.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(u,["coordinates.packedUVfrom1D"])}getPackedSampler2D(e,t,n){const s=n.unpackedShape,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=a[0],c=a[1];if(null!=a&&r.ArrayUtil.arraysEqual(s,a)){const n=`vec4 ${e}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${l}.0);\n return ${u.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(n)}const d=a,h=Math.ceil(s[1]/2),p=`vec4 ${e}(int row, int col) {\n vec2 uv = packedUVfrom2D(${d[1]}, ${d[0]}, ${h}, row, col);\n return ${u.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(p,["coordinates.packedUVfrom2D"])}getPackedSampler3D(e,t,n){const r=n.unpackedShape,s=[n.width,n.height],u=[s[0],s[1]],l=(0,o.getGlsl)(this.context.glContext.version);if(1===r[0]){const o=r.slice(1),s=[1,2],u=(0,a.squeezeInputShape)(r,o),l=["b","row","col"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=u;const d=this.getPackedSamplerFromInput(e,t,c),h=`${d.routineBody}\n vec4 ${e}(int b, int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(l,s)});\n } `;return new i.GlslLibRoutine(h,d.dependencies)}const c=u[0],d=u[1],h=Math.ceil(r[2]/2),p=`vec4 ${e}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${d}, ${c}, ${h*Math.ceil(r[1]/2)}, ${h}, b, row, col);\n return ${l.texture2D}(${t}, uv);}`;return new i.GlslLibRoutine(p,["coordinates.packedUVfrom3D"])}getPackedSamplerND(e,t,n){const r=n.unpackedShape,s=r.length,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=[a[0],a[1]],c=l[1],d=l[0],h=Math.ceil(r[s-1]/2);let p=h*Math.ceil(r[s-2]/2),f="int b, int row, int col",g=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let e=2;e<s-1;e++)f=`int b${e}, `+f,p*=r[s-e-1],g=`b${e} * ${p} + `+g;const m=`vec4 ${e}(${f}) {\n int index = ${g};\n int texR = index / ${d};\n int texC = index - texR * ${d};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${c});\n return ${u.texture2D}(${t}, uv);\n }`;return new i.GlslLibRoutine(m)}getUnpackedSamplerScalar(e,t,n){const[r,o]=[n.width,n.height];if(1===r&&1===o){const n=`\n float ${e}() {\n return sampleTexture(${t}, halfCR);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${e}() {\n int offset_${t} = coordsToOffset(TexCoords, ${r}, ${o});\n vec2 uv = uvFromFlat(${r}, ${o}, offset_${t});\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler1D(e,t,n){const r=n.width,o=n.height;if(1===o&&1===r){const n=`\n float ${e}(int index) {\n return sampleTexture(${t}, halfCR);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===o){const n=`\n float ${e}(int index) {\n vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===r){const n=`\n float ${e}(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${e}(int index) {\n vec2 uv = uvFromFlat(${r}, ${o}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(e,t,n){const o=n.unpackedShape,u=[n.height,n.width];if(null!=u&&r.ArrayUtil.arraysEqual(o,u)){const n=`\n float ${e}(int row, int col) {\n vec2 uv = (vec2(row, col) + halfCR) / vec2(${u[1]}.0, ${u[0]}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const{newShape:l,keptDims:c}=(0,s.squeezeShape)(o),d=l;if(d.length<o.length){const r=(0,a.squeezeInputShape)(o,d),s=JSON.parse(JSON.stringify(n));s.unpackedShape=r;const u=["col","row"],l=`\n ${this.getUnpackedSamplerFromInput(e,t,s).routineBody}\n float ${e}(int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(u,c)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture"])}const h=u[1],p=u[0];if(1===p){const n=`\n float ${e}(int row, int col) {\n int offset_${t} = coordsToOffset(TexCoords, ${h}, ${p});\n float index = dot(vec3(row, col, offset_${t}), vec3(${o[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}if(1===h){const n=`\n float ${e}(int row, int col) {\n int offset_${t} = coordsToOffset(TexCoords, ${h}, ${p});\n float index = dot(vec3(row, col, offset_${t}), vec3(${o[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}const f=`\n float ${e}(int row, int col) {\n int index = col * ${o[1]} + row;\n vec2 uv = uvFromFlat(${h}, ${p}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(e,t,n){const r=n.unpackedShape,o=r[1]*r[2],u=r[2],{newShape:l,keptDims:c}=(0,s.squeezeShape)(r),d=l;if(d.length<r.length){const o=(0,a.squeezeInputShape)(r,d),s=["batch","col","row"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=this.getUnpackedSamplerFromInput(e,t,u),h=c.reverse(),p=`\n ${l.routineBody}\n float ${e}(int batch, int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new i.GlslLibRoutine(p,l.dependencies)}const h=`\n float ${e}(int depth, int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = depth * ${o} + col * ${u} + row;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(h,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler4D(e,t,n){const r=n.unpackedShape,o=r[3],s=r[2]*o,a=`\n float ${e}(int row, int col, int depth, int depth2) {\n int index = row * ${r[1]*s} + col * ${s} +\n depth2 * ${o} + depth;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(a,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(e,t,n){const r=n.unpackedShape,o=r[4],u=r[3]*o,l=r[2]*u,c=r[1]*l,{newShape:d,keptDims:h}=(0,s.squeezeShape)(r);if(d.length<r.length){const o=(0,a.squeezeInputShape)(r,d),s=["row","col","depth","depth2","depth3"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=`\n ${this.getUnpackedSamplerFromInput(e,t,u).routineBody}\n float ${e}(int row, int col, int depth, int depth2, int depth3) {\n return ${e}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const p=`\n float ${e}(int row, int col, int depth, int depth2, int depth3) {\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth3 * ${o} + depth2;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(p,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(e,t,n){const r=n.unpackedShape,o=r[5],u=r[4]*o,l=r[3]*u,c=r[2]*l,d=r[1]*c,{newShape:h,keptDims:p}=(0,s.squeezeShape)(r);if(h.length<r.length){const o=(0,a.squeezeInputShape)(r,h),s=["row","col","depth","depth2","depth3","depth4"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=`\n ${this.getUnpackedSamplerFromInput(e,t,u).routineBody}\n float ${e}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${e}(${(0,a.getSqueezedParams)(s,p)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const f=`\n float ${e}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = row * ${d} + col * ${c} + depth * ${l} +\n depth2 * ${u} + depth3 * ${o} + depth4;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}toVec(){const e=this.context.outputTextureLayout,t=e.shape.length,n=e.strides,r=e.width,o=e.height,s=[];for(let e=0;e<t-1;++e)s.push(`\n c[${e}] = offset / ${n[e]};`),s.push(`\n offset -= c[${e}] * ${n[e]};`);s.push(`\n c[${t-1}] = offset;`);const a=`\n void toVec(vec2 texCoords, out int c[${t}]) {\n int offset = coordsToOffset(texCoords, ${r}, ${o});\n ${s.join("")}\n }\n void toVec(int offset, out int c[${t}]) {\n ${s.join("")}\n }\n `;return{toVec:new i.GlslLibRoutine(a,["coordinates.coordsToOffset"])}}valueFrom(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const r=this.context.inputTextureLayouts[n],o=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let s=`_${t}`;e[s]=new i.GlslLibRoutine(this.getValueFromSingle(t,o,r.width,r.height,!1),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),s+="_T",e[s]=new i.GlslLibRoutine(this.getValueFromSingle(t,o,r.width,r.height,!0),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])})),e}getValueFromSingle(e,t,n,r,i){let s=`_${e}`;return i&&(s+="_T"),`\n float ${s}(int m[${t}]) {\n int offset = indicesToOffset${s}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n float value = getColorAsFloat(${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, coords));\n return value;\n }\n `}getPackedValueFrom(e,t,n,r,i){let s=`_${e}_Pack`;return i&&(s+="_T"),`\n vec4 ${s}(int m[${t}]) {\n int offset = indicesToOffset_${e}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, coords);\n }\n `}}t.CoordsGlslLib=u},1997:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TopologicalSortGlslRoutines=t.GlslLibRoutineNode=t.GlslLibRoutine=t.GlslLib=t.GlslContext=t.FunctionType=void 0,(n=t.FunctionType||(t.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",t.GlslContext=class{constructor(e,t,n,r){this.glContext=e,this.programInfo=t,this.inputTextureLayouts=n,this.outputTextureLayout=r}},t.GlslLib=class{constructor(e){this.context=e}},t.GlslLibRoutine=class{constructor(e,t){this.routineBody=e,this.dependencies=t}},t.GlslLibRoutineNode=class{constructor(e,t,n){this.name=e,this.dependencies=n||[],t&&(this.routineBody=t)}addDependency(e){e&&this.dependencies.push(e)}},t.TopologicalSortGlslRoutines=class{static returnOrderedNodes(e){if(!e||0===e.length)return[];if(1===e.length)return e;const t=new Set,n=new Set,r=new Array;return this.createOrderedNodes(e,t,n,r),r}static createOrderedNodes(e,t,n,r){for(let i=0;i<e.length;++i)this.dfsTraverse(e[i],t,n,r)}static dfsTraverse(e,t,n,r){if(!e||n.has(e.name))return;if(t.has(e.name))throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");t.add(e.name);const i=e.dependencies;if(i&&i.length>0)for(let e=0;e<i.length;++e)this.dfsTraverse(i[e],t,n,r);r.push(e),n.add(e.name),t.delete(e.name)}}},1371:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingGlslLib=void 0;const r=n(1997);class i extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ")}}encodeUint8(){const e=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n highp vec4 encode(highp float f) {\n highp float F = abs(f);\n highp float Sign = step(0.0,-f);\n highp float Exponent = floor(log2(F));\n highp float Mantissa = (exp2(- Exponent) * F);\n Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n highp vec4 rgba;\n rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));\n rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n ${e}\n rgba = rgba / 255.0; // values need to be normalized to [0,1]\n return rgba;\n }\n `)}}decodeUint8(){const e=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n highp float decode(highp vec4 rgba) {\n rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n ${e}\n highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n return Result;\n }\n `)}}static isLittleEndian(){const e=new ArrayBuffer(4),t=new Uint32Array(e),n=new Uint8Array(e);if(t[0]=3735928559,239===n[0])return!0;if(222===n[0])return!1;throw new Error("unknown endianness")}}t.EncodingGlslLib=i},2691:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FragColorGlslLib=void 0;const r=n(1997),i=n(6757);class o extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const e=(0,i.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n void setFragColor(float value) {\n ${e.output} = encode(value);\n }\n `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ",["encoding.decode"])}}}t.FragColorGlslLib=o},3878:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;t.replaceInlines=function(e){const t={};let r;for(;null!==(r=n.exec(e));){const e=r[3].split(",").map((e=>{const t=e.trim().split(" ");return t&&2===t.length?{type:t[0],name:t[1]}:null})).filter((e=>null!==e));t[r[2]]={params:e,body:r[4]}}for(const n in t){const i="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),o=new RegExp(i,"gm");for(;null!==(r=o.exec(e));){const i=r[1],o=r[2],s=r[3].split(","),a=i?`${i} ${o};`:"";let u=t[n].body,l="";t[n].params.forEach(((e,t)=>{e&&(l+=`${e.type} ${e.name} = ${s[t]};\n`)})),u=`${l}\n ${u}`,u=u.replace("return",`${o} = `);const c=`\n ${a}\n {\n ${u}\n }\n `;e=e.replace(r[0],c)}}return e.replace(n,"")}},8897:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GlslPreprocessor=void 0;const r=n(1997),i=n(3878),o=n(1248),s=n(6757);t.GlslPreprocessor=class{constructor(e,t,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(e,t,n,i),Object.keys(o.glslRegistry).forEach((e=>{const t=new o.glslRegistry[e](this.context);this.libs[e]=t}));const s=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const t=this.libs[e].getFunctions();for(const n in t){const i=e+"."+n;let o;s[i]?(o=s[i],o.routineBody=t[n].routineBody):(o=new r.GlslLibRoutineNode(i,t[n].routineBody),s[i]=o);const a=t[n].dependencies;if(a)for(let e=0;e<a.length;++e)if(s[a[e]])o.addDependency(s[a[e]]);else{const t=new r.GlslLibRoutineNode(a[e]);s[a[e]]=t,o.addDependency(t)}}}}preprocess(){const e=this.context.programInfo;let t=e.shaderSource;return this.context.programInfo.hasMain||(t=`${t}\n ${(0,s.getDefaultFragShaderMain)(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),t=(0,i.replaceInlines)(t),`${(0,s.getFragShaderPreamble)(this.context.glContext.version)}\n ${this.getUniforms(e.inputNames,e.variables)}\n ${this.getImports(t)}\n ${t}`}getImports(e){const t=this.selectGlslLibRoutinesToBeIncluded(e);if(0===t.length)return"";let n="";for(let e=0;e<t.length;++e){if(!t[e].routineBody)throw new Error(`Missing body for the Glsl Library routine: ${t[e].name}`);n+=t[e].routineBody+"\n"}return n}selectGlslLibRoutinesToBeIncluded(e){const t=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach((n=>{const r=n.split(".")[1];-1!==e.indexOf(r)&&t.push(this.glslLibRoutineDependencyGraph[n])})),r.TopologicalSortGlslRoutines.returnOrderedNodes(t)}getUniforms(e,t){const n=[];if(e)for(const t of e)n.push(`uniform sampler2D ${t};`);if(t)for(const e of t)n.push(`uniform ${e.type} ${e.name}${e.arrayLength?`[${e.arrayLength}]`:""};`);return n.join("\n")}}},1248:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.glslRegistry=void 0;const r=n(6859),i=n(1371),o=n(2691),s=n(9183),a=n(9314);t.glslRegistry={encoding:i.EncodingGlslLib,fragcolor:o.FragColorGlslLib,vec:a.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},9183:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShapeUtilsGlslLib=void 0;const r=n(1997);class i extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const e=this.context.outputTextureLayout.shape.length,t={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=e){const i=o.length,s=e-i,a=`bcastIndices_${n}`;let u="";for(let e=0;e<i;++e)u+=`\n realIndices[${e}] = int( mod(float(bcastedIndices[${s+e}]), ${o[e]}.0) );\n `;const l=`\n void ${a} (int bcastedIndices[${e}], out int realIndices[${i}]) {\n ${u}\n }\n `;t[a]=new r.GlslLibRoutine(l)}})),t}bcastMatmulIndex(){const e=this.context.outputTextureLayout.shape.length,t={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>e)){const i=o.length,s=e-i,a=`bcastMatmulIndices_${n}`;let u="";for(let e=0;e<i-2;++e)u+=`\n realIndices[${e}] = int( mod(float(bcastedIndices[${s+e}]), ${o[e]}.0) );\n `;const l=`\n void ${a}(int bcastedIndices[${e}], out int realIndices[${i}]) {\n ${u}\n realIndices[${i-1}] = bcastedIndices[${e-1}];\n realIndices[${i-2}] = bcastedIndices[${e-2}];\n }\n `;t[a]=new r.GlslLibRoutine(l)}})),t}indicesToOffset(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`indicesToOffset_${t}`;e[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s)),u=`indicesToOffset_${t}_T`,e[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s.slice().reverse()))})),e}static indexToOffsetSingle(e,t,n){let r="";for(let e=t-1;e>=0;--e)r+=`\n offset += indices[${e}] * ${n[e]};\n `;return`\n int ${e}(int indices[${t}]) {\n int offset = 0;\n ${r}\n return offset;\n }\n `}offsetToIndices(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`offsetToIndices_${t}`;e[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s)),u=`offsetToIndices_${t}_T`,e[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s.slice().reverse()))})),e}static offsetToIndicesSingle(e,t,n){const r=[];for(let e=0;e<t-1;++e)r.push(`\n indices[${e}] = offset / ${n[e]};`),r.push(`\n offset -= indices[${e}] * ${n[e]};`);return r.push(`\n indices[${t-1}] = offset;`),`\n void ${e}(int offset, out int indices[${t}]) {\n ${r.join("")}\n }\n `}incrementIndices(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const i=this.context.inputTextureLayouts[n].shape,o=i.length,s=`incrementIndices_${t}`;let a="";for(let e=0;e<o;++e)a+=`\n shape[${e}] = ${i[e]};`;const u=`\n void ${s}(int axis, out int indices[${o}]) {\n int shape[${o}];\n ${a};\n for(int i = ${o} -1 ; i >= 0; --i) {\n if(i > axis) continue;\n indices[i] += 1;\n if(indices[i] < shape[i]) {\n break;\n }\n indices[i] = 0;\n }\n }\n `;e[s]=new r.GlslLibRoutine(u)})),e}}t.ShapeUtilsGlslLib=i},6757:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDefaultFragShaderMain=t.getFragShaderPreamble=t.getVertexShaderSource=t.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function i(e){return 1===e?n:r}t.getGlsl=i,t.getVertexShaderSource=function(e){const t=i(e);return`${t.version}\n precision highp float;\n ${t.attribute} vec3 position;\n ${t.attribute} vec2 textureCoord;\n\n ${t.varyingVertex} vec2 TexCoords;\n\n void main()\n {\n gl_Position = vec4(position, 1.0);\n TexCoords = textureCoord;\n }`},t.getFragShaderPreamble=function(e){const t=i(e);return`${t.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${t.varyingFrag} vec2 TexCoords;\n ${t.outputDeclaration}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n // Custom vector types to handle higher dimenalities.\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n `},t.getDefaultFragShaderMain=function(e,t){return`\n void main() {\n int indices[${t}];\n toVec(TexCoords, indices);\n vec4 result = vec4(process(indices));\n ${i(e).output} = result;\n }\n `}},9314:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VecGlslLib=void 0;const r=n(1997);class i extends r.GlslLib{constructor(e){super(e)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const e=this.context.outputTextureLayout.shape.length,t={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const i in t){const o=`${i}Vec`;let s="";for(let n=0;n<e;++n)s+=`\n dest[${n}] ${t[i]} src[${n}];\n `;const a=`\n void ${o}(int src[${e}], out int dest[${e}]) {\n ${s}\n }\n `;n[o]=new r.GlslLibRoutine(a)}return n}copyVec(){const e=this.context.outputTextureLayout.shape.length;let t="";for(let n=0;n<e;++n)t+=`\n dest[${n}] = src[${n}];\n `;const n=`\n void copyVec(int src[${e}], out int dest[${e}]) {\n ${t}\n }\n `;return{copyVec:new r.GlslLibRoutine(n)}}setVecItem(){const e=this.context.outputTextureLayout.shape.length;let t=`\n if(index < 0)\n index =${e} + index;\n if (index == 0)\n m[0] = value;\n `;for(let n=1;n<e-1;++n)t+=`\n else if (index == ${n})\n m[${n}] = value;\n `;t+=`\n else\n m[${e-1}] = value;\n `;const n=`\n void setVecItem(out int m[${e}], int index, int value) {\n ${t}\n }\n `;return{setVecItem:new r.GlslLibRoutine(n)}}getVecItem(){const e=this.context.outputTextureLayout.shape.length;let t=`\n if(index < 0)\n index = ${e} + index;\n if (index == 0)\n return m[0];\n `;for(let n=1;n<e-1;++n)t+=`\n else if (index == ${n})\n return m[${n}];\n `;t+=`\n else\n return m[${e-1}];\n `;const n=`\n int getVecItem(int m[${e}], int index) {\n ${t}\n }\n `;return{getVecItem:new r.GlslLibRoutine(n)}}}t.VecGlslLib=i},7860:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLInferenceHandler=void 0;const r=n(1315),i=n(9240),o=n(7273),s=n(9),a=n(7379),u=n(2488),l=n(540),c=n(3314),d=n(5639);t.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,t){return(0,c.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,t)}executeProgram(e,t){if(t.length<e.inputNames.length)throw new Error(`Input size mustn't be less than ${e.inputNames.length}.`);if(e.inputNames.length!==e.inputTypes.length)throw new Error("input names size does not match input types");const n=[];for(let r=0;r<e.inputNames.length;++r)n[r]=this.getOrCreateTextureData(t[r],e.inputTypes[r]);const r=((e,t)=>{const n=t.map((e=>`${e.unpackedShape.join(",")};${e.width}x${e.height}`)).join("_");let r=e.name;return e.cacheHint&&(r+="["+e.cacheHint+"]"),r+=":"+n,r})(e,n);let i=this.session.programManager.getArtifact(r);const o=i?i.programInfo:"function"==typeof e.get?e.get():e,s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o.output.dims,o.output.textureType),a=this.createTextureData(s,o.output.type);return i||(i=this.session.programManager.build(o,n,a),this.session.programManager.setArtifact(r,i)),this.runProgram(i,n,a),a}run(e,t){return this.executeProgram(e,t).tensor}runProgram(e,t,n){for(let n=0;n<t.length;++n)if(!!t[n].isPacked!=(e.programInfo.inputTypes[n]===d.TextureType.packed))throw new Error(`input[${n}] property packed inconsistent`);if(!!n.isPacked!=(e.programInfo.output.textureType===d.TextureType.packed))throw new Error("output property packed inconsistent");this.session.programManager.run(e,t,n)}getOrCreateTextureData(e,t){let n=this.getTextureData(e.dataId,t===d.TextureType.packed);if(!n&&(n=this.getTextureData(e.dataId,t!==d.TextureType.packed),n))return t===d.TextureType.packed?this.pack(n):this.unpack(n);if(!n){const r=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,e.dims,t);if(t===d.TextureType.packedLastDimension){const n=1,r=4,i=e.dims;if(4===i.length){const o=[i[0],Math.ceil(i[1]*i[2]*i[3]/r)],s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o,t);let a=e.numberData;if(i[1]*i[2]*i[3]%r!=0){const t=i[0],o=i[1]*i[2]*i[3],s=Math.ceil(o*n/r)*r;a=new Float32Array(t*s);for(let r=0;r<t;++r){const t=r*o,i=r*s+r%n*o;a.set(e.numberData.subarray(t,t+o),i)}}return this.createTextureData(s,e.type,a,e,1)}}if(t===d.TextureType.packed){const t=(0,c.createTextureLayoutFromShape)(this.session.layoutStrategy,e.dims,1,[],{reverseWH:!0}),r=this.createTextureData(t,e.type,e.numberData,e,1);n=this.pack(r)}else n=this.createTextureData(r,e.type,e.numberData,e,1)}return n}createTextureDataFromLayoutBindTensor(e,t,n,r){return this.createTextureData(e,t,n,r,1)}createTextureData(e,t,n,i,o){r.Logger.verbose("InferenceHandler",`Creating TextureData: layout:[${JSON.stringify(e)}]`);const s=this.session.textureManager.createTextureFromLayout(t,e,n,o);return this.createTextureDataFromTexture(e,t,s,i)}reshapeUnpacked(e,t){const n=this.getOrCreateTextureData(e,d.TextureType.unpacked),r={channels:n.channels,height:n.height,width:n.width,shape:0!==t.length?t:[1],strides:o.ShapeUtil.computeStrides(t),unpackedShape:t};return this.createTextureDataFromTexture(r,e.type,n.texture).tensor}reshapePacked(e,t){const n=this.getOrCreateTextureData(e,d.TextureType.packed);if((0,a.isReshapeCheap)(e.dims,t)){const r={channels:n.channels,height:n.height,width:n.width,shape:0!==t.length?t:[1],strides:o.ShapeUtil.computeStrides(t),unpackedShape:t,isPacked:!0};return this.createTextureDataFromTexture(r,e.type,n.texture).tensor}const r=(0,a.processDims3D)(e.dims),i=(0,a.processDims3D)(t),s=this.reshapePacked(e,r),u=this.run((0,a.createPackedReshape3DProgramInfoLoader)(this,s,i),[s]);return this.reshapePacked(u,t)}cast(e,t){const n=this.getOrCreateTextureData(e,d.TextureType.unpacked);return this.createTextureDataFromTexture(n,t,n.texture).tensor}createTextureDataFromTexture(e,t,n,r,o){const s=Object.assign(Object.assign({},e),{tensor:r||new i.Tensor(e.unpackedShape,t,(e=>this.readTexture(s)),(async e=>this.readTextureAsync(s)),void 0,o),texture:n});return this.setTextureData(s.tensor.dataId,s,e.isPacked),s}getTextureData(e,t=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,t):t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){this.session.isInitializer(e)?this.session.setTextureData(e,t,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,t)}isTextureLayoutCached(e,t=!1){return!!this.getTextureData(e.dataId,t)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((e=>this.session.textureManager.releaseTexture(e))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((e=>this.session.textureManager.releaseTexture(e))),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,l.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},4110:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WEBGL_OP_RESOLVE_RULES=void 0;const s=n(8817),a=o(n(5194)),u=n(4752),l=n(6668),c=n(9754),d=n(5042),h=n(6742),p=n(4125),f=n(6149),g=n(5378),m=n(6981),b=n(7413),y=n(7006),v=n(8276),w=n(5565),S=n(2834),_=n(1010),T=n(8126),x=n(2801),E=n(565),C=n(2444),P=n(815),O=n(564),A=n(5416),k=n(1240),I=n(5944),M=n(5707),R=o(n(9087)),D=n(7862),$=n(3980);t.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",R.abs],["Acos","","7+",R.acos],["Add","","7+",a.add],["And","","7+",a.and],["Asin","","7+",R.asin],["Atan","","7+",R.atan],["AveragePool","","7+",S.averagePool,S.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",u.cast,u.parseCastAttributes],["Ceil","","6+",R.ceil],["Clip","","6-10",R.clip,R.parseClipAttributes],["Clip","","11+",R.clipV11],["Concat","","4+",l.concat,l.parseConcatAttributes],["Conv","","1+",c.conv,c.parseConvAttributes],["ConvTranspose","","1+",d.convTranspose,d.parseConvTransposeAttributes],["Cos","","7+",R.cos],["Div","","7+",a.div],["Dropout","","7+",R.identity],["DepthToSpace","","1+",h.depthToSpace,h.parseDepthToSpaceAttributes],["Equal","","7+",a.equal],["Elu","","6+",R.elu,R.parseEluAttributes],["Exp","","6+",R.exp],["Flatten","","1+",p.flatten,p.parseFlattenAttributes],["Floor","","6+",R.floor],["FusedConv","com.microsoft","1+",c.conv,c.parseConvAttributes],["Gather","","1+",f.gather,f.parseGatherAttributes],["Gemm","","7-10",g.gemm,g.parseGemmAttributesV7],["Gemm","","11+",g.gemm,g.parseGemmAttributesV11],["GlobalAveragePool","","1+",S.globalAveragePool,S.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",S.globalMaxPool],["Greater","","7+",a.greater],["Identity","","1+",R.identity],["ImageScaler","","1+",m.imageScaler,m.parseImageScalerAttributes],["InstanceNormalization","","6+",b.instanceNormalization,b.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",R.leakyRelu,R.parseLeakyReluAttributes],["Less","","7+",a.less],["LRN","","1+",y.lrn,y.parseLrnAttributes],["Log","","6+",R.log],["MatMul","","1+",v.matMul,v.parseMatMulAttributes],["MaxPool","","1+",S.maxPool,S.parseMaxPoolAttributes],["Mul","","7+",a.mul],["Neg","","6+",R.neg],["Not","","1+",R.not],["Or","","7+",a.or],["Pad","","2-10",w.padV2,w.parsePadAttributesV2],["Pad","","11+",w.padV11,w.parsePadAttributesV11],["Pow","","7+",a.pow],["PRelu","","7+",a.pRelu],["ReduceLogSum","","1+",_.reduceLogSum,_.parseReduceAttributes],["ReduceMax","","1+",_.reduceMax,_.parseReduceAttributes],["ReduceMean","","1+",_.reduceMean,_.parseReduceAttributes],["ReduceMin","","1+",_.reduceMin,_.parseReduceAttributes],["ReduceProd","","1+",_.reduceProd,_.parseReduceAttributes],["ReduceSum","","1-12",_.reduceSum,_.parseReduceAttributes],["ReduceSumSquare","","1+",_.reduceLogSumSquare,_.parseReduceAttributes],["Relu","","6+",R.relu],["Reshape","","5+",T.reshape],["Resize","","10",x.resize,x.parseResizeAttributesV10],["Resize","","11+",x.resize,x.parseResizeAttributesV11],["Shape","","1+",E.shape],["Sigmoid","","6+",R.sigmoid],["Sin","","7+",R.sin],["Slice","","10+",C.sliceV10],["Slice","","1-9",C.slice,C.parseSliceAttributes],["Softmax","","1-12",P.softmax,P.parseSoftmaxAttributes],["Softmax","","13+",P.softmaxV13,P.parseSoftmaxAttributesV13],["Split","","2-12",O.split,O.parseSplitAttributes],["Sqrt","","6+",R.sqrt],["Squeeze","","1-12",A.squeeze,A.parseSqueezeAttributes],["Squeeze","","13+",A.squeezeV13],["Sub","","7+",a.sub],["Sum","","6+",k.sum],["Tan","","7+",R.tan],["Tanh","","6+",R.tanh],["Tile","","6+",I.tile],["Transpose","","1+",M.transpose,M.parseTransposeAttributes],["Upsample","","7-8",$.upsample,$.parseUpsampleAttributesV7],["Upsample","","9",$.upsample,$.parseUpsampleAttributesV9],["Unsqueeze","","1-12",D.unsqueeze,D.parseUnsqueezeAttributes],["Unsqueeze","","13+",D.unsqueezeV13],["Xor","","7+",a.xor]]},8817:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseBatchNormalizationAttributes=t.batchNormalization=void 0;const r=n(4910),i=n(6757),o=n(5639),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};t.batchNormalization=(e,t,n)=>(u(t),[e.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(e,t,n)}),t)]),t.parseBatchNormalizationAttributes=e=>{const t=e.attributes.getFloat("epsilon",1e-5),n=e.attributes.getFloat("momentum",.9),i=e.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:t,momentum:n,spatial:i})};const a=(e,t,n)=>{const r=(0,i.getGlsl)(e.session.backend.glContext.version),a=t[0].dims.length,[u,l]=e.calculateTextureWidthAndHeight(t[1].dims,o.TextureType.unpacked),c=`\n float process(int[${a}] indices) {\n vec2 position = offsetToCoords(indices[1], ${u}, ${l});\n float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n float b = getColorAsFloat(${r.texture2D}(B, position));\n\n return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n }`;return Object.assign(Object.assign({},s),{output:{dims:t[0].dims,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:c})},u=e=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs.");const t=e[0],n=e[1],r=e[2],i=e[3],o=e[4];if(t.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==i.dims.length||1!==o.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1]||o.dims[0]!==t.dims[1])throw new Error("invalid input shape.");if("float32"!==t.type&&"float64"!==t.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==i.type&&"float64"!==i.type||"float32"!==o.type&&"float64"!==o.type)throw new Error("invalid input tensor types.")}},5194:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.xor=t.sub=t.pRelu=t.pow=t.or=t.mul=t.less=t.greater=t.equal=t.div=t.and=t.add=t.glslPRelu=t.glslPow=t.glslXor=t.glslOr=t.glslAnd=t.glslLess=t.glslGreater=t.glslEqual=t.glslSub=t.glslMul=t.glslDiv=t.glslAdd=void 0;const r=n(7273),i=n(1997),o=n(6757),s=n(5639);function a(){const e="add_";return{body:`\n float ${e}(float a, float b) {\n return a + b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 + v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function u(){const e="div_";return{body:`\n float ${e}(float a, float b) {\n return a / b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 / v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function l(){const e="mul_";return{body:`\n float ${e}(float a, float b) {\n return a * b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 * v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function c(){const e="sub_";return{body:`\n float ${e}(float a, float b) {\n return a - b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 - v2;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function d(){const e="equal_";return{body:`\n float ${e}(float a, float b) {\n return float(a == b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4(equal(v1, v2));\n }\n `,name:e,type:i.FunctionType.ValueBased}}function h(){const e="greater_";return{body:`\n float ${e}(float a, float b) {\n return float(a > b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4( v1.r > v2.r ,\n v1.g > v2.g,\n v1.b > v2.b,\n v1.a > v2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function p(){const e="less_";return{body:`\n float ${e}(float a, float b) {\n return float(a < b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4( v1.r < v2.r ,\n v1.g < v2.g,\n v1.b < v2.b,\n v1.a < v2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function f(){const e="and_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) && bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r && b2.r ,\n b1.g && b2.g,\n b1.b && b2.b,\n b1.a && b2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function g(){const e="or_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) || bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r || b2.r ,\n b1.g || b2.g,\n b1.b || b2.b,\n b1.a || b2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function m(){const e="xor_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) ^^ bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r ^^ b2.r ,\n b1.g ^^ b2.g,\n b1.b ^^ b2.b,\n b1.a ^^ b2.a );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function b(){return function(e){const t=`${e}_`;return{body:`\n float ${t}(float a, float b) {\n return ${e}(a, b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return ${e}(v1, v2);\n }\n `,name:t,type:i.FunctionType.ValueBased}}("pow")}function y(){const e="prelu_";return{body:`\n float ${e}(float a, float b) {\n return a < 0.0 ? a * b: a;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4(\n v1.r < 0.0 ? v1.r * v2.r: v1.r,\n v1.g < 0.0 ? v1.g * v2.g: v1.g,\n v1.b < 0.0 ? v1.b * v2.b: v1.b,\n v1.a < 0.0 ? v1.a * v2.a: v1.a\n );\n }\n `,name:e,type:i.FunctionType.ValueBased}}t.glslAdd=a,t.glslDiv=u,t.glslMul=l,t.glslSub=c,t.glslEqual=d,t.glslGreater=h,t.glslLess=p,t.glslAnd=f,t.glslOr=g,t.glslXor=m,t.glslPow=b,t.glslPRelu=y;const v=(e,t,n,r=t[0].type,i)=>{const o=e.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>w(e,t,n,r)}},w=(e,t,n,i=t[0].type)=>{const a=e.session.pack?s.TextureType.packed:s.TextureType.unpacked,u=!r.ShapeUtil.areEqual(t[0].dims,t[1].dims);let l=t[0].dims;const c=e.session.pack;if(u){const s=r.BroadcastUtil.calcShape(t[0].dims,t[1].dims,!1);if(!s)throw new Error("Can't perform binary op on the given tensors");l=s;const u=l.length,d=0!==t[0].dims.length?t[0].dims.length:1,h=0!==t[1].dims.length?t[1].dims.length:1,p=0!==t[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",f=0!==t[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",g=(0,o.getGlsl)(e.session.backend.glContext.version),m=c?`\n ${n.body}\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n vec4 result = ${n.name}(a, b);\n ${g.output} = result;\n }`:`\n ${n.body}\n float process(int indices[${u}]) {\n int aindices[${d}];\n int bindices[${h}];\n ${p}\n ${f}\n return ${n.name}(_A(aindices), _B(bindices));\n }`;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:l,type:i,textureType:a},shaderSource:m,hasMain:c}}const d=(0,o.getGlsl)(e.session.backend.glContext.version),h=`\n ${n.body}\n void main() {\n vec4 v1 = ${d.texture2D}(A, TexCoords);\n vec4 v2 = ${d.texture2D}(B, TexCoords);\n vec4 result = ${n.name}(v1, v2);\n ${d.output} = result;\n }\n `;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:t[0].dims,type:i,textureType:a},shaderSource:h,hasMain:!0}};t.add=(e,t)=>[e.run(v(e,t,a()),t)],t.and=(e,t)=>[e.run(v(e,t,f(),"bool"),t)],t.div=(e,t)=>[e.run(v(e,t,u()),t)],t.equal=(e,t)=>[e.run(v(e,t,d(),"bool"),t)],t.greater=(e,t)=>[e.run(v(e,t,h(),"bool"),t)],t.less=(e,t)=>[e.run(v(e,t,p(),"bool"),t)],t.mul=(e,t)=>[e.run(v(e,t,l()),t)],t.or=(e,t)=>[e.run(v(e,t,g(),"bool"),t)],t.pow=(e,t)=>[e.run(v(e,t,b()),t)],t.pRelu=(e,t)=>[e.run(v(e,t,y()),t)],t.sub=(e,t)=>[e.run(v(e,t,c()),t)],t.xor=(e,t)=>[e.run(v(e,t,m(),"bool"),t)]},4752:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseCastAttributes=t.cast=void 0;const r=n(7273);t.cast=(e,t,n)=>(i(t),[e.cast(t[0],n)]),t.parseCastAttributes=e=>r.ProtoUtil.tensorDataTypeFromProto(e.attributes.getInt("to"));const i=e=>{if(!e||1!==e.length)throw new Error("Cast requires 1 input.");if("string"===e[0].type)throw new Error("Invalid input type.")}},4595:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedConcatProgramInfoLoader=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614);t.createPackedConcatProgramInfoLoader=(e,t,n)=>{const u=(l=t.length,c=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:l},((e,t)=>`X${t}`)),inputTypes:Array(l).fill(i.TextureType.packed),cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=n[0].dims.slice();if(u>=l.length||u<-1*l.length)throw new Error("axis specified for concat doesn't match input dimensionality");u<0&&(u=l.length+u);const c=l.slice(0);for(let e=1;e<n.length;e++){const t=n[e].dims.slice();for(let e=0;e<l.length;e++)if(e===u)c[u]+=t[e];else if(l[e]!==t[e])throw new Error("non concat dimensions must match")}const d=c.length,h=(0,s.getChannels)("coords",d),p=(0,o.getCoordsDataType)(d),f=(0,s.unpackFromChannel)(),g=n.map((e=>e.dims)),m=(0,o.getGlChannels)(d),b=new Array(g.length-1);b[0]=g[0][u];for(let e=1;e<b.length;e++)b[e]=b[e-1]+g[e][u];const y=m[u],v=m.slice(-2),w=m.join();let S=`if (${y} < ${b[0]}) {\n return getChannel(\n getX0(${w}), vec2(${v.join()}));\n }`;for(let e=1;e<b.length;e++){const t=b[e-1];S+=`\n if (${y} < ${b[e]} && ${y} >= ${b[e-1]}) {\n return getChannel(\n getX${e}(${a(m,y,t)}),\n vec2(${a(v,y,t)}));\n }`}const _=b.length,T=b[b.length-1];S+=`\n return getChannel(\n getX${_}(${a(m,y,T)}),\n vec2(${a(v,y,T)}));`;const x=(0,r.getGlsl)(e.session.backend.glContext.version),E=`\n ${f}\n float getValue(${m.map((e=>"int "+e))}) {\n ${S}\n }\n\n void main() {\n ${p} coords = getOutputCoords();\n int lastDim = coords.${m[d-1]};\n coords.${m[d-1]} = coords.${m[d-2]};\n coords.${m[d-2]} = lastDim;\n\n vec4 result = vec4(getValue(${h}), 0., 0., 0.);\n\n ${h[d-1]} = ${h[d-1]} + 1;\n if (${h[d-1]} < ${c[d-1]}) {\n result.g = getValue(${h});\n }\n\n ${h[d-2]} = ${h[d-2]} + 1;\n if (${h[d-2]} < ${c[d-2]}) {\n result.a = getValue(${h});\n }\n\n ${h[d-1]} = ${h[d-1]} - 1;\n if (${h[d-2]} < ${c[d-2]} &&\n ${h[d-1]} < ${c[d-1]}) {\n result.b = getValue(${h});\n }\n ${x.output} = result;\n }\n `;return Object.assign(Object.assign({},t),{output:{dims:c,type:n[0].type,textureType:i.TextureType.packed},shaderSource:E,hasMain:!0})})(e,u,t,n.axis)})};const a=(e,t,n)=>{const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}},6668:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseConcatAttributes=t.concat=void 0;const r=n(4910),i=n(5639),o=n(4595);t.concat=(e,t,n)=>(d(t),e.session.pack&&t[0].dims.length>1?[e.run((0,o.createPackedConcatProgramInfoLoader)(e,t,n),t)]:[e.run(s(e,t,n),t)]);const s=(e,t,n)=>{const r=(o=t.length,s=n.cacheKey,{name:"Concat",inputNames:Array.from({length:o},((e,t)=>`X${t}`)),inputTypes:Array(o).fill(i.TextureType.unpacked),cacheHint:s});var o,s;return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const o=n[0].dims.slice();if(r>=o.length||r<-1*o.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=o.length+r);const s=o.slice(0);for(let e=1;e<n.length;e++){const t=n[e].dims.slice();for(let e=0;e<o.length;e++)if(e===r)s[r]+=t[e];else if(o[e]!==t[e])throw new Error("non concat dimensions must match")}const d=s.length,h=new Array(n.length);let p=0;for(let e=0;e<h.length;++e)p+=n[e].dims[r],h[e]=p;let f="";f=n.length<5?a(h):u(h);const g=`\n ${l(n.length,d)}\n ${c(h)}\n ${f}\n float process(int indices[${d}]) {\n int textureIndex = getTextureWhereDataResides (indices[${r}]);\n\n if(textureIndex != 0) {\n indices[${r}] = indices[${r}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));\n }\n\n return fetchDataFromCorrectTexture(textureIndex, indices);\n }`;return Object.assign(Object.assign({},t),{output:{dims:s,type:n[0].type,textureType:i.TextureType.unpacked},shaderSource:g})})(0,r,t,n.axis)})},a=e=>`int getTextureWhereDataResides(int index) {\n ${e.map(((e,t)=>`if(index<${e}) {return ${t};}\n`)).join("")}\n }`,u=e=>a(e),l=(e,t)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${t}]) {`];for(let t=0;t<e;++t)0===t?n.push(`\tif (textureIndex == ${t}) { return _X${t}(indices); }`):t===e-1?n.push(`\telse { return _X${t}(indices); }`):n.push(`\telse if (textureIndex == ${t}) { return _X${t}(indices); }`);return n.push("\t}"),n.join("\n")},c=e=>{const t=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n<e.length;++n)0===n?t.push(`\tif (index == ${n}) { return ${e[n]}; }`):n===e.length-1?t.push(`\telse { return ${e[n]}; }`):t.push(`\telse if (index == ${n}) { return ${e[n]}; }`);return t.push("\t}"),t.join("\n")};t.parseConcatAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const d=e=>{if(!e||e.length<1)throw new Error("too few inputs");const t=e[0].type,n=e[0].dims.length;if("string"===t)throw new Error("string tensor is not supported yet");for(const r of e){if(r.type!==t)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},7825:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(1315),i=n(6757),o=n(5639),s=n(9754),a=n(2150);t.createUnpackedGroupedConvProgramInfoLoader=(e,t,n)=>{const u=(l=t.length>2,c=n.cacheKey,{name:"GroupedConv",inputNames:l?["X","W","Bias"]:["X","W"],inputTypes:l?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=t.length>2?"value += getBias(output_channel);":"",c=t[0].dims.slice(),d=t[1].dims.slice(),h=d[0]/u.group;r.Logger.verbose("GroupedConv",`autpPad:${u.autoPad}, dilations:${u.dilations}, group:${u.group}, kernelShape:${u.kernelShape}, pads:${u.pads}, strides:${u.strides}`);const p=(0,s.calculateOutputShape)(c,d,u.dilations,u.pads,u.strides),f=(0,i.getGlsl)(e.session.backend.glContext.version),{activationFunction:g,applyActivation:m}=(0,a.getActivationSnippet)(u),b=`\n const ivec2 strides = ivec2(${u.strides[0]}, ${u.strides[1]});\n const ivec2 pads = ivec2(${u.pads[0]}, ${u.pads[1]});\n ${g}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n ivec2 xRCCorner = coords.zw * strides - pads;\n int group_id = output_channel / ${h};\n\n float value = 0.0;\n for (int wInChannel = 0; wInChannel < ${d[1]}; wInChannel++) {\n int input_channel = group_id * ${d[1]} + wInChannel;\n for (int wHeight = 0; wHeight < ${d[2]}; wHeight++) {\n int xHeight = xRCCorner.x + wHeight * ${u.dilations[0]};\n\n if (xHeight < 0 || xHeight >= ${c[2]}) {\n continue;\n }\n\n for (int wWidth = 0; wWidth < ${d[3]}; wWidth++) {\n int xWidth = xRCCorner.y + wWidth * ${u.dilations[1]};\n if (xWidth < 0 || xWidth >= ${c[3]}) {\n continue;\n }\n\n float xVal = getX(batch, input_channel, xWidth, xHeight);\n float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n value += xVal*wVal;\n }\n }\n }\n ${l}\n ${m}\n ${f.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:p,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:b,hasMain:!0})})(e,t,u,n)})}},7708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.conv2DPacked=t.conv2DPackedPointwise=void 0;const r=n(9754),i=n(5950),o=n(5632);t.conv2DPackedPointwise=(e,t,n)=>{const i=t[0].dims,s=t[1].dims,a=(0,r.calculateOutputShape)(i,s,n.dilations,n.pads,n.strides),u=e.reshapePacked(t[0],[i[1],i[2]*i[3]]),l=e.reshapePacked(t[1],[s[0],s[1]]),c=t.length>2?[l,u,t[2]]:[l,u],d=e.run((0,o.createPackedMatmulProgramInfoLoader)(e,c,n),c);return e.reshapePacked(d,a)},t.conv2DPacked=(e,t,n)=>{const s=t[0].dims,a=t[1].dims,u=(0,r.calculateOutputShape)(s,a,n.dilations,n.pads,n.strides),l=e.run((0,i.createPackedIm2ColProgramInfoLoader)(e,t[0],t[1],u,n),[t[0]]),c=e.reshapePacked(t[1],[a[0],a[1]*a[2]*a[3]]),d=3===t.length?[c,l,t[2]]:[c,l],h=e.run((0,o.createPackedMatmulProgramInfoLoader)(e,d,n),d);return e.reshapePacked(h,u)}},5042:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseConvTransposeAttributes=t.convTranspose=void 0;const r=n(4910),i=n(6757),o=n(5639),s=n(2150),a=(e,t,n,r,i,o)=>(e-1)*t+n+(r-1)*i+1-o,u=(e,t,n,r,i)=>{const o=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=o,n[i]=e-o):"SAME_LOWER"===t&&(n[r]=e-o,n[i]=o)};t.convTranspose=(e,t,n)=>(h(t,n),l(e,t,n));const l=(e,t,n)=>{const r=d(n,t);return[c(e,t,r)]},c=(e,t,n)=>e.run(((e,t,n)=>{const r=(a=t.length>2,u=n.cacheKey,{name:"ConvTranspose",inputNames:a?["X","W","B"]:["X","W"],inputTypes:a?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:u});var a,u;return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const a=t.length>2?"getB(output_channel)":"0.0",u=t[0].dims,l=t[1].dims,c=l[1],d=l[0]/r.group,h=[t[0].dims[0],t[1].dims[1]*r.group,...r.outputShape],p=(0,i.getGlsl)(e.session.backend.glContext.version),{activationFunction:f,applyActivation:g}=(0,s.getActivationSnippet)(r),m=`\n const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n ${f}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n\n ivec2 loc = coords.zw + pads;\n\n int group_id = output_channel / ${c};\n int wOutChannel = output_channel - group_id * ${c};\n\n float value = ${a};\n for (int inChannelOffset = 0; inChannelOffset < ${d}; inChannelOffset++) {\n int input_channel = group_id * ${d} + inChannelOffset;\n for (int wWOff = 0; wWOff < ${l[2]}; wWOff++) {\n for (int wHOff = 0; wHOff < ${l[3]}; wHOff++) {\n ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n ivec2 wLoc = loc - wOff;\n ivec2 wLocIn = wLoc / strides;\n if (\n wLocIn * strides == wLoc &&\n wLocIn.x >= 0 && wLocIn.x < ${u[2]} &&\n wLocIn.y >= 0 && wLocIn.y < ${u[3]}\n ) {\n float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n value += xVal * wVal;\n }\n }\n }\n }\n ${g}\n ${p.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:h,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:m,hasMain:!0})})(e,t,r,n)})})(e,t,n),t),d=(e,t)=>{const n=e.kernelShape.slice();if(0===e.kernelShape.length)for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e]);const r=e.pads.slice(),i=e.outputShape.slice();((e,t,n,r,i,o,s,l)=>{const c=e.length-2,d=0===l.length;for(let h=0;h<c;++h){const p=d?e[h+2]*o[h]:l[h],f=a(e[h+2],o[h],i[h],t[h],n[h],p);u(f,r,i,h,h+c),d&&l.push(o[h]*(e[h+2]-1)+s[h]+(t[h]-1)*n[h]+1-i[h]-i[h+c])}})(t[0].dims,n,e.dilations,e.autoPad,r,e.strides,e.outputPadding,i);const o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:r,outputShape:i,cacheKey:e.cacheKey}),o};t.parseConvTransposeAttributes=e=>{const t=e.attributes,n=(0,s.parseInternalActivationAttributes)(t),i=t.getString("auto_pad","NOTSET"),o=t.getInts("dilations",[1,1]),a=t.getInt("group",1),u=t.getInts("kernel_shape",[]),l=t.getInts("output_padding",[0,0]),c=t.getInts("output_shape",[]),d=t.getInts("pads",[0,0,0,0]),h=t.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:a,kernelShape:u,outputPadding:l,outputShape:c,pads:d,strides:h},n))};const h=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length||4!==e[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims[1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");const r=e[0].dims.length-2;if(t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==e[0].type||"float32"!==e[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===e.length&&"float32"!==e[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},9754:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseConvAttributes=t.conv=t.calculateOutputShape=void 0;const r=n(4910),i=n(7273),o=n(7825),s=n(7708),a=n(3281),u=n(2150),l=n(1625),c=n(8276);t.calculateOutputShape=(e,t,n,r,i)=>{const o=e[0],s=e.slice(2),a=s.length,u=t[0],l=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),c=s.map(((e,t)=>e+r[t]+r[t+a])).map(((e,t)=>Math.floor((e-l[t]+i[t])/i[t])));return[o,u].concat(...c)},t.conv=(e,t,n)=>(g(t,n),d(e,t,n));const d=(e,t,n)=>{const r=f(n,t),i=e.session.pack,a=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[e.run((0,o.createUnpackedGroupedConvProgramInfoLoader)(e,t,r),t)]:a&&i?[h(e,t,r)]:i&&4===t[0].dims.length&&1===t[0].dims[0]&&!a?[(0,s.conv2DPacked)(e,t,r)]:[p(e,t,r)]},h=(e,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,t.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),a=e.reshapeUnpacked(n[0],[i[1],i[2]*i[3]]),u=e.reshapeUnpacked(n[1],[o[0],o[1]]),l=n.length>2?[u,a,n[2]]:[u,a],d=e.run((0,c.createMatmulProgramInfoLoader)(l,r),l);return e.reshapeUnpacked(d,s)},p=(e,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,t.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),u=e.run((0,l.createIm2ColProgramInfoLoader)(e,n[0],n[1],s,r),[n[0]]),c=3===n.length?[u,n[1],n[2]]:[u,n[1]];return e.run((0,a.createDotProductProgramInfoLoader)(e,n,s,r),c)},f=(e,t)=>{const n=e.kernelShape.slice();if(0===e.kernelShape.length)for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e]);const r=e.pads.slice();i.PoolConvUtil.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,r,e.autoPad);const o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:r,cacheKey:e.cacheKey}),o};t.parseConvAttributes=e=>{const t=e.attributes,n=(0,u.parseInternalActivationAttributes)(t),i=t.getString("auto_pad","NOTSET"),o=t.getInts("dilations",[1,1]),s=t.getInt("group",1),a=t.getInts("kernel_shape",[]),l=t.getInts("pads",[0,0,0,0]),c=t.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:s,kernelShape:a,pads:l,strides:c},n))};const g=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length||4!==e[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims[1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");const n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==e[0].type||"float32"!==e[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===e.length&&"float32"!==e[2].type)throw new Error("Conv input(bias) should be float tensor")}},6742:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDepthToSpaceAttributes=t.depthToSpace=void 0;const r=n(5707);t.depthToSpace=(e,t,n)=>{i(t);const o=n.blocksize,s=o*o,a="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],u="DCR"===n.mode?[t[0].dims[0],o,o,t[0].dims[1]/s,t[0].dims[2],t[0].dims[3]]:[t[0].dims[0],t[0].dims[1]/s,o,o,t[0].dims[2],t[0].dims[3]],l=e.reshapeUnpacked(t[0],u),c={perm:a,cacheKey:`${a}`},[d]=(0,r.transpose)(e,[l],c),h=[t[0].dims[0],t[0].dims[1]/s,t[0].dims[2]*o,t[0].dims[3]*o];return[e.reshapeUnpacked(d,h)]},t.parseDepthToSpaceAttributes=e=>{const t=e.attributes.getInt("blocksize");if(t<1)throw new Error(`blocksize must be >= 1, but got : ${t} for DepthToSpace`);const n=e.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:t}};const i=e=>{if(1!==e.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${e.length}`);if("string"===e[0].type||4!==e[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},3281:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createDotProductProgramInfoLoader=void 0;const r=n(7273),i=n(6757),o=n(5639),s=n(2150),a=n(1625);t.createDotProductProgramInfoLoader=(e,t,n,u)=>{const l=((e,t)=>({name:"ConvDotProduct",inputNames:e?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:e?[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.packedLastDimension],cacheKey:t.activationCacheKey}))(t.length>2,u);return Object.assign(Object.assign({},l),{get:()=>((e,t,n,u,l)=>{const c=n[0].dims,d=n[1].dims,h=[d[0],Math.ceil(c[1]*d[2]*d[3]/4)],p=(0,a.calculateIm2ColDims)(c,d,u),[f,g]=e.calculateTextureWidthAndHeight(h,o.TextureType.packedLastDimension),m=r.ShapeUtil.computeStrides(p),[b,y]=e.calculateTextureWidthAndHeight(p,o.TextureType.packedLastDimension),v=u.length,w=n.length<3?"0.0":"_B(b)",S=Math.ceil(c[1]*d[2]*d[3]/4),{activationFunction:_,applyActivation:T}=(0,s.getActivationSnippet)(l),x=(0,i.getGlsl)(e.session.backend.glContext.version),E=`\n${_}\nfloat process(int indices[${v}]) {\n int b[1];\n b[0] = indices[1];\n int im2col[4];\n im2col[0] = indices[0];\n im2col[1] = indices[2];\n im2col[2] = indices[3];\n int im2colOffset = im2col[0] * ${m[0]} + im2col[1] * ${m[1]} + im2col[2] * ${m[2]};\n int kernelOffset = indices[1] * ${h[1]};\n float value = ${w};\n for (int i = 0; i < ${S}; ++i) {\n vec2 im2colCoords = offsetToCoords(im2colOffset, ${b}, ${y});\n vec2 kernelCoords = offsetToCoords(kernelOffset, ${f}, ${g});\n value += dot(${x.texture2D}(Im2Col, im2colCoords), ${x.texture2D}(K, kernelCoords));\n ++im2colOffset;\n ++kernelOffset;\n }\n ${T}\n return value;\n}`;return Object.assign(Object.assign({},t),{output:{dims:u,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:E})})(e,l,t,n,u)})}},4125:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseFlattenAttributes=t.flatten=void 0;const r=n(7273);t.flatten=(e,t,n)=>{i(t,n);const o=r.ShapeUtil.flattenShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],o)]},t.parseFlattenAttributes=e=>e.attributes.getInt("axis",1);const i=(e,t)=>{if(!e||1!==e.length)throw new Error("Flatten requires 1 input.");const n=e[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(t<-n||t>n)throw new Error("Invalid axis");if("string"===e[0].type)throw new Error("string tensor is not supported.")}},2150:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseInternalActivationAttributes=t.getActivationSnippet=void 0;const r=n(7273),i=n(9087);t.getActivationSnippet=function(e){let t;switch(e.activation){case"Relu":t=(0,i.glslRelu)();break;case"Sigmoid":t=(0,i.glslSigmoid)();break;case"Clip":t=(0,i.glslClip)(e.clipMin,e.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=t.name;return{activationFunction:t.body,applyActivation:`value = ${n}_(value);`}},t.parseInternalActivationAttributes=e=>{const t=e.getString("activation","");if("Clip"===t){const[n,i]=e.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:t,clipMax:i,clipMin:n,activationCacheKey:`${t}:${n},${i}`}}return{activation:t,activationCacheKey:t}}},6149:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseGatherAttributes=t.gather=void 0;const r=n(4910),i=n(6145),o=n(7273),s=n(5639);t.gather=(e,t,n)=>(l(t,n.axis),[e.run(u(e,t,n),t)]),t.parseGatherAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",0)});const a={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},u=(e,t,n)=>{const r=Object.assign(Object.assign({},a),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const i=n[0].dims.slice(),a=n[1].dims.slice(),u=new Array(i.length+a.length-1);r=o.ShapeUtil.normalizeAxis(r,i.length);const l=[];for(let e=0;e<u.length;e++)e<r?(u[e]=i[e],l.push(`inputIdx[${e}] = outputIdx[${e}];`)):e<r+a.length?(u[e]=a[e-r],l.push(`indexDataIdx[${e-r}] = outputIdx[${e}];`)):(u[e]=i[e-a.length+1],l.push(`inputIdx[${e-a.length+1}] = outputIdx[${e}];`));const c=`\n float process(int outputIdx[${u.length||1}]) {\n int inputIdx[${i.length}];\n int indexDataIdx[${a.length||1}];\n indexDataIdx[0] = 0;\n ${l.join("\n ")}\n int idx = int(_B(indexDataIdx));\n inputIdx[${r}] = idx < 0 ? idx + ${i[r]} : idx;\n return _A(inputIdx);\n }`;return Object.assign(Object.assign({},t),{output:{dims:u,type:n[0].type,textureType:s.TextureType.unpacked},shaderSource:c})})(0,r,t,n.axis)})},l=(e,t)=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.");const n=e[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(t<-n||t>n-1)throw new Error("Invalid axis.");if(-1===i.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invaid input type.");if("int32"!==e[1].type&&"int16"!==e[1].type)throw new Error("Invaid input type.")}},5378:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseGemmAttributesV11=t.parseGemmAttributesV7=t.gemm=void 0;const r=n(4910),i=n(7273),o=n(5639);t.gemm=(e,t,n)=>(l(t,n),[e.run(a(t,n),t)]);const s=(e,t)=>{const n=0!==e.attributes.getInt("transA",0),i=0!==e.attributes.getInt("transB",0),o=e.attributes.getFloat("alpha",1),s=e.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:i,alpha:o,beta:s,isOptionalC:t})};t.parseGemmAttributesV7=e=>s(e,!1),t.parseGemmAttributesV11=e=>s(e,!0);const a=(e,t)=>{const n={name:"Gemm",inputNames:3===e.length?["A","B","C"]:["A","B"],inputTypes:3===e.length?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},n),{get:()=>u(n,e,t)})},u=(e,t,n)=>{const r=t[0].dims.slice(),s=t[1].dims.slice(),[a,u]=i.GemmUtil.getShapeOfGemmResult(r,n.transA,s,n.transB,3===t.length?t[2].dims:void 0),l=[a,u];if(!l)throw new Error("Can't use gemm on the given tensors");let c=r[r.length-1],d="";n.transA&&(c=r[0]),n.transA&&n.transB?d="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?d="value += _A_T(a) * _B(b);":!n.transA&&n.transB?d="value += _A(a) * _B_T(b);":n.transA||n.transB||(d="value += _A(a) * _B(b);");const h=l.length,p=`\n float process(int indices[${h}]) {\n int a[${h}];\n int b[${h}];\n ${3===t.length?`int c[${t[2].dims.length}];`:""}\n\n copyVec(indices, a);\n copyVec(indices, b);\n ${3===t.length?"bcastIndices_C(indices, c);":""}\n\n float value = 0.0;\n for (int k=0; k<${c}; ++k) {\n a[${h-1}] = k;\n b[${h-2}] = k;\n ${d}\n }\n\n value = value * alpha;\n ${3===t.length?"value += beta * _C(c);":""}\n return value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:l,type:t[0].type,textureType:o.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:p})},l=(e,t)=>{if(!e)throw new Error("Input is missing");if(t.isOptionalC&&(e.length<2||e.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&3!==e.length)throw new Error("Gemm requires 3 inputs");if(3===e.length&&1!==e[2].dims.length&&2!==e[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==e[0].type&&"float64"!==e[0].type||"float32"!==e[1].type&&"float64"!==e[1].type||3===e.length&&"float32"!==e[2].type&&"float64"!==e[2].type)throw new Error("Invalid input type.");if(e[0].type!==e[1].type||3===e.length&&e[0].type!==e[2].type)throw new Error("Input types are mismatched")}},5950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedIm2ColProgramInfoLoader=void 0;const r=n(6757),i=n(5639),o=n(5614);t.createPackedIm2ColProgramInfoLoader=(e,t,n,s,a)=>{const u=(l=a.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[i.TextureType.packed],cacheHint:l});var l;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,s,a,u)=>{const l=n.dims,c=s.dims,d=a.length,h=[c[1]*c[2]*c[3],a[2]*a[3]],p=c[2]*c[3],f=(0,o.unpackFromChannel)(),g=(0,r.getGlsl)(e.session.backend.glContext.version);let m="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)m+=`\n blockIndex = rc.x + ${t};\n pos = rc.y + ${e};\n\n if(blockIndex < ${h[1]} && pos < ${h[0]}) {\n offsetY = int(blockIndex / (${a[d-1]})) * ${u.strides[0]} -\n ${u.pads[0]};\n d0 = offsetY + ${u.dilations[0]} * (imod(pos, ${p}) / ${c[2]});\n\n if(d0 < ${l[2]} && d0 >= 0) {\n offsetX = imod(blockIndex, ${a[d-1]}) * ${u.strides[1]} -\n ${u.pads[1]};\n d1 = offsetX + ${u.dilations[1]} * imod(imod(pos, ${p}), ${c[2]});\n\n if(d1 < ${l[3]} && d1 >= 0) {\n\n ch = int(float(pos)/ ${p}.);\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(0, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n\n `;const b=`\n ${f}\n\n void main() {\n ivec2 rc = getOutputCoords();\n vec4 result = vec4(0.0);\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n ${m}\n ${g.output} = result;\n }\n `;return Object.assign(Object.assign({},t),{output:{dims:h,type:n.type,textureType:i.TextureType.packed},shaderSource:b,hasMain:!0})})(e,u,t,n,s,a)})}},1625:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateIm2ColDims=t.createIm2ColProgramInfoLoader=void 0;const r=n(5639);t.createIm2ColProgramInfoLoader=(e,n,i,o,s)=>{const a=(u=s.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:u});var u;return Object.assign(Object.assign({},a),{get:()=>((e,n,i,o,s,a)=>{const u=i.dims,l=o.dims,c=s.length,d=(0,t.calculateIm2ColDims)(u,l,s,4),h=`\n const int XC = ${u[1]};\n const int XH = ${u[2]};\n const int XW = ${u[3]};\n const int KH = ${a.kernelShape[0]};\n const int KW = ${a.kernelShape[1]};\n const int dilationH = ${a.dilations[0]};\n const int dilationW = ${a.dilations[1]};\n const int strideH = ${a.strides[0]};\n const int strideW = ${a.strides[1]};\n const int padH = ${a.pads[0]};\n const int padW = ${a.pads[1]};\n const int KHKW = KH*KW;\n const int XCKHKW = XC * KHKW;\n const int outputChannels = 4;\n vec4 process(int indices[${c}]) {\n int b = indices[0]; // batch size\n int oh = indices[1] * strideH - padH; //output height\n int ow = indices[2] * strideW - padW; //output width\n int p = indices[3] * outputChannels; //patch\n vec4 value = vec4(0.0);\n for(int i=0; i < outputChannels; ++i) {\n if(p < XCKHKW) {\n int patchC = p / KHKW;\n int patchH = (p - patchC*KHKW) / KW;\n int patchW = (p - patchC*KHKW) - patchH * KW;\n int xh2 = oh + patchH * dilationH;\n int xw2 = ow + patchW * dilationW;\n int x[${u.length}];\n x[0] = b;\n x[1] = patchC;\n x[2] = xh2;\n x[3] = xw2;\n if(xh2 >= 0 &&\n xh2 < XH &&\n xw2 >= 0 &&\n xw2 < XW) {\n value[i] = _X(x);\n }\n }\n ++p;\n }\n return value;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:d,type:i.type,textureType:r.TextureType.packedLastDimension},shaderSource:h})})(0,a,n,i,o,s)})},t.calculateIm2ColDims=(e,t,n,r=4)=>[n[0],n[2],n[3],Math.ceil(e[1]*t[2]*t[3]/r)]},6981:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseImageScalerAttributes=t.imageScaler=void 0;const r=n(4910),i=n(5639);t.imageScaler=(e,t,n)=>(u(t),[e.run(s(e,t,n),t)]),t.parseImageScalerAttributes=e=>{const t=e.attributes.getFloat("scale"),n=e.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:t,bias:n})};const o={name:"ImageScaler",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=(e,t,n)=>{const r=Object.assign(Object.assign({},o),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const o=n[0].dims.slice(),s=o.length,u=`\n ${a(r.bias.length)}\n float process(int indices[${s}]) {\n return _X(indices) * scale + getBias(bias, indices[1]);\n }`;return Object.assign(Object.assign({},t),{output:{dims:o,type:n[0].type,textureType:i.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:u})})(0,r,t,n)})},a=e=>{const t=[`float getBias(float bias[${e}], int channel) {`];for(let n=0;n<e;++n)0===n?t.push(`\tif (channel == ${n}) { return bias[${n}]; }`):n===e-1?t.push(`\telse { return bias[${n}]; }`):t.push(`\telse if (channel == ${n}) { return bias[${n}]; }`);return t.push("\t}"),t.join("\n")},u=e=>{if(!e||1!==e.length)throw new Error("ImageScaler requires 1 input.");if(4!==e[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")}},7413:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseInstanceNormalizationAttributes=t.instanceNormalization=void 0;const r=n(6757),i=n(5639);t.instanceNormalization=(e,t,n)=>{l(t);const r=e.run(s(t[0]),t);return[e.run(u(e,t[0],n,r.dims),[t[0],r,t[1],t[2]])]},t.parseInstanceNormalizationAttributes=e=>e.attributes.getFloat("epsilon",1e-5);const o={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=e=>Object.assign(Object.assign({},o),{get:()=>((e,t)=>{const n=t.dims.slice(),r=n[1],o=n[2]*n[3],s=[n[0],r],a=`\n vec4 process(int[2] indices) {\n vec4 v = vec4(0.0);\n int a[4];\n a[0] = indices[0];\n a[1] = indices[1];\n float temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += x;\n }\n }\n float mean = temp / float(${o});\n temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += (x - mean) * (x - mean);\n }\n }\n v.r = mean;\n v.g = temp / float(${o});\n\n return v;\n }`;return Object.assign(Object.assign({},e),{output:{dims:s,type:t.type,textureType:i.TextureType.packedLastDimension},shaderSource:a})})(o,e)}),a={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked,i.TextureType.unpacked]},u=(e,t,n,o)=>{const s=Object.assign(Object.assign({},a),{cacheHint:`${n}`});return Object.assign(Object.assign({},s),{get:()=>((e,t,n,o,s)=>{const a=(0,r.getGlsl)(e.session.backend.glContext.version),[u,l]=e.calculateTextureWidthAndHeight(s,i.TextureType.packedLastDimension),[c,d]=[u/4,l],h=`\n vec4 get_MeanAndVariance(int[2] mv) {\n int offset = indicesToOffset_MeanAndVariance(mv);\n vec2 coords = offsetToCoords(offset, ${c}, ${d});\n return ${a.texture2D}(MeanAndVariance, coords);\n }\n\n float process(int[4] indices) {\n int mv[2];\n mv[0] = indices[0];\n mv[1] = indices[1];\n vec4 mean_and_variance = get_MeanAndVariance(mv);\n float mean = mean_and_variance.r;\n float variance = mean_and_variance.g;\n\n int sb[1];\n sb[0] = indices[1];\n float scale = _Scale(sb);\n float b = _B(sb);\n\n return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n }`;return Object.assign(Object.assign({},t),{output:{dims:n.dims,type:n.type,textureType:i.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:o}],shaderSource:h})})(e,s,t,n,o)})},l=e=>{if(!e||3!==e.length)throw new Error("InstanceNormalization requires 3 inputs.");const t=e[0],n=e[1],r=e[2];if(t.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==t.type&&"float64"!==t.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==e[0].dims.length)throw new Error("Only support 4-D input shape.")}},7006:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createLrnProgramInfoLoader=t.parseLrnAttributes=t.lrn=void 0;const r=n(4910),i=n(5639);t.lrn=(e,t,n)=>(a(t),[e.run(s(t,n),t)]),t.parseLrnAttributes=e=>{const t=e.attributes.getFloat("alpha",1e-4),n=e.attributes.getFloat("beta",.75),i=e.attributes.getFloat("bias",1),o=e.attributes.getInt("size");return(0,r.createAttributeWithCacheKey)({alpha:t,beta:n,bias:i,size:o})};const o={name:"LRN",inputNames:["X"],inputTypes:[i.TextureType.unpacked]};function s(e,t){return Object.assign(Object.assign({},o),{cacheHint:t.cacheKey,get:()=>function(e,t){const n=e[0].dims[1],r=e[0].dims.length,s=-Math.floor((t.size-1)/2),a=Math.ceil((t.size-1)/2),u=`float(${t.alpha}) / float(${t.size})`,l=`\n float process(int indices[${r}]) {\n int c = indices[1];\n float x = _X(indices);\n float square_sum = 0.0;\n\n for (int i = ${s}; i <= ${a}; i++) {\n int idx = c + i;\n if (c >= 0 && c < ${n}) {\n indices[1] = idx;\n float j = _X(indices);\n square_sum += j * j;\n }\n }\n return x / pow(float(${t.bias}) + ${u} * square_sum, float(${t.beta}));\n }`;return Object.assign(Object.assign({},o),{cacheHint:t.cacheKey,output:{dims:e[0].dims,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:l})}(e,t)})}t.createLrnProgramInfoLoader=s;const a=e=>{if(!e||1!==e.length)throw new Error("LRN requires 1 input.");if(4!==e[0].dims.length)throw new Error('currently only support LRN for input with "NCHW" format');if("float32"!==e[0].type)throw new Error("input should be float type")}},5632:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackedMatmulProgramInfoLoader=void 0;const r=n(7273),i=n(6757),o=n(5639),s=n(432),a=n(2150),u=n(8276);t.createPackedMatmulProgramInfoLoader=(e,t,n)=>{const l=(c=t.length>2,d=n.activationCacheKey,{name:"MatMul (packed)",inputNames:c?["A","B","Bias"]:["A","B"],inputTypes:c?[o.TextureType.packed,o.TextureType.packed,o.TextureType.packed]:[o.TextureType.packed,o.TextureType.packed],cacheHint:d});var c,d;return Object.assign(Object.assign({},l),{get:()=>((e,t,n,l)=>{const c=n.length>2,d=c?"value += getBiasForMatmul();":"",h=n[0].dims,p=n[1].dims,f=r.BroadcastUtil.calcShape(h,p,!0),g=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!f)throw new Error("Can't use matmul on the given tensors");const m=h[h.length-1],b=Math.ceil(m/2),y=h.length,v=p.length,w=(0,i.getGlsl)(e.session.backend.glContext.version),S=(0,s.getCoordsDataType)(f.length),_=f.length,T=(0,s.getGlChannels)(),{activationFunction:x,applyActivation:E}=(0,a.getActivationSnippet)(l),C=c?`${(0,u.getBiasForMatmul)(S,T,n[2].dims,f,!0)}`:"",P=g?`${function(e,t,n,i){let o=[],s=[];const a=n[0].dims,u=n[1].dims,l=a.length,c=u.length,d=i.length,h=d-l,p=d-c;o=a.map(((e,n)=>`coords.${t[n+h]}`)),o[l-1]="i*2",o.join(", "),s=u.map(((e,n)=>`coords.${t[n+p]}`)),s[c-2]="i*2",s.join(", ");const f=r.BroadcastUtil.getBroadcastDims(a,i),g=r.BroadcastUtil.getBroadcastDims(u,i),m=f.map((e=>`coords.${t[e+h]} = 0;`)).join("\n"),b=g.map((e=>`coords.${t[e+p]} = 0;`)).join("\n"),y=`int lastDim = coords.${t[d-1]};\n coords.${t[d-1]} = coords.${t[d-2]};\n coords.${t[d-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n ${e} coords = getOutputCoords();\n ${y}\n ${m}\n vec4 outputValue = getA(${o});\n return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n ${e} coords = getOutputCoords();\n ${y}\n ${b}\n vec4 outputValue = getB(${s});\n return outputValue;\n}`}(S,T,n,f)}`:"",O=g?"getAAtOutCoordsMatmul(i)":`getA(${function(e,t){let n="";for(let r=0;r<t-2;r++)n+=`rc.${e[r]}, `;return n+=`rc.${e[t-2]}, i*2`,n}(T,y)})`,A=g?"getBAtOutCoordsMatmul(i)":`getB(${function(e,t){let n="";for(let r=0;r<t-2;r++)n+=`rc.${e[r]}, `;return n+=`i*2, rc.${e[t-1]}`,n}(T,v)})`,k=`\n ${P}\n ${C}\n ${x}\n void main() {\n ${g?"":`${S} rc =\n getOutputCoords(); int lastDim = rc.${T[_-1]}; rc.${T[_-1]} =\n rc.${T[_-2]}; rc.${T[_-2]} = lastDim;\n `}\n\n vec4 value = vec4(0);\n for (int i = 0; i < ${b}; i++) {\n vec4 a = ${O};\n vec4 b = ${A};\n\n value += (a.rrbb * b.rgrg);\n value += (a.ggaa * b.baba);\n }\n ${d}\n ${E}\n ${w.output} = value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:f,type:n[0].type,textureType:o.TextureType.packed},shaderSource:k,hasMain:!0})})(e,l,t,n)})}},8276:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getBiasForMatmul=t.createMatmulProgramInfoLoader=t.parseMatMulAttributes=t.matMul=void 0;const r=n(7273),i=n(5639),o=n(432),s=n(2150),a=n(5632);t.matMul=(e,t,n)=>(c(t),e.session.pack?[e.run((0,a.createPackedMatmulProgramInfoLoader)(e,t,n),t)]:[e.run(l(t,n),t)]),t.parseMatMulAttributes=e=>(0,s.parseInternalActivationAttributes)(e.attributes);const u=(e,t)=>({name:"MatMul",inputNames:e?["A","B","Bias"]:["A","B"],inputTypes:e?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:t});function l(e,t){const n=u(e.length>2,t.activationCacheKey);return Object.assign(Object.assign({},n),{get:()=>function(e,t,n){const a=t[0].dims,u=t[1].dims,l=r.BroadcastUtil.calcShape(a,u,!0);if(!l)throw new Error("Can't use matmul on the given tensors");const c=(0,o.getCoordsDataType)(l.length),h=(0,o.getGlChannels)(),{activationFunction:p,applyActivation:f}=(0,s.getActivationSnippet)(n),g=t.length>2,m=g?"value += getBiasForMatmul();":"",b=g?`${d(c,h,t[2].dims,l,!1)}`:"",y=l.length,v=a.length,w=u.length,S=`\n ${p}\n ${b}\n float process(int indices[${y}]) {\n int a[${v}];\n int b[${w}];\n bcastMatmulIndices_A(indices, a);\n bcastMatmulIndices_B(indices, b);\n\n float value;\n for (int k=0; k<${a[a.length-1]}; ++k) {\n a[${v-1}] = k;\n b[${w-2}] = k;\n value += _A(a) * _B(b);\n }\n ${m}\n ${f}\n return value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:l,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:S})}(n,e,t)})}t.createMatmulProgramInfoLoader=l;const c=e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.");if("float32"!==e[0].type&&"float64"!==e[0].type||"float32"!==e[1].type&&"float64"!==e[1].type)throw new Error("inputs should be float type");if(e[0].type!==e[1].type)throw new Error("inputs types should match")};function d(e,t,n,i,o){let s="";const a=n.length,u=i.length,l=u-a;s=u<2&&a>0?"coords":n.map(((e,n)=>`coords.${t[n+l]}`)).join(", ");const c=r.BroadcastUtil.getBroadcastDims(n,i).map((e=>`coords.${t[e+l]} = 0;`)).join("\n");let d="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(d="vec4(outputValue.x)"),o?`\nvec4 getBiasForMatmul() {\n ${e} coords = getOutputCoords();\n ${c}\n vec4 outputValue = getBias(${s});\n return ${d};\n}`:`\nfloat getBiasForMatmul() {\n ${e} coords = getOutputCoords();\n ${c}\n return getBias(coords.x);\n}`}t.getBiasForMatmul=d},9:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPackProgramInfoLoader=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614),a={name:"pack",inputNames:["A"],inputTypes:[i.TextureType.unpackedReversed]};t.createPackProgramInfoLoader=(e,t)=>Object.assign(Object.assign({},a),{get:()=>((e,t)=>{const n=(0,r.getGlsl)(e.session.backend.glContext.version),u=t.dims,l=u.length,c=t.dims.length,d=(0,o.getCoordsDataType)(c),h=(0,s.getChannels)("rc",c),p=(f=c,g=h,m=u[u.length-2],b=u[u.length-1],0===f||1===f?"":`\n int r = ${g[f-2]};\n int c = ${g[f-1]};\n int rp1 = ${g[f-2]} + 1;\n int cp1 = ${g[f-1]} + 1;\n bool rEdge = rp1 >= ${b};\n bool cEdge = cp1 >= ${m};\n `);var f,g,m,b;let y;y=0===l?[1,1]:1===l?[u[0],1]:[u[c-1],u[c-2]];const v=function(e,t,n){if(0===e)return"false";if(1===e)return`rc > ${t[0]}`;let r="";for(let i=e-2;i<e;i++)r+=`${n[i]} >= ${t[i-e+2]}`,i<e-1&&(r+="||");return r}(c,y,h),w=function(e,t){const n=e.length;if(0===n)return"getA(), 0, 0, 0";if(1===n)return`getA(rc),\n rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),\n 0, 0`;let r="";if(n>2)for(let e=0;e<n-2;++e)r+=`${t[e]},`;return`getA(${r}r, c),\n rEdge ? 0. : getA(${r}rp1, c),\n cEdge ? 0. : getA(${r}r, cp1),\n rEdge || cEdge ? 0. : getA(${r}rp1, cp1)`}(u,h),S=`\n void main() {\n ${d} rc = getOutputCoords();\n\n if(${v}) {\n ${n.output} = vec4(0);\n } else {\n ${p}\n\n ${n.output} = vec4(${w});\n }\n }\n `;return Object.assign(Object.assign({},a),{hasMain:!0,output:{dims:t.dims,type:t.type,textureType:i.TextureType.packed},shaderSource:S})})(e,t)})},5614:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unpackFromChannel=t.getChannels=t.getVecChannels=void 0;const r=n(432);function i(e,t){return(0,r.getGlChannels)(t).map((t=>`${e}.${t}`))}t.getVecChannels=i,t.getChannels=function(e,t){return 1===t?[e]:i(e,t)},t.unpackFromChannel=function(){return"\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "}},5565:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parsePadAttributesV11=t.padV11=t.parsePadAttributesV2=t.padV2=void 0;const r=n(4910),i=n(7273),o=n(6757),s=n(5639),a={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};t.padV2=(e,t,n)=>(c(t),[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>l(e,t[0],n)}),t)]),t.parsePadAttributesV2=e=>{const t=e.attributes.getString("mode","constant"),n=e.attributes.getFloat("value",0),i=e.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:t,value:n,pads:i})},t.padV11=(e,n,r)=>{d(n);const i=u(e,n,r);return(0,t.padV2)(e,[n[0]],i)},t.parsePadAttributesV11=e=>e.attributes.getString("mode","constant");const u=(e,t,n)=>{if(!e.session.isInitializer(t[1].dataId)||t.length>=3&&!e.session.isInitializer(t[2].dataId))throw new Error("dynamic pad attributes are not allowed");const i=Array.from(t[1].integerData),o=t.length>=3?t[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:i,value:o})},l=(e,t,n)=>{const r=i.ShapeUtil.padShape(t.dims.slice(),n.pads),o=r.length,a=`\n ${h(e,t,n)}\n float process(int[${o}] indices) {\n return padA(indices);\n }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:r,type:t.type,textureType:s.TextureType.unpacked},shaderSource:a}},c=e=>{if(!e||1!==e.length)throw new Error("Pad requires 1 input");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")},d=e=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==e[1].type)throw new Error("Invalid input type.");if(e.length>=3&&"string"===e[2].type)throw new Error("Invalid input type.")},h=(e,t,n)=>{const r=(0,o.getGlsl)(e.session.backend.glContext.version),[a,u]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),l=i.ShapeUtil.computeStrides(t.dims);switch(n.mode){case"constant":return p(r,t.dims,l,a,u,n.pads,n.value);case"reflect":return f(r,t.dims,l,a,u,n.pads);case"edge":return g(r,t.dims,l,a,u,n.pads);default:throw new Error("Invalid mode")}},p=(e,t,n,r,i,o,s)=>{const a=t.length;let u="";for(let e=a-1;e>=0;--e)u+=`\n k = m[${e}] - ${o[e]};\n if (k < 0) return constant;\n if (k >= ${t[e]}) return constant;\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${a}]) {\n const float constant = float(${s});\n int offset = 0;\n int k = 0;\n ${u}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `},f=(e,t,n,r,i,o)=>{const s=t.length;let a="";for(let e=s-1;e>=0;--e)a+=`\n k = m[${e}] - ${o[e]};\n if (k < 0) { k = -k; }\n {\n const int _2n_1 = ${2*(t[e]-1)};\n k = int( mod( float(k), float(_2n_1) ) ) ;\n if(k >= ${t[e]}) { k = _2n_1 - k; }\n }\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `},g=(e,t,n,r,i,o)=>{const s=t.length;let a="";for(let e=s-1;e>=0;--e)a+=`\n k = m[${e}] - ${o[e]};\n if (k < 0) k = 0;\n if (k >= ${t[e]}) k = ${t[e]-1};\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `}},2834:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.globalMaxPool=t.parseMaxPoolAttributes=t.maxPool=t.parseGlobalAveragePoolAttributes=t.globalAveragePool=t.parseAveragePoolAttributes=t.averagePool=void 0;const r=n(4910),i=n(7273),o=n(5639);t.averagePool=(e,t,n)=>{d(t);const r={name:"AveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[e.run(Object.assign(Object.assign({},r),{get:()=>s(t,r,!1,n)}),t)]},t.parseAveragePoolAttributes=e=>{const t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=0!==e.attributes.getInt("count_include_pad",0),o=e.attributes.getInts("kernel_shape"),s=e.attributes.getInts("strides",[]),a=e.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:t,ceilMode:n,countIncludePad:i,kernelShape:o,strides:s,pads:a})};const s=(e,t,n,r)=>{const[s,a]=u(e,r,n),l=i.ShapeUtil.size(s.kernelShape);let c="";s.countIncludePad?c+=`value /= float(${l});`:c+=`value /= float(${l} - pad);`;const d=`\n ${h(e[0].dims,s,"value += _X(x);",c,"0.0")}\n `;return Object.assign(Object.assign({},t),{output:{dims:a,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:d})};t.globalAveragePool=(e,t,n)=>{d(t);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[e.run(Object.assign(Object.assign({},r),{get:()=>s(t,r,!0,n)}),t)]},t.parseGlobalAveragePoolAttributes=e=>{const t=0!==e.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:t,kernelShape:[],strides:[],pads:[]})},t.maxPool=(e,t,n)=>{d(t);const r={name:"MaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[e.run(Object.assign(Object.assign({},r),{get:()=>a(t,r,!1,n)}),t)]},t.parseMaxPoolAttributes=e=>{const t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=e.attributes.getInts("kernel_shape"),o=e.attributes.getInts("strides",[]),s=e.attributes.getInts("pads",[]),a=e.attributes.getInt("storage_order",0),u=e.attributes.getInts("dilations",[]);if(0!==a)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:t,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:o,pads:s,storageOrder:a,dilations:u})};const a=(e,t,n,r)=>{const[i,s]=u(e,r,n),a=`\n ${h(e[0].dims,i,"\n value = max(_X(x), value);\n ","","-1e5")}\n `;return Object.assign(Object.assign({},t),{output:{dims:s,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:a})},u=(e,t,n)=>{const r=e[0].dims.slice(),o=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),a=t.strides.slice(),u=o?t.dilations.slice():[],l=t.pads.slice();i.PoolConvUtil.adjustPoolAttributes(n,r,s,a,u,l);const c=i.PoolConvUtil.computePoolOutputShape(n,r,a,u,s,l,t.autoPad),d=Object.assign({},t);return o?Object.assign(d,{kernelShape:s,strides:a,pads:l,dilations:u,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:s,strides:a,pads:l,cacheKey:t.cacheKey}),[d,c]},l={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},c={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};t.globalMaxPool=(e,t)=>(d(t),[e.run(Object.assign(Object.assign({},c),{get:()=>a(t,c,!0,l)}),t)]);const d=e=>{if(!e||1!==e.length)throw new Error("Pool ops requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")},h=(e,t,n,r,o)=>{const s=e.length;if(t.kernelShape.length<=2){const i=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],u=t.pads[t.pads.length/2-1],l=t.pads[t.pads.length-1],c=e[s-1];let d="",h="",p="";if(d=u+l!==0?`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n if (x[${s} - 1] < 0 || x[${s} - 1] >= ${c}) {\n pad++;\n continue;\n }\n ${n}\n }`:`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n ${n}\n }`,2===t.kernelShape.length){const n=t.kernelShape[t.kernelShape.length-2],r=t.strides[t.strides.length-2],o=t.pads[t.pads.length/2-2],a=t.pads[t.pads.length-2],u=e[s-2];h=o+a!==0?`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n if (x[${s} - 2] < 0 || x[${s} - 2] >= ${u}) {\n pad+= ${i};\n continue;\n }\n `:`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n `,p="\n }\n "}return`\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n\n float value = ${o};\n int pad = 0;\n ${h}\n ${d}\n ${p}\n ${r}\n return value;\n }\n `}{const a=i.ShapeUtil.size(t.kernelShape),u=i.ShapeUtil.computeStrides(t.kernelShape),l=u.length,c=t.pads.length,d=f(l),h=p(e,"inputDims"),g=p(t.pads,"pads"),m=p(u,"kernelStrides"),b=p(t.strides,"strides");let y="";return y=t.pads.reduce(((e,t)=>e+t))?`\n if (x[j] >= inputDims[j] || x[j] < 0) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n ${n}\n }`:`\n }\n ${n}\n `,`\n ${d}\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n int offset[${l}];\n int pads[${c}];\n int inputDims[${s}];\n int kernelStrides[${l}];\n int strides[${l}];\n ${g}\n ${h}\n ${b}\n ${m}\n\n float value = ${o};\n int pad = 0;\n bool isPad = false;\n for (int i = 0; i < ${a}; i++) {\n offsetToIndices(i, kernelStrides, offset);\n isPad = false;\n for (int j = ${s} - ${l}; j < ${s}; j++) {\n x[j] = indices[j] * strides[j - ${s} + ${l}]\n + offset[j - ${s} + ${l}] - pads[j - 2];\n ${y}\n }\n ${r}\n\n return value;\n }\n `}},p=(e,t)=>{let n="";for(let r=0;r<e.length;r++)n+=`\n ${t}[${r}] = ${e[r]};\n `;return n},f=e=>`\n void offsetToIndices(int offset, int[${e}] strides, out int[${e}] indices) {\n if (${e} == 0) {\n return;\n }\n for (int i = 0; i < ${e} - 1; ++i) {\n indices[i] = offset / strides[i];\n offset -= indices[i] * strides[i];\n }\n indices[${e} - 1] = offset;\n }`},1010:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reduceLogSumSquare=t.reduceLogSum=t.reduceProd=t.reduceMin=t.reduceMax=t.reduceMean=t.reduceSum=t.parseReduceAttributes=void 0;const r=n(4910),i=n(6145),o=n(7273),s=n(5639),a=(e,t,n,r,i)=>{l(t);const o={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[e.run(Object.assign(Object.assign({},o),{cacheHint:n.cacheKey,get:()=>u(e,t,n,r,i,o)}),t)]};t.parseReduceAttributes=e=>{const t=e.attributes.getInts("axes",[]),n=1===e.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:t,keepDims:n})};const u=(e,t,n,r,i,a)=>{const u=[],l=t[0].dims.length||1,c=[],d=o.ShapeUtil.normalizeAxes(n.axes,t[0].dims.length),h=i(t,d);let p=h[1];for(let e=0;e<t[0].dims.length;e++)d.indexOf(e)>=0||0===d.length?(n.keepDims&&u.push(1),p=`\n for(int j${e} = 0; j${e} < ${t[0].dims[e]}; j${e}++) {\n inputIdx[${e}] = j${e};\n ${p}\n }`):(c.push(`inputIdx[${e}] = outputIdx[${u.length}];`),u.push(t[0].dims[e]));const f=`\n float process(int outputIdx[${u.length||1}]) {\n float value; // final result\n int inputIdx[${l}]; // addressing input data\n ${c.join("\n")}\n ${h[0]} // init ops for reduce max/min\n ${p}\n ${h[2]} // final computation for reduce mean\n return value;\n }`;return Object.assign(Object.assign({},a),{output:{dims:u,type:t[0].type,textureType:s.TextureType.unpacked},shaderSource:f})},l=e=>{if(!e||1!==e.length)throw new Error("Reduce op requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.")};t.reduceSum=(e,t,n)=>a(e,t,n,"ReduceSum",(()=>["value = 0.0;","value += _A(inputIdx);",""])),t.reduceMean=(e,t,n)=>a(e,t,n,"ReduceMean",((e,t)=>{let n=1;for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&(n*=e[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]})),t.reduceMax=(e,t,n)=>a(e,t,n,"ReduceMax",((e,t)=>{const n=[];for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]})),t.reduceMin=(e,t,n)=>a(e,t,n,"ReduceMin",((e,t)=>{const n=[];for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]})),t.reduceProd=(e,t,n)=>a(e,t,n,"ReduceProd",(()=>["value = 1.0;","value *= _A(inputIdx);",""])),t.reduceLogSum=(e,t,n)=>a(e,t,n,"ReduceLogSum",(()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"])),t.reduceLogSumSquare=(e,t,n)=>a(e,t,n,"ReduceLogSumSquare",(()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""]))},7379:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isReshapeCheap=t.processDims3D=t.createPackedReshape3DProgramInfoLoader=void 0;const r=n(7273),i=n(6757),o=n(5639),s=n(5614);t.createPackedReshape3DProgramInfoLoader=(e,t,n)=>{const a=(e=>({name:"Reshape (packed)",inputTypes:[o.TextureType.packed],inputNames:["A"],cacheHint:`${e}`}))(n);return Object.assign(Object.assign({},a),{get:()=>((e,t,n,a)=>{const u=t.dims,l=a;let c="";for(let e=0;e<4;e++){let t="";switch(e){case 0:t="outputCoords = rc;";break;case 1:t="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:t="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:t="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}c+=`\n ${t}\n ${e>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n int flattenedIndex = getFlattenedIndex(outputCoords);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n ${e>0?"}":""}\n `}const d=(0,i.getGlsl)(e.session.backend.glContext.version),h=`\n ${function(e){const t=r.ShapeUtil.computeStrides(e),n=["b","r","c"],i="index";return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${t.map(((e,r)=>`int ${n[r]} = ${i} / ${e}; ${r===t.length-1?`int ${n[r+1]} = ${i} - ${n[r]} * ${e}`:`index -= ${n[r]} * ${e}`};`)).join("")}\n return ivec3(b, r, c);\n }\n `}(u)}\n ${function(e){const t=r.ShapeUtil.computeStrides(e);return`\n int getFlattenedIndex(ivec3 coords) {\n // reverse y, z order\n return coords.x * ${t[0]} + coords.z * ${t[1]} + coords.y;\n }\n`}(l)}\n ${(0,s.unpackFromChannel)()}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.0);\n\n ivec3 outputCoords;\n int rows = ${l[2]};\n int cols = ${l[1]};\n\n ${c}\n ${d.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:l,type:t.type,textureType:o.TextureType.packed},shaderSource:h,hasMain:!0})})(e,t,a,n)})},t.processDims3D=function(e){if(0===e.length)return[1,1,1];let t=1;for(let n=0;n<e.length-2;++n)t*=e[n];return[t,e.length>1?e[e.length-2]:1,e[e.length-1]]},t.isReshapeCheap=function(e,t){let n=!1;return n=0===e.length||0===t.length||(e.length<2||t.length<2?e[e.length-1]===t[t.length-1]:e[e.length-1]===t[t.length-1]&&e[e.length-2]===t[t.length-2]),n}},8126:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reshape=void 0;const r=n(7273);t.reshape=(e,t)=>{const n=r.ShapeUtil.calculateReshapedDims(t[0].dims,t[1].integerData);return e.session.pack?[e.reshapePacked(t[0],n)]:[e.reshapeUnpacked(t[0],n)]}},2801:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseResizeAttributesV11=t.parseResizeAttributesV10=t.resize=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614),a=n(3980),u={name:"Resize",inputNames:["A"],inputTypes:[i.TextureType.packed]};t.resize=(e,t,n)=>((0,a.validateInputs)(t,n),[e.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>l(e,t,n)}),t)]),t.parseResizeAttributesV10=e=>(0,a.parseUpsampleAttributes)(e,10),t.parseResizeAttributesV11=e=>(0,a.parseUpsampleAttributes)(e,11);const l=(e,t,n)=>{const a=(0,r.getGlsl)(e.session.backend.glContext.version),[l,d]=c(t,n);if(l.every((e=>1===e))&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},u),{output:{dims:d,type:t[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:`void main() {\n vec4 v = ${a.texture2D}(X, TexCoords);\n ${a.output} = v;\n }`});const h=d.length;if(h<2)throw new Error(`output dimension should be at least 2, but got ${h}`);const p=d[h-2],f=d[h-1],g=t[0].dims;if(h!==g.length)throw new Error(`output dimension should match input ${g.length}, but got ${h}`);const m=g[h-2],b=g[h-1],y=l[h-2],v=l[h-1];let w="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":w="\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n ";break;case"half_pixel":w="\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n ";break;case"pytorch_half_pixel":w=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 fcoords = vec4(coords);\n return vec4(\n ${f}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n ${f}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n );\n }\n `;break;case"align_corners":w=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 resized = vec4(${f}.0 - 1.0, ${p}.0 - 1.0, ${f}.0 - 1.0,\n ${p}.0 - 1.0);\n vec4 original = vec4(${b}.0 - 1.0, ${m}.0 - 1.0, ${b}.0 - 1.0,\n ${m}.0 - 1.0);\n vec4 new_scale = original / resized;\n return vec4(coords) * new_scale;\n }\n `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}const S=(0,o.getCoordsDataType)(h),_=`\n const vec2 inputWH = vec2(${m}.0, ${b}.0);\n const vec4 scaleWHWH = vec4(float(${y}), float(${v}), float(${y}), float(${v}));\n ${(0,s.unpackFromChannel)()}\n ${w}\n float getAValue(int x10, int r, int c, int d) {\n return getChannel(getA(x10, r, c, d), vec2(c, d));\n }\n void main() {\n ${S} rc = getOutputCoords();\n\n int batch = rc[0];\n int depth = rc[1];\n\n // retrieve the 4 coordinates that is used in the 4 packed output values.\n ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n // calculate the source index in fraction\n vec4 sourceFrac = getSourceFracIndex(coords);\n\n // get the lower and upper bound of the 4 values that will be packed into one texel.\n ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n bool hasNextRow = rc.w < ${p-1};\n bool hasNextCol = rc.z < ${f-1};\n\n // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n vec4 topLeft = vec4(\n getAValue(batch, depth, x00.x, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n vec4 topRight = vec4(\n getAValue(batch, depth, x00.x, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n vec4 bottomLeft = vec4(\n getAValue(batch, depth, x00.z, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n vec4 bottomRight = vec4(\n getAValue(batch, depth, x00.z, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n // calculate the interpolation fraction on u and v direction\n vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n ${a.output} = vec4(newValue);\n }\n `;return Object.assign(Object.assign({},u),{output:{dims:d,type:t[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:_})},c=(e,t)=>{const n=e[0].dims;let r,i=t.scales;if(0===i.length){const o=e[t.scalesInputIdx];if(o&&0!==o.size){if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=d(o,t.mode,t.isResize)}else{const o=e[t.sizesInputIdx];if(!o||0===o.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(o.integerData),i=h(r,n,t.mode,t.isResize)}}else if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const o=r||n.map(((e,t)=>Math.floor(e*i[t])));return[i,o]},d=(e,t,n)=>{const r=Array.from(e.floatData);return(0,a.scalesValidation)(r,t,n),r},h=(e,t,n,r)=>{const i=t.length,o=new Array(i);for(let n=0,r=i;n<r;n++)if(0===t[n]){if(0!==e[n])throw new Error("Input dim is zero but required output dim is non-zero.");o[n]=1}else o[n]=e[n]/t[n];return(0,a.scalesValidation)(o,n,r),o}},565:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shape=void 0;const r=n(9240);t.shape=(e,t)=>(i(t),[new r.Tensor([t[0].dims.length],"int32",void 0,void 0,new Int32Array(t[0].dims))]);const i=e=>{if(!e||1!==e.length)throw new Error("Shape requires 1 input.")}},2444:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sliceV10=t.parseSliceAttributes=t.slice=void 0;const r=n(4910),i=n(6145),o=n(7273),s=n(5639),a={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};t.slice=(e,t,n)=>(l(t),[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(e,t[0],n)}),t)]),t.parseSliceAttributes=e=>{const t=e.attributes.getInts("starts"),n=e.attributes.getInts("ends"),i=e.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:t,ends:n,axes:i})};const u=(e,t,n)=>{const r=0===n.axes.length?t.dims.slice(0).map(((e,t)=>t)):n.axes,i=o.ShapeUtil.normalizeAxes(r,t.dims.length),u=n.starts.map(((e,n)=>e>t.dims[i[n]]-1?t.dims[i[n]]:o.ShapeUtil.normalizeAxis(e,t.dims[i[n]]))),l=n.ends.map(((e,n)=>e>t.dims[i[n]]-1?t.dims[i[n]]:o.ShapeUtil.normalizeAxis(e,t.dims[i[n]]))),c=t.dims.slice(),d=[];for(let e=0;e<i.length;e++)c[i[e]]=l[e]-u[e],u[e]>0&&d.push(`outputIdx[${i[e]}] += ${u[e]};`);const h=`\n float process(int outputIdx[${c.length}]) {\n ${d.join("\n ")}\n return _A(outputIdx);\n }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:t.type,textureType:s.TextureType.unpacked},shaderSource:h})},l=e=>{if(!e||1!==e.length)throw new Error("Slice requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.")};t.sliceV10=(e,t)=>{d(t);const n=c(e,t);return[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(e,t[0],n)}),[t[0]])]};const c=(e,t)=>{if(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)||t.length>=4&&!e.session.isInitializer(t[3].dataId)||t.length>=5&&!e.session.isInitializer(t[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(t.length>=5&&t[4].integerData.some((e=>1!==e)))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(t[1].integerData),r=Array.from(t[2].integerData),i=t.length>=4?Array.from(t[3].integerData):[];return{starts:n,ends:r,axes:i,cacheKey:`${i};${n};${r}`}},d=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if("int32"!==e[1].type||1!==e[1].dims.length)throw new Error("Invalid input type.");if("int32"!==e[2].type||1!==e[2].dims.length)throw new Error("Invalid input type.");if(e.length>=4&&("int32"!==e[3].type||1!==e[3].dims.length))throw new Error("Invalid input type.");if(e.length>=5&&("int32"!==e[4].type||1!==e[4].dims.length))throw new Error("Invalid input type.")}},815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.softmaxV13=t.parseSoftmaxAttributesV13=t.parseSoftmaxAttributes=t.softmax=void 0;const r=n(4910),i=n(7273),o=n(6757),s=n(5639),a=n(5707),u={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},l={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},c={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};t.softmax=(e,t,n)=>{g(t);const r=t[0].dims.slice(),o=i.ShapeUtil.normalizeAxis(n.axis,r.length),s=i.ShapeUtil.sizeToDimension(r,o),a=i.ShapeUtil.sizeFromDimension(r,o);return d(e,t,n,s,a)},t.parseSoftmaxAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",1)}),t.parseSoftmaxAttributesV13=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",-1)}),t.softmaxV13=(e,t,n)=>{g(t);const o=t[0].dims.slice(),s=i.ShapeUtil.normalizeAxis(n.axis,o.length),u=o.length,l=s!==u-1,c=[];let h,p=[],f=[];l&&(p=Array.from({length:u}).map(((e,t)=>t)),p[s]=u-1,p[u-1]=s,p.map((e=>c.push(o[e]))),h=(0,r.createAttributeWithCacheKey)({perm:p}),f=(0,a.transpose)(e,t,h));const m=l?i.ShapeUtil.sizeToDimension(c,u-1):i.ShapeUtil.sizeToDimension(o,u-1),b=l?i.ShapeUtil.sizeFromDimension(c,u-1):i.ShapeUtil.sizeFromDimension(o,u-1),y=d(e,l?f:t,n,m,b);return l?(0,a.transpose)(e,y,h):y};const d=(e,t,n,r,i)=>{const o=h(e,t[0],r,i,[r]),s=e.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>o}),t),a=p(e,t[0],r,i,o.output.dims,[r]),d=e.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>a}),[t[0],s]),g=f(e,t[0],r,i,o.output.dims,a.output.dims);return[e.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>g}),[t[0],s,d])]},h=(e,t,n,r,i)=>{const[a,l]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),c=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const d=(0,o.getGlsl)(e.session.backend.glContext.version),h=`\n float process(int[${c}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float max = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset, ${a},\n ${l} )));\n for(int i=1; i<${r}; ++i)\n {\n float current = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${a}, ${l})));\n if(current > max)\n max = current;\n }\n\n return max;\n }`;return Object.assign(Object.assign({},u),{output:{dims:i,type:t.type,textureType:s.TextureType.unpacked},shaderSource:h})},p=(e,t,n,r,i,a)=>{const[u,c]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),d=a.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==a.length)throw new Error("Dimensionality of the output should be 1");if(a[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const h=`\n float process(int[${d}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float norm_factor = 0.0;\n float max = _Max(indices);\n for(int i=0; i<${r}; ++i)\n {\n norm_factor += exp(getColorAsFloat(${(0,o.getGlsl)(e.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${u}, ${c}))) - max);\n }\n\n return norm_factor;\n }`;return Object.assign(Object.assign({},l),{output:{dims:a,type:t.type,textureType:s.TextureType.unpacked},shaderSource:h})},f=(e,t,n,r,i,o)=>{const[a,u]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),l=t.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length||1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n||o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const d=`\n float process(int[${l}] indices) {\n\n // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n int offset = coordsToOffset(TexCoords, ${a}, ${u});\n\n //determine the logical row for this index\n int logical_row_index[1];\n logical_row_index[0] = offset / ${r};\n\n float norm_factor = _Norm(logical_row_index);\n\n // avoid possible division by 0\n // if norm_facor is 0, all elements are zero\n // if so, return 0\n if(norm_factor == 0.0)\n return 0.0;\n\n return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n }`;return Object.assign(Object.assign({},c),{output:{dims:t.dims,type:t.type,textureType:s.TextureType.unpacked},shaderSource:d})},g=e=>{if(!e||1!==e.length)throw new Error("Softmax requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type")}},564:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseSplitAttributes=t.split=void 0;const r=n(4910),i=n(7273),o=n(5639),s={name:"Split",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};t.split=(e,t,n)=>{l(t);const r=i.ShapeUtil.normalizeAxis(n.axis,t[0].dims.length),o=a(e,t,r,n),c=[];for(let i=0;i<o;++i)c.push(e.run(Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey};${i}`,get:()=>u(e,t[0],n,r,i)}),t));return c},t.parseSplitAttributes=e=>{const t=e.attributes.getInt("axis",0),n=e.attributes.getInts("split",[]),i=e.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:t,split:n,numOutputs:i})};const a=(e,t,n,r)=>{const[,o]=i.SplitUtil.splitShape(t[0].dims,n,r.split,r.numOutputs);return o.length},u=(e,t,n,r,a)=>{const[u,l]=i.SplitUtil.splitShape(t.dims,r,n.split,n.numOutputs),c=l[a],d=u[a],h=`\n float process(int indices[${d.length}]) {\n indices[${r}] += ${c};\n return _A(indices);\n }\n `;return Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey}:${a}`,output:{dims:d,type:t.type,textureType:o.TextureType.unpacked},shaderSource:h})},l=e=>{if(!e||1!==e.length)throw new Error("Split requires one input.");if("int8"!==e[0].type&&"uint8"!==e[0].type&&"int16"!==e[0].type&&"uint16"!==e[0].type&&"int32"!==e[0].type&&"uint32"!==e[0].type&&"float32"!==e[0].type&&"float64"!==e[0].type&&"bool"!==e[0].type)throw new Error("Invalid input type.")}},5416:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseSqueezeAttributes=t.squeezeV13=t.squeeze=void 0;const r=n(7273);t.squeeze=(e,t,n)=>{i(t);const o=r.ShapeUtil.squeezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],o)]},t.squeezeV13=(e,n)=>(o(n),(0,t.squeeze)(e,[n[0]],Array.from(n[1].integerData))),t.parseSqueezeAttributes=e=>e.attributes.getInts("axes");const i=e=>{if(!e||1!==e.length)throw new Error("Squeeze requires 1 input.");if("string"===e[0].type)throw new Error("invalid input tensor types.")},o=e=>{if(!e||2!==e.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==e[1].type)throw new Error("Invalid input type.")}},1240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sum=void 0;const r=n(6757),i=n(5639);t.sum=(e,t)=>{s(t);const n={name:"Sum",inputNames:t.map(((e,t)=>`X${t}`)),inputTypes:new Array(t.length).fill(i.TextureType.unpacked)};return[e.run(Object.assign(Object.assign({},n),{get:()=>o(e,t,n)}),t)]};const o=(e,t,n)=>{const o=(0,r.getGlsl)(e.session.backend.glContext.version),s=t[0].dims.slice(),a=`\n void main() {\n vec4 result = ${t.map(((e,t)=>`${o.texture2D}(X${t},TexCoords)`)).join(" + ")};\n ${o.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:s,type:t[0].type,textureType:i.TextureType.unpacked},hasMain:!0,shaderSource:a})},s=e=>{if(!e||0===e.length)throw new Error("Sum requires inputs.");const t=e[0].dims.length;for(let n=1;n<e.length;n++){if(t!==e[n].dims.length)throw new Error("Input shapes are mismatched.");for(let r=0;r<t;r++)if(e[0].dims[r]!==e[n].dims[r])throw new Error("Input shapes are not matched.")}if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.");for(let t=1;t<e.length;t++)if(e[0].type!==e[t].type)throw new Error("Input types are not matched.")}},5944:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tile=void 0;const r=n(6145),i=n(5639);t.tile=(e,t)=>{s(t);const n={name:"Tile",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};return[e.run(Object.assign(Object.assign({},n),{get:()=>o(e,t,n)}),t)]};const o=(e,t,n)=>{const r=t[0].dims.slice(),o=new Array(r.length),s=[];for(let e=0;e<r.length;e++)o[e]=r[e]*t[1].numberData[e],s.push(`inputIdx[${e}] = int(mod(float(outputIdx[${e}]), ${r[e]}.));`);const a=o.length,u=`\n float process(int outputIdx[${a}]) {\n int inputIdx[${a}];\n ${s.join("\n")}\n return _A(inputIdx);\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:o,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:u})},s=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 input.");if(1!==e[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(e[1].dims[0]!==e[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.");if("int32"!==e[1].type&&"int16"!==e[1].type)throw new Error("Invalid repeat type.")}},5707:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseTransposeAttributes=t.transpose=void 0;const r=n(4910),i=n(7273),o=n(5639),s={name:"Transpose",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};t.transpose=(e,t,n)=>(d(t),[e.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(e,t[0],n.perm)}),t)]),t.parseTransposeAttributes=e=>(0,r.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const a=(e,t,n)=>{const r=t.dims;n=u(r,n);const i=l(r,n),a=r.length,d=`\n ${c("perm",n,a)}\n float process(int indices[${a}]) {\n int a[${a}];\n perm(a, indices);\n return _A(a);\n }`;return Object.assign(Object.assign({},s),{output:{dims:i,type:t.type,textureType:o.TextureType.unpacked},shaderSource:d})},u=(e,t)=>(t&&t.length!==e.length&&(t=[...e.keys()].reverse()),t),l=(e,t)=>(t=u(e,t),i.ShapeUtil.sortBasedOnPerm(e,t)),c=(e,t,n)=>{const r=[];r.push(`void ${e}(out int a[${n}], int src[${n}]) {`);for(let e=0;e<n;++e)r.push(`\ta[${t[e]}]=src[${e}];`);return r.push("\t}"),r.join("\n")},d=e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("input should be float tensor")}},2488:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeAsUint8=void 0;const r=n(6757),i=n(5639);t.encodeAsUint8=(e,t)=>{const n=t.shape,o=(0,r.getGlsl)(e.session.backend.glContext.version),s=`\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n highp vec4 encodeAsUint8(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float value = ${o.texture2D}(X,TexCoords).r;\n ${o.output} = encodeAsUint8(value);\n }`,a={name:"Uint8Encode",inputTypes:[i.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:t.tensor.type,textureType:i.TextureType.downloadUint8AsFloat},shaderSource:s,hasMain:!0};return e.executeProgram(a,[t.tensor])}},9087:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tanh=t.tan=t.sqrt=t.sin=t.sigmoid=t.relu=t.not=t.neg=t.log=t.parseLeakyReluAttributes=t.leakyRelu=t.identity=t.floor=t.exp=t.parseEluAttributes=t.elu=t.cos=t.ceil=t.clipV11=t.parseClipAttributes=t.clip=t.atan=t.asin=t.acos=t.abs=t.glslTanh=t.glslTan=t.glslSqrt=t.glslSigmoid=t.glslRelu=t.glslSin=t.glslNot=t.glslNeg=t.glslLog=t.glslLeakyRelu=t.glslIdentity=t.glslClip=t.glslFloor=t.glslExp=t.glslElu=t.glslCos=t.glslCeil=t.glslAtan=t.glslAsin=t.glslAcos=t.glslAbs=void 0;const r=n(4910),i=n(7273),o=n(1997),s=n(6757),a=n(5639);function u(){return A("abs")}function l(){return A("acos")}function c(){return A("asin")}function d(){return A("atan")}function h(){return A("ceil")}function p(){return A("cos")}function f(e){const t="elu";return{body:`\n const float alpha = float(${e});\n\n float ${t}_(float a) {\n return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function g(){return A("exp")}function m(){return A("floor")}function b(e,t){const n="clip";return{body:`\n const float min = float(${e});\n const float max = float(${t});\n\n float ${n}_(float a) {\n return clamp(a, min, max);\n }\n vec4 ${n}_(vec4 v) {\n return clamp(v, min, max);\n }\n `,name:n,type:o.FunctionType.ValueBased}}function y(){const e="indentity";return{body:`\n float ${e}_(float a) {\n return a;\n }\n vec4 ${e}_(vec4 v) {\n return v;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function v(e){const t="leakyRelu";return{body:`\n const float alpha = float(${e});\n\n float ${t}_(float a) {\n return a < 0.0 ? a * alpha : a;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function w(){return A("log")}function S(){const e="neg";return{body:`\n float ${e}_(float a) {\n return -a;\n }\n vec4 ${e}_(vec4 v) {\n return -v;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function _(){const e="not";return{body:`\n float ${e}_(float a) {\n return float( ! bool(a) );\n }\n bool ${e}_(bool a) {\n return !a;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n }\n bvec4 ${e}_(bvec4 v) {\n return bvec4(!v.x, !v.y, !v.z, !v.w);\n }\n `,name:e,type:o.FunctionType.ValueBased}}function T(){return A("sin")}function x(){const e="relu";return{body:`\n float ${e}_(float a) {\n return max( a, 0.0 );\n }\n vec4 ${e}_(vec4 v) {\n return max( v, 0.0 );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function E(){const e="sigmoid";return{body:`\n float ${e}_(float a) {\n return 1.0 / (1.0 + exp(-a));\n }\n vec4 ${e}_(vec4 v) {\n return 1.0 / (1.0 + exp(-v));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function C(){return A("sqrt")}function P(){return A("tan")}function O(){const e="tanh";return{body:`\n float ${e}_(float a) {\n a = clamp(a, -10., 10.);\n a = exp(2.*a);\n return (a - 1.) / (a + 1.);\n }\n vec4 ${e}_(vec4 v) {\n v = clamp(v, -10., 10.);\n v = exp(2.*v);\n return (v - 1.) / (v + 1.);\n }\n `,name:e,type:o.FunctionType.ValueBased}}function A(e){return{body:`\n float ${e}_(float a) {\n return ${e}(a);\n }\n vec4 ${e}_(vec4 v) {\n return ${e}(v);\n }\n `,name:e,type:o.FunctionType.ValueBased}}t.glslAbs=u,t.glslAcos=l,t.glslAsin=c,t.glslAtan=d,t.glslCeil=h,t.glslCos=p,t.glslElu=f,t.glslExp=g,t.glslFloor=m,t.glslClip=b,t.glslIdentity=y,t.glslLeakyRelu=v,t.glslLog=w,t.glslNeg=S,t.glslNot=_,t.glslSin=T,t.glslRelu=x,t.glslSigmoid=E,t.glslSqrt=C,t.glslTan=P,t.glslTanh=O;const k=(e,t,n,r)=>{const i=e.session.pack?a.TextureType.packed:a.TextureType.unpacked,o={name:n.name,inputTypes:[i],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},o),{get:()=>((e,t,n,r)=>{const i=e.session.pack?a.TextureType.packed:a.TextureType.unpacked,o=(0,s.getGlsl)(e.session.backend.glContext.version);return Object.assign(Object.assign({},t),{output:{dims:n.dims,type:n.type,textureType:i},shaderSource:`\n ${r.body}\n void main() {\n vec4 v = ${o.texture2D}(A, TexCoords);\n v = ${r.name}_(v);\n ${o.output} = v;\n }\n `,hasMain:!0})})(e,o,t,n)})};t.abs=(e,t)=>[e.run(k(e,t[0],u()),t)],t.acos=(e,t)=>[e.run(k(e,t[0],l()),t)],t.asin=(e,t)=>[e.run(k(e,t[0],c()),t)],t.atan=(e,t)=>[e.run(k(e,t[0],d()),t)],t.clip=(e,t,n)=>[e.run(k(e,t[0],b(n.min,n.max),n.cacheKey),t)],t.parseClipAttributes=e=>(0,r.createAttributeWithCacheKey)({min:e.attributes.getFloat("min",i.MIN_CLIP),max:e.attributes.getFloat("max",i.MAX_CLIP)}),t.clipV11=(e,n)=>{const r=I(e,n);return(0,t.clip)(e,[n[0]],r)};const I=(e,t)=>{if(t.length>=3&&(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=t.length>=3?t[1].numberData[0]:i.MIN_CLIP,o=t.length>=3?t[2].numberData[0]:i.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:o})};t.ceil=(e,t)=>[e.run(k(e,t[0],h()),t)],t.cos=(e,t)=>[e.run(k(e,t[0],p()),t)],t.elu=(e,t,n)=>[e.run(k(e,t[0],f(n.alpha),n.cacheKey),t)],t.parseEluAttributes=e=>(0,r.createAttributeWithCacheKey)({alpha:e.attributes.getFloat("alpha",1)}),t.exp=(e,t)=>[e.run(k(e,t[0],g()),t)],t.floor=(e,t)=>[e.run(k(e,t[0],m()),t)],t.identity=(e,t)=>[e.run(k(e,t[0],y()),t)],t.leakyRelu=(e,t,n)=>[e.run(k(e,t[0],v(n.alpha),n.cacheKey),t)],t.parseLeakyReluAttributes=e=>(0,r.createAttributeWithCacheKey)({alpha:e.attributes.getFloat("alpha",.01)}),t.log=(e,t)=>[e.run(k(e,t[0],w()),t)],t.neg=(e,t)=>[e.run(k(e,t[0],S()),t)],t.not=(e,t)=>[e.run(k(e,t[0],_()),t)],t.relu=(e,t)=>[e.run(k(e,t[0],x()),t)],t.sigmoid=(e,t)=>[e.run(k(e,t[0],E()),t)],t.sin=(e,t)=>[e.run(k(e,t[0],T()),t)],t.sqrt=(e,t)=>[e.run(k(e,t[0],C()),t)],t.tan=(e,t)=>[e.run(k(e,t[0],P()),t)],t.tanh=(e,t)=>[e.run(k(e,t[0],O()),t)]},540:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createUnpackProgramInfoLoader=t.createUnpackProgramInfo=void 0;const r=n(6757),i=n(5639),o=n(432),s=n(5614),a={name:"unpack",inputNames:["A"],inputTypes:[i.TextureType.packed]};t.createUnpackProgramInfo=(e,t)=>{const n=t.dims.length,u=(0,s.getChannels)("rc",n),l=u.slice(-2),c=(0,o.getCoordsDataType)(n),d=(0,s.unpackFromChannel)(),h=0===t.dims.length?"":function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(n,u),p=n<=1?"rc":`vec2(${l.join(",")})`,f=`\n ${d}\n void main() {\n ${c} rc = getOutputCoords();\n\n // Sample the texture with the coords to get the rgba channel value.\n vec4 packedInput = getA(${h});\n\n ${(0,r.getGlsl)(e.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${p}), 0, 0, 0);\n }\n `;return Object.assign(Object.assign({},a),{hasMain:!0,output:{dims:t.dims,type:t.type,textureType:i.TextureType.unpacked},shaderSource:f})},t.createUnpackProgramInfoLoader=(e,n)=>Object.assign(Object.assign({},a),{get:()=>(0,t.createUnpackProgramInfo)(e,n)})},7862:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseUnsqueezeAttributes=t.unsqueezeV13=t.unsqueeze=void 0;const r=n(7273);t.unsqueeze=(e,t,n)=>{i(t);const o=r.ShapeUtil.unsqueezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],o)]},t.unsqueezeV13=(e,n)=>(o(n),(0,t.unsqueeze)(e,[n[0]],Array.from(n[1].integerData))),t.parseUnsqueezeAttributes=e=>e.attributes.getInts("axes");const i=e=>{if(!e||1!==e.length)throw new Error("Unsqueeze requires 1 input.");if("string"===e[0].type)throw new Error("invalid input tensor types.")},o=e=>{if(!e||2!==e.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==e[1].type)throw new Error("Invalid input type.")}},3980:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scalesValidation=t.validateInputs=t.parseUpsampleAttributes=t.parseUpsampleAttributesV9=t.parseUpsampleAttributesV7=t.upsample=void 0;const r=n(4910),i=n(6757),o=n(5639),s={name:"Upsample",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};t.upsample=(e,n,r)=>((0,t.validateInputs)(n,r),[e.run(Object.assign(Object.assign({},s),{cacheHint:r.cacheKey,get:()=>a(e,n,r)}),n)]),t.parseUpsampleAttributesV7=e=>(0,t.parseUpsampleAttributes)(e,7),t.parseUpsampleAttributesV9=e=>(0,t.parseUpsampleAttributes)(e,9),t.parseUpsampleAttributes=(e,n)=>{const i=n>=10,o=e.attributes.getString("mode","nearest");if("nearest"!==o&&"linear"!==o&&(n<11||"cubic"!==o))throw new Error(`unrecognized mode: ${o}`);let s=[];n<9&&(s=e.attributes.getFloats("scales"),(0,t.scalesValidation)(s,o,i));const a=e.attributes.getFloat("extrapolation_value",0),u=n>10?e.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(u))throw new Error(`coordinate_transform_mode '${u}' is not supported`);const l="tf_crop_and_resize"===u,c=l,d="nearest"===o&&n>=11?e.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(d))throw new Error(`nearest_mode '${d}' is not supported`);const h=e.attributes.getFloat("cubic_coeff_a",-.75),p=0!==e.attributes.getInt("exclude_outside",0);if(p&&"cubic"!==o)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const f=n<11||"nearest"===o&&"asymmetric"===u&&"floor"===d;let g=0,m=0,b=0;return n>10?e.inputs.length>2?(g=1,m=2,b=3):(m=1,b=2):9===n&&(m=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:i,mode:o,scales:s,extrapolationValue:a,coordinateTransformMode:u,useExtrapolation:c,needRoiInput:l,nearestMode:d,cubicCoefficientA:h,excludeOutside:p,useNearest2xOptimization:f,roiInputIdx:g,scalesInputIdx:m,sizesInputIdx:b})};const a=(e,t,n)=>{const r=(0,i.getGlsl)(e.session.backend.glContext.version),[a,u]=e.calculateTextureWidthAndHeight(t[0].dims,o.TextureType.unpacked),l=t[0].dims.map(((e,t)=>Math.floor(e*n.scales[t]))),[c,d]=e.calculateTextureWidthAndHeight(l,o.TextureType.unpacked),h=l.length,p=new Array(h),f=new Array(h);let g=`\n int output_pitches[${h}];\n int input_pitches[${h}];\n `;for(let e=h-1;e>=0;e--)p[e]=e===h-1?1:p[e+1]*l[e+1],f[e]=e===h-1?1:f[e+1]*t[0].dims[e+1],g+=`\n output_pitches[${e}] = ${p[e]};\n input_pitches[${e}] = ${f[e]};\n `;const m=`\n float getInputFloat(int index) {\n vec2 coords = offsetToCoords(index, ${a}, ${u});\n float value = getColorAsFloat(${r.texture2D}(X, coords));\n return value;\n }\n `,b="nearest"===n.mode?`\n ${m}\n float process(int indices[${h}]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int d, m;\n for (int dim = 0; dim < ${h}; ++dim) {\n d = output_index / output_pitches[dim];\n m = output_index - d * output_pitches[dim];\n output_index = m;\n\n if (scales[dim] != 1 && d > 0) {\n int d2 = d / scales[dim];\n m = d - d2 * scales[dim];\n d = d2;\n }\n input_index += input_pitches[dim] * d;\n }\n\n return getInputFloat(input_index);\n }`:4===h?`\n ${m}\n float process(int indices[4]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m / output_pitches[1];\n m = m - index_of_dim1 * output_pitches[1];\n index_of_dim2 = m / output_pitches[2];\n m = m - index_of_dim2 * output_pitches[2];\n index_of_dim3 = m;\n\n int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n index_of_input_dim2 = index_of_dim2 / scales[2];\n y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n index_of_input_dim3 = index_of_dim3 / scales[3];\n x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n input_index = index_of_dim0 * input_pitches[0] +\n index_of_dim1 * input_pitches[1] +\n index_of_input_dim2 * input_pitches[2] +\n index_of_input_dim3;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim2 = false;\n if (index_of_input_dim2 == (${t[0].dims[2]} - 1)) {\n // It's the end in dimension 2\n x01 = x00;\n end_of_dim2 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[2]);\n }\n\n if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n // It's the end in dimension 3\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n }`:`\n ${m}\n float process(int indices[2]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m;\n\n int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n index_of_input_dim0 = index_of_dim0 / scales[0];\n y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n index_of_input_dim1 = index_of_dim1 / scales[1];\n x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim0 = false;\n if (index_of_input_dim0 == (${t[0].dims[0]} - 1)) {\n // It's the end in dimension 0\n x01 = x00;\n end_of_dim0 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[0]);\n }\n\n if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n // It's the end in dimension 1\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n }`;return Object.assign(Object.assign({},s),{output:{dims:l,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:b,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map((e=>Math.ceil(e)))}]})};t.validateInputs=(e,t)=>{if(!e||t.opset<9&&1!==e.length||t.opset>=9&&t.opset<11&&2!==e.length||t.opset>=11&&e.length<2)throw new Error("invalid inputs.");if(t.scales.length>0&&e[0].dims.length!==t.scales.length)throw new Error("Invalid input shape.");if("string"===e[0].type)throw new Error("Invalid input tensor types.")},t.scalesValidation=(e,t,n)=>{if(n){for(const t of e)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(const t of e)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==t&&"cubic"!==t||2===e.length||4===e.length&&1===e[0]&&1===e[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}},2757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgramManager=void 0;const r=n(8453),i=n(1315),o=n(8897),s=n(6757);t.ProgramManager=class{constructor(e,t,n){this.profiler=e,this.glContext=t,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=e.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,(()=>{var r;const o=this.glContext.gl,s=e.program;o.useProgram(s);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(e.attribLocations),this.bindUniforms(e.uniformLocations,null!==(r=e.programInfo.variables)&&void 0!==r?r:[],t)}catch(t){throw i.Logger.error("ProgramManager",e.programInfo.shaderSource),t}this.profiler.event("backend","GlContext.draw()",(()=>{this.glContext.draw()}))}),this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((e=>this.glContext.deleteProgram(e.program)))}build(e,t,n){return this.profiler.event("backend","ProgramManager.build",(()=>{const r=new o.GlslPreprocessor(this.glContext,e,t,n),i=r.preprocess(),s=this.compile(i);return{programInfo:e,program:s,uniformLocations:this.getUniformLocations(s,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(s)}}))}compile(e){if(!this.vertexShader){i.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const e=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(e,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&i.Logger.verbose("ProrgramManager",`FragShader:\n${e}\n`);const t=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,t);return this.glContext.deleteShader(t),n}bindOutput(e){const t=e.width,n=e.height;i.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${t}/${n}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,t,n)}bindAttributes(e){const t=e.position,n=e.textureCoord;this.glContext.setVertexAttributes(t,n),this.attributesBound=!0}bindUniforms(e,t,n){var r;const i=this.glContext.gl;let o=0;for(const{name:s,type:a,location:u,arrayLength:l}of e){const e=null===(r=t.find((e=>e.name===s)))||void 0===r?void 0:r.data;if("sampler2D"!==a&&!e)throw new Error(`variable '${s}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(n[o],u,o),o++;break;case"float":l?i.uniform1fv(u,e):i.uniform1f(u,e);break;case"int":l?i.uniform1iv(u,e):i.uniform1i(u,e);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(e,t,n){this.glContext.bindTextureToUniform(e.texture,n,t)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,t,n){const r=[];if(t)for(const n of t)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(e,n)});if(n)for(const t of n)r.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(e,t.name)}));return r}getUniformLocation(e,t){const n=this.glContext.gl.getUniformLocation(e,t);if(null===n)throw new Error(`Uniform ${t} not found.`);return n}getAttribLocation(e,t){return this.glContext.gl.getAttribLocation(e,t)}}},2171:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLSessionHandler=void 0;const r=n(1315),i=n(5881),o=n(7860),s=n(4110),a=n(2757),u=n(7618),l=n(5243);t.WebGLSessionHandler=class{constructor(e,t){this.backend=e,this.context=t,this.layoutStrategy=new u.PreferLogicalStrategy(e.glContext.maxTextureSize),this.programManager=new a.ProgramManager(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new l.TextureManager(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===e.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new o.WebGLInferenceHandler(this)}onGraphInitialized(e){const t=e.getValues().filter((e=>-1===e.from&&e.tensor)).map((e=>e.tensor.dataId));this.initializers=new Set(t)}isInitializer(e){return!!this.initializers&&this.initializers.has(e)}addInitializer(e){this.initializers.add(e)}getTextureData(e,t){return t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(e,t):this.unpackedTextureDataCache.set(e,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((e=>this.textureManager.releaseTexture(e,!0))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((e=>this.textureManager.releaseTexture(e,!0))),this.unpackedTextureDataCache=new Map}resolve(e,t,n){const r=(0,i.resolveOperator)(e,t,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(e,n):e}}}},9622:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Uint8DataEncoder=t.RGBAFloatDataEncoder=t.RedFloat32DataEncoder=void 0;const r=n(1315);t.RedFloat32DataEncoder=class{constructor(e,t=1){if(1===t)this.internalFormat=e.R32F,this.format=e.RED,this.textureType=e.FLOAT,this.channelSize=t;else{if(4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA32F,this.format=e.RGBA,this.textureType=e.FLOAT,this.channelSize=t}}encode(e,t){let n,i;return e.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(e)),t*this.channelSize>e.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),i=e,n=this.allocate(t*this.channelSize),i.forEach(((e,t)=>n[t]=e))):(i=e,n=i),n}allocate(e){return new Float32Array(4*e)}decode(e,t){return 1===this.channelSize?e.filter(((e,t)=>t%4==0)).subarray(0,t):e.subarray(0,t)}},t.RGBAFloatDataEncoder=class{constructor(e,t=1,n){if(1!==t&&4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.channelSize=t,this.textureType=n||e.FLOAT}encode(e,t){let n=e;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(t),e.forEach(((e,t)=>n[4*t]=e))),n}allocate(e){return new Float32Array(4*e)}decode(e,t){return 1===this.channelSize?e.filter(((e,t)=>t%4==0)).subarray(0,t):e.subarray(0,t)}},t.Uint8DataEncoder=class{constructor(e,t=1){if(this.channelSize=4,1===t)this.internalFormat=e.ALPHA,this.format=e.ALPHA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else{if(4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t}}encode(e,t){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}allocate(e){return new Uint8Array(e*this.channelSize)}decode(e,t){if(e instanceof Uint8Array)return e.subarray(0,t);throw new Error(`Invalid array type: ${e.constructor}`)}}},7618:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getBatchDim=t.sizeToSquarishShape=t.getRowsCols=t.sizeFromShape=t.isInt=t.parseAxisParam=t.squeezeShape=t.PreferLogicalStrategy=t.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(1315),i=n(7273);function o(e,t){const n=[],r=[],i=null!=t&&Array.isArray(t)&&0===t.length,o=null==t||i?null:s(t,e).sort();let a=0;for(let t=0;t<e.length;++t){if(null!=o){if(o[a]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==o[a]||o[a]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),o[a]<=t&&a++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function s(e,t){const n=t.length;return e=null==e?t.map(((e,t)=>t)):[].concat(e),(0,i.assert)(e.every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),(0,i.assert)(e.every(a),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function a(e){return e%1==0}function u(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function l(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}t.AlwaysKeepOriginalSizeStrategy=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){if(0===e.length)return[1,1];const n=this.maxTextureSize;if(t&&void 0!==t.breakAxis){const i=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce(((e,t)=>e*t)),o=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce(((e,t)=>e*t));if(!(i>n||o>n))return[i,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`)}const i=e.reduce(((e,t)=>e*t));let o=Math.floor(Math.sqrt(i));for(;o<n&&o<i&&i%o!=0;o++);if(o>=n||i%o!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${e}`);return[o,i/o]}},t.PreferLogicalStrategy=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){const n=this.computeTexture(e,t);return t&&t.isPacked&&(n[0]/=2,n[1]/=2),t&&t.reverseWH?[n[1],n[0]]:n}computeTexture(e,t){const n=t&&t.isPacked;if(0===e.length)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(t&&void 0!==t.breakAxis){const n=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce(((e,t)=>e*t)),o=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce(((e,t)=>e*t));if(!(n>i||o>i))return[n,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`)}let s=e.slice(0);if(n&&(i*=2,s=s.map(((e,t)=>t>=s.length-2?s[t]%2==0?s[t]:s[t]+1:s[t])),1===s.length&&(s=[2,s[0]])),2!==s.length){const e=o(s);s=e.newShape}const a=u(s);return s.length<=1&&a<=i?[1,a]:2===s.length&&s[0]<=i&&s[1]<=i?s:3===s.length&&s[0]*s[1]<=i&&s[2]<=i?[s[0]*s[1],s[2]]:3===s.length&&s[0]<=i&&s[1]*s[2]<=i?[s[0],s[1]*s[2]]:4===s.length&&s[0]*s[1]*s[2]<=i&&s[3]<=i?[s[0]*s[1]*s[2],s[3]]:4===s.length&&s[0]<=i&&s[1]*s[2]*s[3]<=i?[s[0],s[1]*s[2]*s[3]]:n?l(a/4).map((e=>2*e)):l(a)}},t.squeezeShape=o,t.parseAxisParam=s,t.isInt=a,t.sizeFromShape=u,t.getRowsCols=function(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]},t.sizeToSquarishShape=l,t.getBatchDim=function(e,t=2){return u(e.slice(0,e.length-t))}},3314:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createTextureLayoutFromShape=t.calculateTextureWidthAndHeight=t.createTextureLayoutFromTextureType=void 0;const r=n(7273),i=n(5639);t.createTextureLayoutFromTextureType=(e,n,r)=>{const o=r===i.TextureType.unpacked||r===i.TextureType.unpackedReversed?1:4,s=r===i.TextureType.packed,a=r===i.TextureType.unpackedReversed||r===i.TextureType.packed,u=r===i.TextureType.packedLastDimension?n.length-1:void 0,l=r===i.TextureType.packedLastDimension?n.map(((e,t)=>t===n.length-1?4*e:e)):void 0;return(0,t.createTextureLayoutFromShape)(e,n,o,l,{isPacked:s,reverseWH:a,breakAxis:u})},t.calculateTextureWidthAndHeight=(e,n,r)=>{const i=(0,t.createTextureLayoutFromTextureType)(e,n,r);return[i.width,i.height]},t.createTextureLayoutFromShape=(e,t,n=1,i,o)=>{const s=!(!o||!o.isPacked),[a,u]=e.computeTextureWH(s&&i||t,o),l=t.length;let c=t.slice(0);if(0===l&&(c=[1]),1===n)i=t;else if(s){if(4!==n)throw new Error("a packed texture must be 4-channel");i=t,l>0&&(c[l-1]=Math.ceil(c[l-1]/2)),l>1&&(c[l-2]=Math.ceil(c[l-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:a,height:u,channels:n,isPacked:s,shape:c,strides:r.ShapeUtil.computeStrides(c),unpackedShape:i,reversedWH:o&&o.reverseWH}}},5243:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TextureManager=void 0;const r=n(1315);t.TextureManager=class{constructor(e,t,n,r){this.glContext=e,this.layoutStrategy=t,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,t,n,i){const o=this.toEncoderType(e),s=this.glContext.getEncoder(o,t.channels||1,i);if(t.isPacked&&1===i)throw new Error("not implemented");const a=t.width,u=t.height;let l,c;if(this.config.reuseTextures){l=`${a}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`,c=this.inUseTextures.get(l),c||(c=[],this.inUseTextures.set(l,c));const t=this.idleTextures.get(l);if(t&&t.length>0){const r=t.pop();return c.push(r),1===i&&this.glContext.updateTexture(r,a,u,s,this.toTextureData(e,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${t.width}x${t.height}`);const d=this.glContext.allocateTexture(a,u,s,this.toTextureData(e,n));return this.config.reuseTextures&&(c.push(d),this.textureLookup.set(d,l)),d}readTexture(e,t,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",(()=>{const r=e.shape.reduce(((e,t)=>e*t))*n,i=this.glContext.readTexture(e.texture,e.width,e.height,r,this.toEncoderType(t),n);return this.toTensorData(t,i)}))}async readTextureAsync(e,t,n){const r=e.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const e=this.pendingRead.get(r);return new Promise((t=>null==e?void 0:e.push(t)))}return this.profiler.event("backend","TextureManager.readTextureAsync",(async()=>{this.pendingRead.set(r,[]);const i=e.shape.reduce(((e,t)=>e*t))*n;await this.glContext.createAndWaitForFence();const o=this.glContext.readTexture(e.texture,e.width,e.height,i,this.toEncoderType(t),n),s=this.toTensorData(t,o),a=this.pendingRead.get(r);return this.pendingRead.delete(r),null==a||a.forEach((e=>e(s))),s}))}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",(()=>{const t=e.shape.reduce(((e,t)=>e*t)),n=this.glContext.readTexture(e.texture,e.width,e.height,4*t,"byte",4);return new Float32Array(n.buffer,n.byteOffset,t)}))}releaseTexture(e,t){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(e.texture),n)){t&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const t=r.indexOf(e.texture);if(-1!==t){r.splice(t,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(e.texture)}}}n&&!t||(r.Logger.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,t){switch(e){case"int16":return t instanceof Int16Array?t:Int16Array.from(t);case"int32":return t instanceof Int32Array?t:Int32Array.from(t);case"int8":return t instanceof Int8Array?t:Int8Array.from(t);case"uint16":return t instanceof Uint16Array?t:Uint16Array.from(t);case"uint32":return t instanceof Uint32Array?t:Uint32Array.from(t);case"uint8":case"bool":return t instanceof Uint8Array?t:Uint8Array.from(t);case"float32":return t instanceof Float32Array?t:Float32Array.from(t);case"float64":return t instanceof Float64Array?t:Float64Array.from(t);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,t){if(t)return t instanceof Float32Array?t:new Float32Array(t)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},5639:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TextureType=void 0,(n=t.TextureType||(t.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},432:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getGlChannels=t.getCoordsDataType=t.getSqueezedParams=t.squeezeInputShape=t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=t.generateShaderFuncNameFromInputSamplerName=t.repeatedTry=t.getPackedShape=void 0;const r=n(7273);t.getPackedShape=function(e){const t=e.length;return e.slice(0,t-1).concat(e[t-1]/4)},t.repeatedTry=async function(e,t=(e=>0),n){return new Promise(((r,i)=>{let o=0;const s=()=>{if(e())return void r();o++;const a=t(o);null!=n&&o>=n?i():setTimeout(s,a)};s()}))},t.generateShaderFuncNameFromInputSamplerName=function(e){return(0,r.assert)(void 0!==e&&0!==e.length,(()=>"empty string found for sampler name")),"get"+e.charAt(0).toUpperCase()+e.slice(1)},t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(e){return(0,r.assert)(void 0!==e&&0!==e.length,(()=>"empty string found for sampler name")),"get"+e.charAt(0).toUpperCase()+e.slice(1)+"AtOutCoords"},t.squeezeInputShape=function(e,t){let n=JSON.parse(JSON.stringify(e));return n=t,n},t.getSqueezedParams=function(e,t){return t.map((t=>e[t])).join(", ")},t.getCoordsDataType=function(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)},t.getGlChannels=function(e=6){return["x","y","z","w","u","v"].slice(0,e)}},3389:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createNewWebGLContext=t.createWebGLContext=void 0;const r=n(1315),i=n(3524),o={};function s(e){const t=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const e=document.createElement("canvas");return e.width=1,e.height=1,e}();let n;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!e||"webgl2"===e)&&(n=t.getContext("webgl2",o),n))try{return new i.WebGLContext(n,2)}catch(e){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${e}`)}if((!e||"webgl"===e)&&(n=t.getContext("webgl",o)||t.getContext("experimental-webgl",o),n))try{return new i.WebGLContext(n,1)}catch(e){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${e}`)}throw new Error("WebGL is not supported")}t.createWebGLContext=function e(t){let n;t&&"webgl2"!==t||!("webgl2"in o)?t&&"webgl"!==t||!("webgl"in o)||(n=o.webgl):n=o.webgl2,n=n||s(t),t=t||1===n.version?"webgl":"webgl2";const r=n.gl;return o[t]=n,r.isContextLost()?(delete o[t],e(t)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},t.createNewWebGLContext=s},3524:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WebGLContext=t.linearSearchLastTrue=void 0;const s=n(8453),a=o(n(9622)),u=n(432);function l(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}t.linearSearchLastTrue=l,t.WebGLContext=class{constructor(e,t){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=e,this.version=t,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,t,n,r){const i=this.gl,o=i.createTexture();i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE);const s=r?n.encode(r,e*t):null;return i.texImage2D(i.TEXTURE_2D,0,n.internalFormat,e,t,0,n.format,n.textureType,s),this.checkError(),o}updateTexture(e,t,n,r,i){const o=this.gl;o.bindTexture(o.TEXTURE_2D,e);const s=r.encode(i,t*n);o.texSubImage2D(o.TEXTURE_2D,0,0,0,t,n,r.format,r.textureType,s),this.checkError()}attachFramebuffer(e,t,n){const r=this.gl;r.bindTexture(r.TEXTURE_2D,e),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),this.checkError(),r.viewport(0,0,t,n),r.scissor(0,0,t,n)}readTexture(e,t,n,r,i,o){const s=this.gl;o||(o=1),this.frameBufferBound||this.attachFramebuffer(e,t,n);const a=this.getEncoder(i,o),u=a.allocate(t*n);return s.bindTexture(s.TEXTURE_2D,e),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e,0),s.readPixels(0,0,t,n,s.RGBA,a.textureType,u),this.checkError(),a.decode(u,r)}isFramebufferReady(){return!0}getActiveTexture(){const e=this.gl;return"TEXTURE"+(e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0)}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,t){const n=this.gl;n.vertexAttribPointer(e,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(e),-1!==t&&(n.vertexAttribPointer(t,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(t)),this.checkError()}createProgram(e,t){const n=this.gl,r=n.createProgram();return n.attachShader(r,e),n.attachShader(r,t),n.linkProgram(r),r}compileShader(e,t){const n=this.gl,r=n.createShader(t);if(!r)throw new Error(`createShader() returned null with type ${t}`);if(n.shaderSource(r,e),n.compileShader(r),!1===n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(r)}\nShader source:\n${e}`);return r}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,t,n){const r=this.gl;r.activeTexture(r.TEXTURE0+t),this.checkError(),r.bindTexture(r.TEXTURE_2D,e),this.checkError(),r.uniform1i(n,t),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(s.env.debug){const e=this.gl,t=e.getError();let n="";switch(t){case e.NO_ERROR:return;case e.INVALID_ENUM:n="INVALID_ENUM";break;case e.INVALID_VALUE:n="INVALID_VALUE";break;case e.INVALID_OPERATION:n="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${t.toString(16)}`}throw new Error(n)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,t,n=0){if(2===this.version)return new a.RedFloat32DataEncoder(this.gl,t);switch(e){case"float":return 1===n||this.isRenderFloat32Supported?new a.RGBAFloatDataEncoder(this.gl,t):new a.RGBAFloatDataEncoder(this.gl,t,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new a.Uint8DataEncoder(this.gl,t);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){const e=this.gl;for(let t=0;t<this.maxTextureImageUnits;++t)e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,null)}dispose(){if(this.disposed)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(this.framebuffer),e.bindBuffer(e.ARRAY_BUFFER,null),e.deleteBuffer(this.vertexbuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.finish(),this.disposed=!0}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){const e=this.gl,t=e.createBuffer();if(!t)throw new Error("createBuffer() returned null");const n=this.createDefaultGeometry();return e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW),this.checkError(),t}createFramebuffer(){const e=this.gl.createFramebuffer();if(!e)throw new Error("createFramebuffer returned null");return e}queryVitalParameters(){const e=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),1===this.version&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw new Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.version}getExtensions(){2===this.version?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){const e=this.gl,t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);const n=2===this.version?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,n,1,1,0,e.RGBA,e.FLOAT,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0);const i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(t),e.deleteFramebuffer(r),i}checkRenderFloat32(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension)return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else{if(!this.textureFloatExtension)return!1;if(!this.gl.getExtension("WEBGL_color_buffer_float"))return!1}return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){const e=this.gl;let t,n,r,i,o;try{t=e.createTexture(),n=e.createFramebuffer(),e.bindTexture(e.TEXTURE_2D,t);const s=2===this.version?e.RGBA32F:e.RGBA;return e.texImage2D(e.TEXTURE_2D,0,s,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.enable(e.BLEND),r=e.createShader(e.VERTEX_SHADER),!!r&&(e.shaderSource(r,"void main(){}"),e.compileShader(r),i=e.createShader(e.FRAGMENT_SHADER),!!i&&(e.shaderSource(i,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),e.compileShader(i),o=e.createProgram(),!!o&&(e.attachShader(o,r),e.attachShader(o,i),e.linkProgram(o),e.useProgram(o),e.drawArrays(e.POINTS,0,1),e.getError()===e.NO_ERROR)))}finally{e.disable(e.BLEND),o&&e.deleteProgram(o),r&&e.deleteShader(r),i&&e.deleteShader(i),n&&(e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(n)),t&&(e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(t))}}beginTimer(){if(2===this.version&&this.disjointTimerQueryWebgl2Extension){const e=this.gl,t=this.disjointTimerQueryWebgl2Extension,n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}throw new Error("WebGL1 profiling currently not supported.")}endTimer(){if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const e=this.gl,t=this.disjointTimerQueryWebgl2Extension;e.endQuery(t.TIME_ELAPSED_EXT)}}isTimerResultAvailable(e){let t=!1,n=!1;if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const r=this.gl,i=this.disjointTimerQueryWebgl2Extension;t=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE),n=r.getParameter(i.GPU_DISJOINT_EXT)}return t&&!n}getTimerResult(e){let t=0;if(2!==this.version)throw new Error("WebGL1 profiling currently not supported");{const n=this.gl;t=n.getQueryParameter(e,n.QUERY_RESULT),n.deleteQuery(e)}return t/1e6}async waitForQueryAndGetTime(e){return await(0,u.repeatedTry)((()=>this.isTimerResultAvailable(e))),this.getTimerResult(e)}async createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t;const n=e,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),t=null===r?()=>!0:()=>{const e=n.clientWaitSync(r,0,0);return e===n.ALREADY_SIGNALED||e===n.CONDITION_SATISFIED},{query:r,isFencePassed:t}}async pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=l(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||await(0,u.repeatedTry)((()=>(this.pollItems(),0===this.itemsToPoll.length)))}}},6496:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExecutionPlan=void 0;const r=n(1315);class i{constructor(e,t){this.op=e,this.node=t}}t.ExecutionPlan=class{constructor(e,t,n){this.graph=e,this.profiler=n,this.initialize(t)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",(()=>{const t=this.graph.getNodes();if(t.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map(((e,n)=>new i(e,t[n]))),this.reset(),this._starter=[],this._ops.forEach(((e,t)=>{let n=!0;for(const t of e.node.inputs)if(!this._values[t]&&-1===this.graph.getInputIndices().indexOf(t)){n=!1;break}n&&this._starter.push(t)}))}))}reset(){this._values=this.graph.getValues().map((e=>e.tensor))}async execute(e,t){return this.profiler.event("session","ExecutionPlan.execute",(async()=>{this.reset();const n=e.createInferenceHandler(),i=this.graph.getInputIndices();if(t.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${t.length} expected: ${i.length}`);t.forEach(((e,t)=>{const n=i[t];this._values[n]=e}));const o=this._starter.slice(0),s=this.graph.getValues(),a=this.graph.getNodes();let u=0;for(;u<o.length;){const e=o[u++],t=this._ops[e],i=t.node.inputs.map((e=>this._values[e]));if(-1!==i.indexOf(void 0))throw new Error(`unresolved input detected: op: ${t.node}`);const l=i;r.Logger.verbose("ExecPlan",`Runing op:${t.node.name} (${l.map(((e,n)=>`'${t.node.inputs[n]}': ${e.type}[${e.dims.join(",")}]`)).join(", ")})`);const c=await this.profiler.event("node",t.node.name,(async()=>t.op.impl(n,l,t.op.context)));if(c.length!==t.node.outputs.length)throw new Error("the size of output does not match model definition.");c.forEach(((e,n)=>{const r=t.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${t.node.name}`);this._values[r]=e}));const d=new Set;c.forEach(((e,n)=>{const r=t.node.outputs[n];for(const e of s[r].to){const t=a[e];let n=!0;for(const e of t.inputs)if(!this._values[e]){n=!1;break}n&&d.add(e)}})),o.push(...d)}const l=[];for(let e=0;e<this.graph.getOutputIndices().length;e++){const t=this.graph.getOutputIndices()[e],n=this._values[t];if(void 0===n)throw new Error(`required output [${t}] does not have value`);0===t?await n.getData():n.data,l.push(n)}return r.Logger.verbose("ExecPlan","disposing of inferenceHandler"),n.dispose(),l}))}}},4662:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Graph=void 0;const r=n(1446),i=n(6874),o=n(1287),s=n(9240),a=n(7273);var u=o.onnxruntime.experimental.fbs;t.Graph={from:(e,t)=>new d(e,t)};class l{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=a.ProtoUtil.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}}class c{constructor(e,t){e instanceof r.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new i.Attribute(e.attribute)):e instanceof u.Node&&(this.name=null!=t?t:e.name(),this.opType=e.opType(),this.attributes=new i.Attribute(a.ProtoUtil.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class d{constructor(e,t){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(t),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else{if(!(e instanceof u.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(e)}}buildGraphFromOnnxFormat(e){const t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!e.input)throw new Error("missing information in graph: input");const r=[];for(const n of e.input){if(t.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const e=this._allData.push(new l(n))-1;t.set(n.name,e),r.push(n.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(const n of e.initializer){let e=t.get(n.name);if(void 0===e){const r=new l;r.type={shape:{dims:a.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:a.ProtoUtil.tensorDataTypeFromProto(n.dataType)},e=this._allData.push(r)-1,t.set(n.name,e)}this._allData[e]._from=-1,this._allData[e].tensor=s.Tensor.fromProto(n)}for(let e=0;e<this._allData.length;e++)this._allData[e].tensor||(this._allInputIndices.push(e),this._allInputNames.push(r[e]));if(!e.output)throw new Error("missing information in graph: output");for(const n of e.output){if(t.has(n.name))throw new Error(`duplicated output name: ${n.name}`);const e=this._allData.push(new l(n))-1;t.set(n.name,e),this._allOutputIndices.push(e),this._allOutputNames.push(n.name)}if(!e.node)throw new Error("missing information in graph: node");for(const t of e.node){if(!t.name)for(let e=0;;e++){const r=`unnamed_${t.opType}_${e}`;if(!n.has(r)){t.name=r;break}}if(n.has(t.name))throw new Error(`duplicated node name: ${t.name}`);const e=this._nodes.push(new c(t))-1;n.set(t.name,e)}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=e.node[n];if(!i.output)throw new Error(`missing output for node: ${i.name}`);for(const e of i.output){let o=t.get(e);if(void 0===o&&(o=this._allData.push(new l)-1,t.set(e,o)),r.outputs.push(o),void 0!==this._allData[o]._from)throw new Error(`multiple nodes output to one data value: ${o}`);if(this._allData[o]._from=n,"Constant"===i.opType){if(!i.attribute||1!==i.attribute.length||!i.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!i.output||1!==i.output.length)throw new Error("missing output or incorrect number of outputs for this Constant operator");r.outputs.pop(),r.executeNode=!1,this._allData[o]._from=-1,this._allData[o].tensor=s.Tensor.fromProto(i.attribute[0].t)}}}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=e.node[n];if(!i.input)throw new Error(`missing input for node: ${i.name}`);for(const e of i.input){const o=t.get(e);if(void 0===o){if(""===e&&3===i.input.length&&"Resize"===i.opType)continue;throw new Error(`unrecognized input '${e}' for node: ${i.name}`)}r.inputs.push(o),this._allData[o]._to.push(n)}}return!0}buildGraphFromOrtFormat(e){var t,n,r;const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const o=new Map,d=[];for(let o=0;o<e.inputsLength();o++){const s=e.inputs(o);if(i.has(s))throw new Error(`duplicated input name: ${s}`);for(let o=0;o<e.nodeArgsLength();o++)if((null===(t=e.nodeArgs(o))||void 0===t?void 0:t.name())===s){const t=new l;if((null===(r=null===(n=e.nodeArgs(o))||void 0===n?void 0:n.type())||void 0===r?void 0:r.valueType())!==u.TypeInfoValue.tensor_type)throw new Error("Unexpected value type for the nodeArg.");const c=e.nodeArgs(o).type().value(new u.TensorTypeAndShape),h=a.ProtoUtil.tensorDataTypeFromProto(c.elemType()),p=c.shape(),f=[];for(let e=0;e<p.dimLength();e++)f.push(a.LongUtil.longToNumber(p.dim(e).value().dimValue()));t.type={shape:{dims:f},tensorType:h};const g=this._allData.push(t)-1;i.set(s,g),d.push(s)}}for(let t=0;t<e.initializersLength();t++){const n=e.initializers(t);let r=i.get(n.name());if(void 0===r){const e=new l,t=a.ProtoUtil.tensorDimsFromORTFormat(n),o=a.ProtoUtil.tensorDataTypeFromProto(n.dataType());e.type={shape:{dims:t},tensorType:o},r=this._allData.push(e)-1,i.set(n.name(),r)}this._allData[r]._from=-1,this._allData[r].tensor=s.Tensor.fromOrtTensor(n)}for(let e=0;e<this._allData.length;e++)this._allData[e].tensor||(this._allInputIndices.push(e),this._allInputNames.push(d[e]));for(let t=0;t<e.outputsLength();t++){const n=e.outputs(t);if(i.has(n))throw new Error(`duplicated output name: ${n}`);const r=this._allData.push(new l)-1;i.set(n,r),this._allOutputIndices.push(r),this._allOutputNames.push(n)}if(!e.nodes)throw new Error("missing information in graph: node");for(let t=0;t<e.nodesLength();t++){const n=e.nodes(t);let r=n.name();if(!r)for(let e=0;r=`unnamed_${n.opType()}_${e}`,o.has(r);e++);if(o.has(r))throw new Error(`duplicated node name: ${r}`);const i=this._nodes.push(new c(n,r))-1;o.set(r,i)}for(let t=0;t<this._nodes.length;t++){const n=this._nodes[t],r=e.nodes(t);if(null==r)throw new Error(`No node exists at index ${t}`);if(0===(null==r?void 0:r.outputsLength()))throw new Error(`missing output for node: ${r.name}`);for(let e=0;e<(null==r?void 0:r.outputsLength());e++){const o=null==r?void 0:r.outputs(e);let a=i.get(o);if(void 0===a&&(a=this._allData.push(new l)-1,i.set(o,a)),n.outputs.push(a),void 0!==this._allData[a]._from)throw new Error(`multiple nodes output to one data value: ${a}`);if(this._allData[a]._from=t,"Constant"===r.opType()){if(1!==r.attributesLength()||!r.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(1!==r.outputsLength())throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=!1,this._allData[a]._from=-1,this._allData[a].tensor=s.Tensor.fromOrtTensor(r.attributes(0).t())}}}for(let t=0;t<this._nodes.length;t++){const n=this._nodes[t],r=e.nodes(t);if(0===r.inputsLength())throw new Error(`missing input for node: ${r.name}`);for(let e=0;e<r.inputsLength();e++){const o=r.inputs(e),s=i.get(o);if(void 0===s)throw new Error(`unrecognized input '${o}' for node: ${r.name()}`);n.inputs.push(s),this._allData[s]._to.push(t)}}}checkIsAcyclic(){const e=new Set;this._allInputIndices.forEach((t=>{this._allData[t]._to.forEach((t=>{e.add(t)}))}));const t=Array.from(e),n=new Array(this._nodes.length).fill("white");for(;t.length>0;){const e=t.pop();"gray"===n[e]?n[e]="black":(t.push(e),n[e]="gray",this._nodes[e].outputs.forEach((r=>{const i=this._allData[r];if(void 0!==i.tensor)throw new Error("node outputs should not be initialized");if(i._from!==e)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach((e=>{if("gray"===n[e])throw new Error("model graph is cyclic");"white"===n[e]&&t.push(e)}))})))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0;const t=new Array(this._nodes.length,0);let n=0;for(let e=0;e<this._nodes.length;e++)t[e]=n,this._nodes[e].executeNode?(n!==e&&(this._nodes[n]=this._nodes[e]),n++):this._nodes[e].outputs.forEach((e=>{this._allData[e]._from=-2}));this._nodes.splice(n,this._nodes.length-n);for(let e=0;e<this._allData.length;e++){const n=this._allData[e];void 0!==n._from&&-1!==n._from&&-2!==n._from&&(n._from=t[n._from]);for(let e=0;e<n._to.length;e++){if(!(n._to[e]>=0))throw new Error("Trying to update a removed node");n._to[e]=t[n._to[e]]}}e=0;for(let t=0;t<this._allData.length;t++)if(-2!==this._allData[t].from||-1!==this._allOutputIndices.indexOf(t+e)){if(e>0){let n=-1;void 0!==this._allData[t].from&&-1!==this._allData[t].from?(n=this._nodes[this._allData[t].from].outputs.indexOf(t+e),-1!==n&&(this._nodes[this._allData[t].from].outputs[n]=t)):(n=this._allInputIndices.indexOf(t+e),-1!==n&&(this._allInputIndices[n]=t)),this._allData[t].to.forEach((r=>{n=this._nodes[r].inputs.indexOf(t+e),-1!==n&&(this._nodes[r].inputs[n]=t)})),0===this._allData[t].to.length&&(n=this._allOutputIndices.indexOf(t+e),-1!==n&&(this._allOutputIndices[n]=t))}}else e++,this._allData.splice(t,1),t--}deleteNode(e){const t=this._nodes[e];if(t.outputs.length>1)for(let e=1;e<t.outputs.length;e++)if(this._allData[t.outputs[e]].to.length>0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");t.executeNode=!1;const n=t.inputs[0],r=t.outputs[0],i=this._allData[r].to;for(let n=0;n<t.inputs.length;n++){const r=this._allData[t.inputs[n]].to.indexOf(e);if(-1===r)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[t.inputs[n]].to.splice(r,1)}this._allData[r]._to=[];const o=this._allOutputIndices.indexOf(r);if(-1!==o&&(this._allOutputIndices[o]=n),i&&i.length>0)for(const e of i){const t=this._nodes[e].inputs.indexOf(r);if(-1===t)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[e].inputs[t]=n,this._allData[n].to.push(e)}}removeAllDropoutNodes(){let e=0;for(const t of this._nodes){if("Dropout"===t.opType){if(1!==t.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==t.outputs.length&&2!==t.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===t.outputs.length&&0!==this._allData[t.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(const t of this._nodes)"Identity"===t.opType&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const e of this._nodes)if("Conv"===e.opType){const t=this._allData[e.outputs[0]]._to;if(1===t.length&&this.isActivation(this._nodes[t[0]])){const n=this._nodes[t[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{e.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(t){e.attributes.set("activation_params","floats",[a.MIN_CLIP,a.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;e.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}e.attributes.set("activation","string",n.opType),this.deleteNode(t[0])}}}}},1315:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.now=t.Profiler=t.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(e,t,n){}},console:new class{log(e,t,n){console.log(`${this.color(e)} ${n?""+n+" ":""}${t}`)}color(e){switch(e){case"verbose":return"v";case"info":return"i";case"warning":return"w";case"error":return"e";case"fatal":return"f";default:throw new Error(`unsupported severity: ${e}`)}}}},i={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let o={"":i};function s(e,t,n,r){if(void 0===t)return i=e,{verbose:s.verbose.bind(null,i),info:s.info.bind(null,i),warning:s.warning.bind(null,i),error:s.error.bind(null,i),fatal:s.fatal.bind(null,i)};if(void 0===n)a(e,t);else if("number"==typeof n&&void 0===r)a(e,t);else if("string"==typeof n&&void 0===r)a(e,n,0,t);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");a(e,n,0,t)}var i}function a(e,t,i,s){const a=o[s||""]||o[""];n[e]<n[a.minimalSeverity]||(a.logDateTime&&(t=`${(new Date).toISOString()}|${t}`),a.logSourceLocation,r[a.provider].log(e,t,s))}!function(e){function t(e){o={},n("",e||{})}function n(e,n){if("*"===e)t(n);else{const t=o[e]||i;o[e]={provider:n.provider||t.provider,minimalSeverity:n.minimalSeverity||t.minimalSeverity,logDateTime:void 0===n.logDateTime?t.logDateTime:n.logDateTime,logSourceLocation:void 0===n.logSourceLocation?t.logSourceLocation:n.logSourceLocation}}}e.verbose=function(t,n){e("verbose",t,n)},e.info=function(t,n){e("info",t,n)},e.warning=function(t,n){e("warning",t,n)},e.error=function(t,n){e("error",t,n)},e.fatal=function(t,n){e("fatal",t,n)},e.reset=t,e.set=n,e.setWithEnv=function(e){const t={};e.logLevel&&(t.minimalSeverity=e.logLevel),n("",t)}}(s||(s={})),t.Logger=s;class u{constructor(e,t,n,r,i,o){this.category=e,this.name=t,this.startTime=n,this.endCallback=r,this.timer=i,this.ctx=o}async end(){return this.endCallback(this)}async checkTimer(){if(void 0===this.ctx||void 0===this.timer)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}}class l{constructor(e,t,n,r){this.category=e,this.name=t,this.startTime=n,this.endTime=r}}t.Profiler=class{static create(e){return void 0===e?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}constructor(e,t,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=void 0===e?1e4:e,this._flushBatchSize=void 0===t?10:t,this._flushIntervalInMilliseconds=void 0===n?5e3:n}start(){this._started=!0,this._timingEvents=[],this._flushTime=(0,t.now)(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer])}event(e,t,n,r){const i=this._started?this.begin(e,t,r):void 0;let o=!1;const s=n();if(s&&"function"==typeof s.then)return o=!0,new Promise(((e,t)=>{s.then((async t=>{i&&await i.end(),e(t)}),(async e=>{i&&await i.end(),t(e)}))}));if(!o&&i){const e=i.end();if(e&&"function"==typeof e.then)return new Promise(((t,n)=>{e.then((()=>{t(s)}),(e=>{n(e)}))}))}return s}begin(e,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,t.now)();return this.flush(r),new u(e,n,r,(e=>this.endSync(e)))}{const t=r.beginTimer();return new u(e,n,0,(async e=>this.end(e)),t,r)}}async end(e){const t=await e.checkTimer();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new l(e.category,e.name,e.startTime,t)),this.flush(t))}endSync(e){const n=(0,t.now)();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new l(e.category,e.name,e.startTime,n)),this.flush(n))}logOneEvent(e){t.Logger.verbose(`Profiler.${e.category}`,`${(e.endTime-e.startTime).toFixed(2)}ms on event '${e.name}' at ${e.endTime.toFixed(2)}`)}flush(e){if(this._timingEvents.length-this._flushPointer>=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(const e=this._flushPointer;this._flushPointer<e+this._flushBatchSize&&this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer]);this._flushTime=(0,t.now)()}}get started(){return this._started}},t.now="undefined"!=typeof performance&&performance.now?()=>performance.now():Date.now},1745:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const r=n(5686),i=n(1446),o=n(4662),s=n(1287),a=n(7273);var u=s.onnxruntime.experimental.fbs;t.Model=class{constructor(){}load(e,t,n){if(!n)try{return void this.loadFromOnnxFormat(e,t)}catch(e){if(void 0!==n)throw e}this.loadFromOrtFormat(e,t)}loadFromOnnxFormat(e,t){const n=i.onnx.ModelProto.decode(e);if(a.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map((e=>({domain:e.domain,version:a.LongUtil.longToNumber(e.version)}))),this._graph=o.Graph.from(n.graph,t)}loadFromOrtFormat(e,t){const n=new r.flatbuffers.ByteBuffer(e),i=u.InferenceSession.getRootAsInferenceSession(n).model();if(a.LongUtil.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let e=0;e<i.opsetImportLength();e++){const t=i.opsetImport(e);this._opsets.push({domain:null==t?void 0:t.domain(),version:a.LongUtil.longToNumber(t.version())})}this._graph=o.Graph.from(i.graph(),t)}get graph(){return this._graph}get opsets(){return this._opsets}}},6145:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FLOAT_TYPES=t.INT_TYPES=t.NUMBER_TYPES=void 0,t.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],t.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],t.FLOAT_TYPES=["float32","float64"]},5881:(e,t)=>{"use strict";function n(e,t){if(t.endsWith("+")){const n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}if(2===t.split("-").length){const n=t.split("-"),r=Number.parseInt(n[0],10),i=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(i)&&r<=e&&e<=i}return Number.parseInt(t,10)===e}Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOperator=void 0,t.resolveOperator=function(e,t,r){for(const i of r){const r=i[0],o=i[1],s=i[2],a=i[3],u=i[4];if(e.opType===r)for(const e of t)if((e.domain===o||"ai.onnx"===e.domain&&""===o)&&n(e.version,s))return{opImpl:a,opInit:u}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map((e=>`${e.domain||"ai.onnx"} v${e.version}`)).join(", ")}`)}},1287:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onnxruntime=void 0;const r=n(5686);var i,o;(function(e){let t;!function(e){e[e.UNDEFINED=0]="UNDEFINED",e[e.FLOAT=1]="FLOAT",e[e.INT=2]="INT",e[e.STRING=3]="STRING",e[e.TENSOR=4]="TENSOR",e[e.GRAPH=5]="GRAPH",e[e.FLOATS=6]="FLOATS",e[e.INTS=7]="INTS",e[e.STRINGS=8]="STRINGS",e[e.TENSORS=9]="TENSORS",e[e.GRAPHS=10]="GRAPHS",e[e.SPARSE_TENSOR=11]="SPARSE_TENSOR",e[e.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(t=e.AttributeType||(e.AttributeType={}))})((o=(i=t.onnxruntime||(t.onnxruntime={})).experimental||(i.experimental={})).fbs||(o.fbs={})),function(e){!function(e){!function(e){let t;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VALUE=1]="VALUE",e[e.PARAM=2]="PARAM"}(t=e.DimensionValueType||(e.DimensionValueType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){let t;!function(e){e[e.UNDEFINED=0]="UNDEFINED",e[e.FLOAT=1]="FLOAT",e[e.UINT8=2]="UINT8",e[e.INT8=3]="INT8",e[e.UINT16=4]="UINT16",e[e.INT16=5]="INT16",e[e.INT32=6]="INT32",e[e.INT64=7]="INT64",e[e.STRING=8]="STRING",e[e.BOOL=9]="BOOL",e[e.FLOAT16=10]="FLOAT16",e[e.DOUBLE=11]="DOUBLE",e[e.UINT32=12]="UINT32",e[e.UINT64=13]="UINT64",e[e.COMPLEX64=14]="COMPLEX64",e[e.COMPLEX128=15]="COMPLEX128",e[e.BFLOAT16=16]="BFLOAT16"}(t=e.TensorDataType||(e.TensorDataType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){let t;!function(e){e[e.Primitive=0]="Primitive",e[e.Fused=1]="Fused"}(t=e.NodeType||(e.NodeType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){let t;!function(e){e[e.NONE=0]="NONE",e[e.tensor_type=1]="tensor_type",e[e.sequence_type=2]="sequence_type",e[e.map_type=3]="map_type"}(t=e.TypeInfoValue||(e.TypeInfoValue={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsShape(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsShape(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}dim(t,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new e.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}dimLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}static startShape(e){e.startObject(1)}static addDim(e,t){e.addFieldOffset(0,t,0)}static createDimVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startDimVector(e,t){e.startVector(4,t,4)}static endShape(e){return e.endObject()}static createShape(e,t){return n.startShape(e),n.addDim(e,t),n.endShape(e)}}t.Shape=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDimension(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsDimension(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}value(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}denotation(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startDimension(e){e.startObject(2)}static addValue(e,t){e.addFieldOffset(0,t,0)}static addDenotation(e,t){e.addFieldOffset(1,t,0)}static endDimension(e){return e.endObject()}static createDimension(e,t,r){return n.startDimension(e),n.addValue(e,t),n.addDenotation(e,r),n.endDimension(e)}}t.Dimension=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDimensionValue(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsDimensionValue(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):e.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}dimParam(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}static startDimensionValue(e){e.startObject(3)}static addDimType(t,n){t.addFieldInt8(0,n,e.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addDimParam(e,t){e.addFieldOffset(2,t,0)}static endDimensionValue(e){return e.endObject()}static createDimensionValue(e,t,r,i){return n.startDimensionValue(e),n.addDimType(e,t),n.addDimValue(e,r),n.addDimParam(e,i),n.endDimensionValue(e)}}t.DimensionValue=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTensorTypeAndShape(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTensorTypeAndShape(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(e){e.startObject(2)}static addElemType(t,n){t.addFieldInt32(0,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(e,t){e.addFieldOffset(1,t,0)}static endTensorTypeAndShape(e){return e.endObject()}static createTensorTypeAndShape(e,t,r){return n.startTensorTypeAndShape(e),n.addElemType(e,t),n.addShape(e,r),n.endTensorTypeAndShape(e)}}t.TensorTypeAndShape=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMapType(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMapType(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(e){e.startObject(2)}static addKeyType(t,n){t.addFieldInt32(0,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(e,t){e.addFieldOffset(1,t,0)}static endMapType(e){return e.endObject()}static createMapType(e,t,r){return n.startMapType(e),n.addKeyType(e,t),n.addValueType(e,r),n.endMapType(e)}}t.MapType=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSequenceType(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSequenceType(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}elemType(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSequenceType(e){e.startObject(1)}static addElemType(e,t){e.addFieldOffset(0,t,0)}static endSequenceType(e){return e.endObject()}static createSequenceType(e,t){return n.startSequenceType(e),n.addElemType(e,t),n.endSequenceType(e)}}t.SequenceType=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){(e.fbs||(e.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(e,t,n,r){return e.prep(4,12),e.writeInt32(r),e.writeInt32(n),e.writeInt32(t),e.offset()}}}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNodeEdge(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsNodeEdge(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}nodeIndex(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb_pos+e):0}inputEdges(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}inputEdgesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}outputEdges(t,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}outputEdgesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}static startNodeEdge(e){e.startObject(3)}static addNodeIndex(e,t){e.addFieldInt32(0,t,0)}static addInputEdges(e,t){e.addFieldOffset(1,t,0)}static startInputEdgesVector(e,t){e.startVector(12,t,4)}static addOutputEdges(e,t){e.addFieldOffset(2,t,0)}static startOutputEdgesVector(e,t){e.startVector(12,t,4)}static endNodeEdge(e){return e.endObject()}static createNodeEdge(e,t,r,i){return n.startNodeEdge(e),n.addNodeIndex(e,t),n.addInputEdges(e,r),n.addOutputEdges(e,i),n.endNodeEdge(e)}}t.NodeEdge=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNode(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsNode(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}domain(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}sinceVersion(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):0}index(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint32(this.bb_pos+e):0}opType(e){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__string(this.bb_pos+t,e):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.NodeType.Primitive}executionProviderType(e){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__string(this.bb_pos+t,e):null}inputs(e,t){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}inputsLength(){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__vector_len(this.bb_pos+e):0}outputs(e,t){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}outputsLength(){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.__vector_len(this.bb_pos+e):0}attributes(t,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new e.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}attributesLength(){let e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__vector_len(this.bb_pos+e):0}inputArgCounts(e){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.readInt32(this.bb.__vector(this.bb_pos+t)+4*e):0}inputArgCountsLength(){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__vector_len(this.bb_pos+e):0}inputArgCountsArray(){let e=this.bb.__offset(this.bb_pos,26);return e?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}implicitInputs(e,t){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}implicitInputsLength(){let e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__vector_len(this.bb_pos+e):0}static startNode(e){e.startObject(13)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addDomain(e,t){e.addFieldOffset(2,t,0)}static addSinceVersion(e,t){e.addFieldInt32(3,t,0)}static addIndex(e,t){e.addFieldInt32(4,t,0)}static addOpType(e,t){e.addFieldOffset(5,t,0)}static addType(t,n){t.addFieldInt32(6,n,e.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(e,t){e.addFieldOffset(7,t,0)}static addInputs(e,t){e.addFieldOffset(8,t,0)}static createInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInputsVector(e,t){e.startVector(4,t,4)}static addOutputs(e,t){e.addFieldOffset(9,t,0)}static createOutputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOutputsVector(e,t){e.startVector(4,t,4)}static addAttributes(e,t){e.addFieldOffset(10,t,0)}static createAttributesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startAttributesVector(e,t){e.startVector(4,t,4)}static addInputArgCounts(e,t){e.addFieldOffset(11,t,0)}static createInputArgCountsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startInputArgCountsVector(e,t){e.startVector(4,t,4)}static addImplicitInputs(e,t){e.addFieldOffset(12,t,0)}static createImplicitInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startImplicitInputsVector(e,t){e.startVector(4,t,4)}static endNode(e){return e.endObject()}static createNode(e,t,r,i,o,s,a,u,l,c,d,h,p,f){return n.startNode(e),n.addName(e,t),n.addDocString(e,r),n.addDomain(e,i),n.addSinceVersion(e,o),n.addIndex(e,s),n.addOpType(e,a),n.addType(e,u),n.addExecutionProviderType(e,l),n.addInputs(e,c),n.addOutputs(e,d),n.addAttributes(e,h),n.addInputArgCounts(e,p),n.addImplicitInputs(e,f),n.endNode(e)}}t.Node=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsValueInfo(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsValueInfo(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}type(t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startValueInfo(e){e.startObject(3)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addType(e,t){e.addFieldOffset(2,t,0)}static endValueInfo(e){return e.endObject()}static createValueInfo(e,t,r,i){return n.startValueInfo(e),n.addName(e,t),n.addDocString(e,r),n.addType(e,i),n.endValueInfo(e)}}t.ValueInfo=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTypeInfo(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTypeInfo(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}denotation(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):e.experimental.fbs.TypeInfoValue.NONE}value(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}static startTypeInfo(e){e.startObject(3)}static addDenotation(e,t){e.addFieldOffset(0,t,0)}static addValueType(t,n){t.addFieldInt8(1,n,e.experimental.fbs.TypeInfoValue.NONE)}static addValue(e,t){e.addFieldOffset(2,t,0)}static endTypeInfo(e){return e.endObject()}static createTypeInfo(e,t,r,i){return n.startTypeInfo(e),n.addDenotation(e,t),n.addValueType(e,r),n.addValue(e,i),n.endTypeInfo(e)}}t.TypeInfo=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){class t{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsOperatorSetId(e,n){return(n||new t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsOperatorSetId(e,n){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new t).__init(e.readInt32(e.position())+e.position(),e)}domain(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}version(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}static startOperatorSetId(e){e.startObject(2)}static addDomain(e,t){e.addFieldOffset(0,t,0)}static addVersion(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static endOperatorSetId(e){return e.endObject()}static createOperatorSetId(e,n,r){return t.startOperatorSetId(e),t.addDomain(e,n),t.addVersion(e,r),t.endOperatorSetId(e)}}e.OperatorSetId=t}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTensor(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTensor(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dims(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}dimsLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}rawData(e){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint8(this.bb.__vector(this.bb_pos+t)+e):0}rawDataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}rawDataArray(){let e=this.bb.__offset(this.bb_pos,12);return e?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}stringData(e,t){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}stringDataLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}static startTensor(e){e.startObject(6)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addDims(e,t){e.addFieldOffset(2,t,0)}static createDimsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startDimsVector(e,t){e.startVector(8,t,8)}static addDataType(t,n){t.addFieldInt32(3,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(e,t){e.addFieldOffset(4,t,0)}static createRawDataVector(e,t){e.startVector(1,t.length,1);for(let n=t.length-1;n>=0;n--)e.addInt8(t[n]);return e.endVector()}static startRawDataVector(e,t){e.startVector(1,t,1)}static addStringData(e,t){e.addFieldOffset(5,t,0)}static createStringDataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startStringDataVector(e,t){e.startVector(4,t,4)}static endTensor(e){return e.endObject()}static createTensor(e,t,r,i,o,s,a){return n.startTensor(e),n.addName(e,t),n.addDocString(e,r),n.addDims(e,i),n.addDataType(e,o),n.addRawData(e,s),n.addStringData(e,a),n.endTensor(e)}}t.Tensor=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSparseTensor(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSparseTensor(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}values(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}dims(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}dimsLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSparseTensor(e){e.startObject(3)}static addValues(e,t){e.addFieldOffset(0,t,0)}static addIndices(e,t){e.addFieldOffset(1,t,0)}static addDims(e,t){e.addFieldOffset(2,t,0)}static createDimsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startDimsVector(e,t){e.startVector(8,t,8)}static endSparseTensor(e){return e.endObject()}static createSparseTensor(e,t,r,i){return n.startSparseTensor(e),n.addValues(e,t),n.addIndices(e,r),n.addDims(e,i),n.endSparseTensor(e)}}t.SparseTensor=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsAttribute(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsAttribute(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.AttributeType.UNDEFINED}f(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readFloat32(this.bb_pos+e):0}i(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}s(e){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__string(this.bb_pos+t,e):null}t(t){let n=this.bb.__offset(this.bb_pos,16);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(t){let n=this.bb.__offset(this.bb_pos,18);return n?(t||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}floats(e){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.readFloat32(this.bb.__vector(this.bb_pos+t)+4*e):0}floatsLength(){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__vector_len(this.bb_pos+e):0}floatsArray(){let e=this.bb.__offset(this.bb_pos,20);return e?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}ints(e){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}intsLength(){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.__vector_len(this.bb_pos+e):0}strings(e,t){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}stringsLength(){let e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__vector_len(this.bb_pos+e):0}tensors(t,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}tensorsLength(){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__vector_len(this.bb_pos+e):0}graphs(t,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}graphsLength(){let e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__vector_len(this.bb_pos+e):0}static startAttribute(e){e.startObject(13)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addType(t,n){t.addFieldInt32(2,n,e.experimental.fbs.AttributeType.UNDEFINED)}static addF(e,t){e.addFieldFloat32(3,t,0)}static addI(e,t){e.addFieldInt64(4,t,e.createLong(0,0))}static addS(e,t){e.addFieldOffset(5,t,0)}static addT(e,t){e.addFieldOffset(6,t,0)}static addG(e,t){e.addFieldOffset(7,t,0)}static addFloats(e,t){e.addFieldOffset(8,t,0)}static createFloatsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addFloat32(t[n]);return e.endVector()}static startFloatsVector(e,t){e.startVector(4,t,4)}static addInts(e,t){e.addFieldOffset(9,t,0)}static createIntsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startIntsVector(e,t){e.startVector(8,t,8)}static addStrings(e,t){e.addFieldOffset(10,t,0)}static createStringsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startStringsVector(e,t){e.startVector(4,t,4)}static addTensors(e,t){e.addFieldOffset(11,t,0)}static createTensorsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startTensorsVector(e,t){e.startVector(4,t,4)}static addGraphs(e,t){e.addFieldOffset(12,t,0)}static createGraphsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startGraphsVector(e,t){e.startVector(4,t,4)}static endAttribute(e){return e.endObject()}static createAttribute(e,t,r,i,o,s,a,u,l,c,d,h,p,f){return n.startAttribute(e),n.addName(e,t),n.addDocString(e,r),n.addType(e,i),n.addF(e,o),n.addI(e,s),n.addS(e,a),n.addT(e,u),n.addG(e,l),n.addFloats(e,c),n.addInts(e,d),n.addStrings(e,h),n.addTensors(e,p),n.addGraphs(e,f),n.endAttribute(e)}}t.Attribute=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsGraph(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsGraph(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}initializers(t,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}initializersLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}nodeArgs(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeArgsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}nodes(t,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new e.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}maxNodeIndex(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readUint32(this.bb_pos+e):0}nodeEdges(t,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new e.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeEdgesLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}inputs(e,t){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}inputsLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}outputs(e,t){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}outputsLength(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}sparseInitializers(t,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new e.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}sparseInitializersLength(){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__vector_len(this.bb_pos+e):0}static startGraph(e){e.startObject(8)}static addInitializers(e,t){e.addFieldOffset(0,t,0)}static createInitializersVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInitializersVector(e,t){e.startVector(4,t,4)}static addNodeArgs(e,t){e.addFieldOffset(1,t,0)}static createNodeArgsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodeArgsVector(e,t){e.startVector(4,t,4)}static addNodes(e,t){e.addFieldOffset(2,t,0)}static createNodesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodesVector(e,t){e.startVector(4,t,4)}static addMaxNodeIndex(e,t){e.addFieldInt32(3,t,0)}static addNodeEdges(e,t){e.addFieldOffset(4,t,0)}static createNodeEdgesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodeEdgesVector(e,t){e.startVector(4,t,4)}static addInputs(e,t){e.addFieldOffset(5,t,0)}static createInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInputsVector(e,t){e.startVector(4,t,4)}static addOutputs(e,t){e.addFieldOffset(6,t,0)}static createOutputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOutputsVector(e,t){e.startVector(4,t,4)}static addSparseInitializers(e,t){e.addFieldOffset(7,t,0)}static createSparseInitializersVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startSparseInitializersVector(e,t){e.startVector(4,t,4)}static endGraph(e){return e.endObject()}static createGraph(e,t,r,i,o,s,a,u,l){return n.startGraph(e),n.addInitializers(e,t),n.addNodeArgs(e,r),n.addNodes(e,i),n.addMaxNodeIndex(e,o),n.addNodeEdges(e,s),n.addInputs(e,a),n.addOutputs(e,u),n.addSparseInitializers(e,l),n.endGraph(e)}}t.Graph=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsModel(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsModel(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}irVersion(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}opsetImport(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}opsetImportLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}producerName(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}producerVersion(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__string(this.bb_pos+t,e):null}domain(e){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__string(this.bb_pos+t,e):null}modelVersion(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}docString(e){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__string(this.bb_pos+t,e):null}graph(t){let n=this.bb.__offset(this.bb_pos,18);return n?(t||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}graphDocString(e){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__string(this.bb_pos+t,e):null}static startModel(e){e.startObject(9)}static addIrVersion(e,t){e.addFieldInt64(0,t,e.createLong(0,0))}static addOpsetImport(e,t){e.addFieldOffset(1,t,0)}static createOpsetImportVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOpsetImportVector(e,t){e.startVector(4,t,4)}static addProducerName(e,t){e.addFieldOffset(2,t,0)}static addProducerVersion(e,t){e.addFieldOffset(3,t,0)}static addDomain(e,t){e.addFieldOffset(4,t,0)}static addModelVersion(e,t){e.addFieldInt64(5,t,e.createLong(0,0))}static addDocString(e,t){e.addFieldOffset(6,t,0)}static addGraph(e,t){e.addFieldOffset(7,t,0)}static addGraphDocString(e,t){e.addFieldOffset(8,t,0)}static endModel(e){return e.endObject()}static createModel(e,t,r,i,o,s,a,u,l,c){return n.startModel(e),n.addIrVersion(e,t),n.addOpsetImport(e,r),n.addProducerName(e,i),n.addProducerVersion(e,o),n.addDomain(e,s),n.addModelVersion(e,a),n.addDocString(e,u),n.addGraph(e,l),n.addGraphDocString(e,c),n.endModel(e)}}t.Model=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){class t{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsKernelCreateInfos(e,n){return(n||new t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsKernelCreateInfos(e,n){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new t).__init(e.readInt32(e.position())+e.position(),e)}nodeIndices(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb.__vector(this.bb_pos+t)+4*e):0}nodeIndicesLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}nodeIndicesArray(){let e=this.bb.__offset(this.bb_pos,4);return e?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}kernelDefHashes(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}kernelDefHashesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}static startKernelCreateInfos(e){e.startObject(2)}static addNodeIndices(e,t){e.addFieldOffset(0,t,0)}static createNodeIndicesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startNodeIndicesVector(e,t){e.startVector(4,t,4)}static addKernelDefHashes(e,t){e.addFieldOffset(1,t,0)}static createKernelDefHashesVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startKernelDefHashesVector(e,t){e.startVector(8,t,8)}static endKernelCreateInfos(e){return e.endObject()}static createKernelCreateInfos(e,n,r){return t.startKernelCreateInfos(e),t.addNodeIndices(e,n),t.addKernelDefHashes(e,r),t.endKernelCreateInfos(e)}}e.KernelCreateInfos=t}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSubGraphSessionState(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSubGraphSessionState(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}graphId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}sessionState(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSubGraphSessionState(e){e.startObject(2)}static addGraphId(e,t){e.addFieldOffset(0,t,0)}static addSessionState(e,t){e.addFieldOffset(1,t,0)}static endSubGraphSessionState(e){let t=e.endObject();return e.requiredField(t,4),t}static createSubGraphSessionState(e,t,r){return n.startSubGraphSessionState(e),n.addGraphId(e,t),n.addSessionState(e,r),n.endSubGraphSessionState(e)}}t.SubGraphSessionState=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSessionState(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSessionState(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}kernels(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}subGraphSessionStatesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSessionState(e){e.startObject(2)}static addKernels(e,t){e.addFieldOffset(0,t,0)}static addSubGraphSessionStates(e,t){e.addFieldOffset(1,t,0)}static createSubGraphSessionStatesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startSubGraphSessionStatesVector(e,t){e.startVector(4,t,4)}static endSessionState(e){return e.endObject()}static createSessionState(e,t,r){return n.startSessionState(e),n.addKernels(e,t),n.addSubGraphSessionStates(e,r),n.endSessionState(e)}}t.SessionState=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInferenceSession(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsInferenceSession(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static bufferHasIdentifier(e){return e.__has_identifier("ORTM")}ortVersion(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}model(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startInferenceSession(e){e.startObject(3)}static addOrtVersion(e,t){e.addFieldOffset(0,t,0)}static addModel(e,t){e.addFieldOffset(1,t,0)}static addSessionState(e,t){e.addFieldOffset(2,t,0)}static endInferenceSession(e){return e.endObject()}static finishInferenceSessionBuffer(e,t){e.finish(t,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(e,t){e.finish(t,"ORTM",!0)}static createInferenceSession(e,t,r,i){return n.startInferenceSession(e),n.addOrtVersion(e,t),n.addModel(e,r),n.addSessionState(e,i),n.endInferenceSession(e)}}t.InferenceSession=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={}))},1723:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OnnxjsSessionHandler=void 0;const r=n(8453),i=n(9240);t.OnnxjsSessionHandler=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(e,t,n){const o=new Map;for(const t in e)if(Object.hasOwnProperty.call(e,t)){const n=e[t];o.set(t,new i.Tensor(n.dims,n.type,void 0,void 0,n.data))}const s=await this.session.run(o),a={};return s.forEach(((e,t)=>{a[t]=new r.Tensor(e.type,e.data,e.dims)})),a}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6027:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Session=void 0;const r=n(7067),i=n(1296),o=n(1975),s=n(6496),a=n(1315),u=n(1745);t.Session=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=a.Profiler.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,t,n){await this.profiler.event("session","Session.loadModel",(async()=>{const s=await(0,o.resolveBackend)(this.backendHint);if(this.sessionHandler=s.createSessionHandler(this.context),this._model=new u.Model,"string"==typeof e){const t=e.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(e);this.initialize(n,t)}else{const n=await fetch(e),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),t)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{const r=new Uint8Array(e,t||0,n||e.byteLength);this.initialize(r)}}))}initialize(e,t){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",(()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,n,t),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.ExecutionPlan(this._model.graph,this._ops,this.profiler)})),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",(async()=>{const t=this.normalizeAndValidateInputs(e),n=await this._executionPlan.execute(this.sessionHandler,t);return this.createOutput(n)}))}normalizeAndValidateInputs(e){const t=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==t.length)throw new Error(`incorrect input array length: expected ${t.length} but got ${e.length}`)}else{if(e.size!==t.length)throw new Error(`incorrect input map size: expected ${t.length} but got ${e.size}`);const n=new Array(e.size);let r=0;for(let i=0;i<t.length;++i){const o=e.get(t[i]);if(!o)throw new Error(`missing input tensor for: '${name}'`);n[r++]=o}e=n}if(this.context.graphInputTypes&&0!==this.context.graphInputTypes.length&&this.context.graphInputDims&&0!==this.context.graphInputDims.length)this.validateInputTensorDims(this.context.graphInputDims,e,!1);else{const t=this._model.graph.getInputIndices(),n=this._model.graph.getValues(),r=new Array(t.length);for(let i=0;i<t.length;++i){const o=n[t[i]];r[i]=o.type.shape.dims,this.context.graphInputTypes.push(o.type.tensorType),this.context.graphInputDims.push(e[i].dims)}this.validateInputTensorDims(r,e,!0)}return this.validateInputTensorTypes(this.context.graphInputTypes,e),e}validateInputTensorTypes(e,t){for(let n=0;n<t.length;n++){const r=e[n],i=t[n].type;if(r!==i)throw new Error(`input tensor[${n}] check failed: expected type '${r}' but got ${i}`)}}validateInputTensorDims(e,t,n){for(let r=0;r<t.length;r++){const i=e[r],o=t[r].dims;if(!this.compareTensorDims(i,o,n))throw new Error(`input tensor[${r}] check failed: expected shape '[${i.join(",")}]' but got [${o.join(",")}]`)}}compareTensorDims(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;++r)if(e[r]!==t[r]&&(!n||0!==e[r]))return!1;return!0}createOutput(e){const t=this._model.graph.getOutputNames();if(e.length!==t.length)throw new Error("expected number of outputs do not match number of generated outputs");const n=new Map;for(let r=0;r<t.length;++r)n.set(t[r],e[r]);return n}initializeOps(e){const t=e.getNodes();this._ops=new Array(t.length);for(let n=0;n<t.length;n++)this._ops[n]=this.sessionHandler.resolve(t[n],this._model.opsets,e)}}},9240:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Tensor=void 0;const i=n(3442),o=r(n(3720)),s=n(1446),a=n(1287),u=n(7273);var l=a.onnxruntime.experimental.fbs;class c{get data(){if(void 0===this.cache){const e=this.dataProvider(this.dataId);if(e.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=e}return this.cache}get stringData(){if("string"!==this.type)throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if("string"!==this.type)return this.data;throw new TypeError("type cannot be non-number (string)")}get(e){return this.data[u.ShapeUtil.indicesToOffset(e,this.strides)]}set(e,t){this.data[u.ShapeUtil.indicesToOffset(e,this.strides)]=t}async getData(){return void 0===this.cache&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=u.ShapeUtil.computeStrides(this.dims)),this._strides}constructor(e,t,n,r,o,s=i.Guid.create()){this.dims=e,this.type=t,this.dataProvider=n,this.asyncDataProvider=r,this.cache=o,this.dataId=s,this.size=u.ShapeUtil.validateDimsAndCalcSize(e);const a=this.size,l=void 0===n&&void 0===r&&void 0===o;if(void 0!==o&&o.length!==a)throw new RangeError("Input dims doesn't match data length.");if("string"===t){if(!(void 0===o||Array.isArray(o)&&o.every((e=>"string"==typeof e))))throw new TypeError("cache should be a string array");l&&(this.cache=new Array(a))}else{if(void 0!==o){const e=h(t);if(!(o instanceof e))throw new TypeError(`cache should be type ${e.name}`)}if(l){const e=new ArrayBuffer(a*function(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}(t));this.cache=function(e,t){return new(h(t))(e)}(e,t)}}}static fromProto(e){if(!e)throw new Error("cannot construct Value from an empty tensor");const t=u.ProtoUtil.tensorDataTypeFromProto(e.dataType),n=u.ProtoUtil.tensorDimsFromProto(e.dims),r=new c(n,t);if("string"===t)e.stringData.forEach(((e,t)=>{r.data[t]=(0,u.decodeUtf8String)(e)}));else if(e.rawData&&"number"==typeof e.rawData.byteLength&&e.rawData.byteLength>0){const t=r.data,n=new DataView(e.rawData.buffer,e.rawData.byteOffset,e.rawData.byteLength),i=d(e.dataType),o=e.rawData.byteLength/i;if(e.rawData.byteLength%i!=0)throw new Error("invalid buffer length");if(t.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=f(n,e.dataType,r*i);t[r]=o}}else{let t;switch(e.dataType){case s.onnx.TensorProto.DataType.FLOAT:t=e.floatData;break;case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.INT16:case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.BOOL:t=e.int32Data;break;case s.onnx.TensorProto.DataType.INT64:t=e.int64Data;break;case s.onnx.TensorProto.DataType.DOUBLE:t=e.doubleData;break;case s.onnx.TensorProto.DataType.UINT32:case s.onnx.TensorProto.DataType.UINT64:t=e.uint64Data;break;default:throw new Error("unspecific error")}if(null==t)throw new Error("failed to populate data from a tensorproto value");const n=r.data;if(n.length!==t.length)throw new Error("array length mismatch");for(let r=0;r<t.length;r++){const i=t[r];o.default.isLong(i)?n[r]=p(i,e.dataType):n[r]=i}}return r}static fromData(e,t,n){return new c(t,n,void 0,void 0,e)}static fromOrtTensor(e){if(!e)throw new Error("cannot construct Value from an empty tensor");const t=u.ProtoUtil.tensorDimsFromORTFormat(e),n=u.ProtoUtil.tensorDataTypeFromProto(e.dataType()),r=new c(t,n);if("string"===n)for(let t=0;t<e.stringDataLength();t++)r.data[t]=e.stringData(t);else if(e.rawDataArray()&&"number"==typeof e.rawDataLength()&&e.rawDataLength()>0){const t=r.data,n=new DataView(e.rawDataArray().buffer,e.rawDataArray().byteOffset,e.rawDataLength()),i=d(e.dataType()),o=e.rawDataLength()/i;if(e.rawDataLength()%i!=0)throw new Error("invalid buffer length");if(t.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=f(n,e.dataType(),r*i);t[r]=o}}return r}}function d(e){switch(e){case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.BOOL:return 1;case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT16:return 2;case s.onnx.TensorProto.DataType.FLOAT:case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.UINT32:return 4;case s.onnx.TensorProto.DataType.INT64:case s.onnx.TensorProto.DataType.DOUBLE:case s.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${s.onnx.TensorProto.DataType[e]}`)}}function h(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function p(e,t){if(t===s.onnx.TensorProto.DataType.INT64||t===l.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else{if(t!==s.onnx.TensorProto.DataType.UINT32&&t!==l.TensorDataType.UINT32&&t!==s.onnx.TensorProto.DataType.UINT64&&t!==l.TensorDataType.UINT64)throw new TypeError(`not a LONG type: ${s.onnx.TensorProto.DataType[t]}`);if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}return e.toNumber()}function f(e,t,n){switch(t){case s.onnx.TensorProto.DataType.BOOL:case s.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case s.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case s.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,!0);case s.onnx.TensorProto.DataType.INT16:return e.getInt16(n,!0);case s.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,!0);case s.onnx.TensorProto.DataType.INT32:return e.getInt32(n,!0);case s.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,!0);case s.onnx.TensorProto.DataType.INT64:return p(o.default.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!1),t);case s.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,!0);case s.onnx.TensorProto.DataType.UINT64:return p(o.default.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!0),t);default:throw new Error(`cannot read from DataView for type ${s.onnx.TensorProto.DataType[t]}`)}}t.Tensor=c},7273:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decodeUtf8String=t.MAX_CLIP=t.MIN_CLIP=t.PoolConvUtil=t.ReduceUtil=t.SplitUtil=t.MathUtil=t.ShapeUtil=t.LongUtil=t.ProtoUtil=t.GemmUtil=t.arrayCopyHelper=t.BroadcastUtil=t.MatMulUtil=t.ArrayUtil=t.assert=t.checkInputsShape=void 0;const i=n(5686),o=r(n(3720)),s=n(1446),a=n(9240);t.checkInputsShape=function(e,...t){if(!e||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].dims||e[n].dims.length!==t[n])return!1;return!0},t.assert=function(e,t){if(!e)throw new Error("string"==typeof t?t:t())},t.ArrayUtil=class{static arraysEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}};class u{static preprocessInputShapes(e,t){return[1===e.length?[1,e[0]]:e,1===t.length?[t[0],1]:t]}static postprocessOutputShape(e,t,n){1===t&&e.splice(e.length-2,1),1===n&&e.pop()}static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}}t.MatMulUtil=u;class l{static calcShape(e,t,n=!1){const r=e.length,i=t.length;if(0===r)return t;if(0===i)return e;const o=Math.max(e.length,t.length),s=new Array(o);if(n){if(r<2||i<2)return;const n=u.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(void 0===n)return;[s[o-2],s[o-1]]=n}for(let a=n?3:1;a<=o;a++){const n=r-a<0?1:e[r-a],u=i-a<0?1:t[i-a];if(n!==u&&n>1&&u>1)return;s[o-a]=Math.max(n,u)}return s}static index(e,t){const n=new Array(t.length);return l.fillIndex(e,t,n),n}static fillIndex(e,t,n){const r=e.length-t.length;for(let i=0;i<t.length;i++)n[i]=e[r+i]%t[i]}static calc(e,t,n,r,i){const o=l.calcShape(e.dims,t.dims);if(o){if(r&&!h.areEqual(o,e.dims))return;const s=h.size(o),u=r?e:new a.Tensor(o,i||e.type);if(0===o.length)u.set([],n(e.get([]),t.get([])));else{const r=new Array(o.length),i=new Array(e.dims.length),a=new Array(t.dims.length);let c,d=0,h=0,p=!1,f=!1;0===e.dims.length&&(d=e.get([]),p=!0),0===t.dims.length&&(h=t.get([]),f=!0);for(let g=0;g<s;g++){c=g;for(let e=o.length-1;e>=0;e--)r[e]=c%o[e],c=Math.floor(c/o[e]);p||(l.fillIndex(r,e.dims,i),d=e.get(i)),f||(l.fillIndex(r,t.dims,a),h=t.get(a)),u.set(r,n(d,h))}}return u}}static isValidBroadcast(e,t){const n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==e[n-i]&&e[n-i]!==t[r-i])return!1;return!0}static getBroadcastDims(e,t){const n=e.length,r=[];for(let i=0;i<n;i++){const o=n-1-i,s=e[o]||1;(t[t.length-1-i]||1)>1&&1===s&&r.unshift(o)}return r}}t.BroadcastUtil=l,t.arrayCopyHelper=function(e,t,n,r,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)e[n+o]=t[r+o]},t.GemmUtil=class{static getShapeOfGemmResult(e,t,n,r,i){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let o,s,a;t?(o=e[1],s=e[0]):(o=e[0],s=e[1]);let u=-1;if(r?(a=n[0],u=1):(a=n[1],u=0),n[u]!==s)throw new Error("dimension mismatch");if(o<=0||a<=0||s<=0)throw new Error("invalid shape specified");if(i&&!l.isValidBroadcast(i,[o,a]))throw new Error("gemm: invalid bias shape for broadcast");return[o,a,s]}};class c{static tensorDataTypeFromProto(e){switch(e){case s.onnx.TensorProto.DataType.INT8:return"int8";case s.onnx.TensorProto.DataType.UINT8:return"uint8";case s.onnx.TensorProto.DataType.BOOL:return"bool";case s.onnx.TensorProto.DataType.INT16:return"int16";case s.onnx.TensorProto.DataType.UINT16:return"uint16";case s.onnx.TensorProto.DataType.INT32:return"int32";case s.onnx.TensorProto.DataType.UINT32:return"uint32";case s.onnx.TensorProto.DataType.FLOAT:return"float32";case s.onnx.TensorProto.DataType.DOUBLE:return"float64";case s.onnx.TensorProto.DataType.STRING:return"string";case s.onnx.TensorProto.DataType.INT64:return"int32";case s.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${s.onnx.TensorProto.DataType[e]}`)}}static tensorDataTypeStringToEnum(e){switch(e){case"int8":return s.onnx.TensorProto.DataType.INT8;case"uint8":return s.onnx.TensorProto.DataType.UINT8;case"bool":return s.onnx.TensorProto.DataType.BOOL;case"int16":return s.onnx.TensorProto.DataType.INT16;case"uint16":return s.onnx.TensorProto.DataType.UINT16;case"int32":return s.onnx.TensorProto.DataType.INT32;case"uint32":return s.onnx.TensorProto.DataType.UINT32;case"float32":return s.onnx.TensorProto.DataType.FLOAT;case"float64":return s.onnx.TensorProto.DataType.DOUBLE;case"string":return s.onnx.TensorProto.DataType.STRING;case"int64":return s.onnx.TensorProto.DataType.INT64;case"uint64":return s.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${e}`)}}static tensorDimsFromProto(e){return e.map((e=>o.default.isLong(e)?e.toNumber():e))}static tensorValueTypeFromProto(e){return{tensorType:c.tensorDataTypeFromProto(e.elemType),shape:{dims:c.tensorDimsFromProto(e.shape.dim.map((e=>e.dimValue)))}}}static tensorDimsFromORTFormat(e){const t=[];for(let n=0;n<e.dimsLength();n++)t.push(d.longToNumber(e.dims(n)));return t}static tensorAttributesFromORTFormat(e){const t=[];for(let n=0;n<e.attributesLength();n++)t.push(e.attributes(n));return t}}t.ProtoUtil=c;class d{static longToNumber(e,t){return o.default.isLong(e)?e.toNumber():e instanceof i.flatbuffers.Long?o.default.fromValue({low:e.low,high:e.high,unsigned:null!=t&&t}).toNumber():e}static isLong(e){return o.default.isLong(e)||e instanceof i.flatbuffers.Long}}t.LongUtil=d;class h{static size(e){return h.getSizeFromDimensionRange(e,0,e.length)}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return h.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return h.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=e[i]}return r}static computeStrides(e){const t=e.length;if(0===t)return[];if(1===t)return[1];const n=new Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static transpose(e){return e.slice().reverse()}static indicesToOffset(e,t,n){void 0===n&&(n=e.length);let r=0;for(let i=0;i<n;++i)r+=t[i]*e[i];return r}static offsetToIndices(e,t){const n=t.length;if(0===n)return[];if(1===n)return[e*t[0]];const r=new Array(t.length);for(let n=0;n<r.length-1;++n)r[n]=Math.floor(e/t[n]),e-=r[n]*t[n];return r[r.length-1]=e,r}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((e=>this.normalizeAxis(e,t)))}static incrementIndex(e,t,n){if(0===t.length||0===e.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=t.length;else if(n<=0||n>t.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(e[r]++,!(e[r]<t[r]));--r)e[r]=0}static calculateReshapedDims(e,t){if(0===t.length){if(0===e.length||1===h.size(e))return[];throw new Error("cannot reshape to a scalar Tensor")}const n=t.length,r=new Array(n);let i=-1,o=1;for(let s=0;s<n;s++){if(t[s]<-1)throw new Error("a dimension in shape hints cannot be less than -1");if(-1===t[s]){if(-1!==i)throw new Error("at most one dimension in shape hints can be -1");i=s}else{if(0===t[s]){if(s>=e.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[s]=e[s]}else r[s]=t[s];o*=r[s]}}const s=h.size(e);if(-1!==i){if(s%o!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${t}]`);r[i]=s/o}else if(o!==s)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){const n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}static validateDimsAndCalcSize(e){if(e.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let t=1;for(const n of e){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);t*=n}return t}static flattenShape(e,t){t<0&&(t+=e.length);const n=e.reduce(((e,t)=>e*t),1),r=e.slice(t).reduce(((e,t)=>e*t),1);return[n/r,r]}static squeezeShape(e,t){const n=new Array;t=h.normalizeAxes(t,e.length);for(let r=0;r<e.length;r++){const i=t.indexOf(r)>=0;if(i&&1!==e[r])throw new Error("squeeze an axis of size different than 1");(0===t.length&&e[r]>1||t.length>0&&!i)&&n.push(e[r])}return n}static unsqueezeShape(e,t){const n=new Array(e.length+t.length);n.fill(0);for(let e=0;e<t.length;e++){const r=h.normalizeAxis(t[e],n.length);if(r>=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let t=0;t<n.length;t++)0===n[t]&&(n[t]=e[r++]);if(r!==e.length)throw new Error("the unsqueezed dimension could not be established");return n}}t.ShapeUtil=h,t.MathUtil=class{static sqr(e,t,n,r,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)e[n+o]+=Math.pow(t[r+o],2)}static axpy(e,t,n,r,i,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let s=0;s<i;s++)e[n+s]+=o*t[r+s]}static powx(e,t,n,r,i,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let s=0;s<i;s++)e[n+s]=Math.pow(t[r+s],o)}static mul(e,t,n,r,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+i>t.length)throw new Error("source indices to be copied are outside bounds");if(n+i>e.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)e[n+o]=t[r+o]*e[n+o]}};class p{static splitShape(e,t,n,r){if(0===n.length){if(!r)throw new Error("need to know number of outputs when the 'split' attribute is not specified");p.determineSplit(e[t],r,n)}const i=[],o=[0];for(let r=0;r<n.length;++r){0!==r&&o.push(o[r-1]+n[r-1]);const s=e.slice();s[t]=n[r],i.push(s)}return[i,o]}static determineSplit(e,t,n){if(e%t!=0)throw new Error("cannot split tensor to equal sized parts");for(let r=0;r<t;++r)n.push(e/t)}}t.SplitUtil=p;class f{static calcReduce(e,t,n,r,i){const o=e.dims.slice(0);0===t.length&&o.forEach(((e,n)=>t.push(n)));const s=f.calcReduceShape(o,t,!0),u=h.size(s),c=new a.Tensor(s,e.type),d=h.computeStrides(s),p=h.computeStrides(o),g=new Array(o.length);for(let n=0;n<u;n++){const s=h.offsetToIndices(n,d);l.fillIndex(s,o,g),c.set(s,f.calcReduceByAxis(e.numberData,t,o,0,h.indicesToOffset(g,p),r,i))}return n?c:new a.Tensor(f.calcReduceShape(o,t,n),c.type,void 0,void 0,c.data,c.dataId)}static calcReduceByAxis(e,t,n,r,i,o,s){let a=0;if(r>=t.length)return o(e[i]);const u=t[r],l=u>=n.length?1:h.size(n.slice(u+1));for(let c=0;c<n[u];c++)a=0===c?f.calcReduceByAxis(e,t,n,r+1,i,o,s):s(a,f.calcReduceByAxis(e,t,n,r+1,i,o,s)),i+=l;return a}static calcReduceShape(e,t,n){const r=e.slice();for(let e=0;e<t.length;e++)r[t[e]]=n?1:0;return r.filter((e=>0!==e))}}t.ReduceUtil=f;class g{static adjustPoolAttributes(e,t,n,r,i,o){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw new Error("dilations should be greater than or equal to 1")}else i.push(1);for(let e=0;e<2*n.length;e++)if(e<o.length){if(o[e]<0)throw new Error("pad should be greater than or equal to 1")}else o.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw new Error("kernel shapes need to be greater than 0");if(o[e]>=n[e]||o[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,n,r,i,o){if(o){if(i.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s<e.length-2;s++)g.adjustPadAndReturnShape(e[s+2],t[s],n[s],r[s],i,s,s+e.length-2,o)}}static computePoolOutputShape(e,t,n,r,i,o,s){if(t.length<=0)throw new Error("input shape must be of size greater than 0");const a=[t[0],t[1]];return g.computeShapeHelper(e,t,a,n,r,i,o,s),a}static computeConvOutputShape(e,t,n,r,i,o,s){if(e.length<=0||t.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const a=[e[0],t[0]];return g.computeShapeHelper(!1,e,a,n,r,i,o,s),a}static computeShapeHelper(e,t,n,r,i,o,s,a){if(e)for(let e=0;e<t.length-2;e++)n.push(1);else for(let e=0;e<t.length-2;e++)n.push(g.adjustPadAndReturnShape(t[e+2],r[e],i[e],o[e],s,e,e+t.length-2,a))}static adjustPadAndReturnShape(e,t,n,r,i,o,s,a){const u=n*(r-1)+1;if(!a||"NOTSET"===a)return Math.floor((e+i[o]+i[s]-u)/t+1);switch(a){case"VALID":return i[o]=0,i[s]=0,Math.floor((e-u)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((e+t-1)/t-1)*t+r-e;return i[o]="SAME_LOWER"===a?Math.floor((n+1)/2):Math.floor(n/2),i[s]=n-i[o],Math.floor((e+n-r)/t+1)}default:throw new Error("Unsupported AutoPad type")}}}t.PoolConvUtil=g,t.MIN_CLIP=-34028234663852886e22,t.MAX_CLIP=34028234663852886e22,t.decodeUtf8String=function(e){return(new TextDecoder).decode(e)}},3838:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebGpuBackend=void 0;const r=n(8453),i=n(4955),o=n(7771),s=n(8510),a=n(8305);t.WebGpuBackend=class{constructor(){this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.pendingDispatchNumber=0,this.profilingEnabled=!1}get currentKernelCustomData(){if(null===this.currentKernelId)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(){if(!navigator.gpu)throw new Error("WebGpuBackend: WebGPU is not available.");const e=await navigator.gpu.requestAdapter();if(!e)throw new Error("WebGpuBackend: Failed to get GPU adapter.");const t={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize}};e.features.has("timestamp-query-inside-passes")&&"default"===r.env.webgpu.profilingMode&&(this.profilingEnabled=!0,t.requiredFeatures=["timestamp-query-inside-passes"]),this.device=await e.requestDevice(t),this.gpuDataManager=(0,o.createGpuDataManager)(this),this.programManager=new a.ProgramManager(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},this.profilingEnabled&&(this.profilingQuerySet=this.device.createQuerySet({type:"timestamp",count:2}))}dispose(){}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){return this.computePassEncoder||(this.computePassEncoder=this.getCommandEncoder().beginComputePass()),this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){this.endComputePass(),this.device.queue.submit([this.getCommandEncoder().finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0}run(e,t,n,r,o){if(t.length!==e.inputTypes.length)throw new Error(`Input size must be equal to ${e.inputTypes.length}.`);const s=[];for(let e=0;e<t.length;++e){const n=this.gpuDataManager.get(t[e].data);if(!n)throw new Error(`no GPU data for input: ${t[e].data}`);s[e]=n}const a=((e,t,n)=>{const r=t.map((e=>`${e.join(",")}`)).join("_"),i=n.join("_");let o=e.name;return e.cacheHint&&(o+="["+e.cacheHint+"]"),o+=":"+r+";"+i,o})(e,t.map((e=>e.dims)),s.map((e=>e.type)));let u=this.programManager.getArtifact(a);const l=u?u.programInfo:"function"==typeof e.get?e.get():e,c=0===n.length?l.outputs.map(((e,t)=>t)):n;if(c.length!==l.outputs.length)throw new Error(`Output size ${c.length} must be equal to ${l.outputs.length}.`);const d=[],h=[];for(let e=0;e<l.outputs.length;++e){if(!Number.isInteger(c[e])||c[e]<-2||c[e]>=l.outputs.length)throw new Error(`Invalid output index: ${c[e]}`);const t=-1===c[e],n=-2===c[e],i=t||n?o(l.outputs[e].dataType,l.outputs[e].dims):r(c[e],l.outputs[e].dataType,l.outputs[e].dims),s=this.gpuDataManager.get(i.data);if(!s)throw new Error(`no GPU data for output: ${i.data}`);if(t&&this.temporaryData.push(s),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(s)}d.push(i),h.push(s)}const p=this.programManager.normalizeDispatchGroupSize(l.dispatchGroup(t));return u||(u=this.programManager.build(l,p),this.programManager.setArtifact(a,u)),(0,i.LOG_DEBUG)("info",(()=>`[ProgramManager] run "${l.name}" (key=${a}) with ${p[0]}x${p[1]}x${p[2]}`)),this.programManager.run(u,s,h,p),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){const n=await this.gpuDataManager.download(e);t().set(new Uint8Array(n))}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n){const r=s.WEBGPU_OP_RESOLVE_RULES.get(e);if(!r)throw new Error(`kernel not implemented: ${e}`);this.kernels.set(t,[e,r[0],[r[1],n]])}releaseKernel(e){const t=this.kernelPersistentData.get(e);if(t){for(const e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t){const n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);const[r,o,s]=n;if(null!==this.currentKernelId)throw new Error(`kernel "${r}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&(s[1]=s[0](s[1]),s[0]=void 0),(0,i.LOG_DEBUG)("info",(()=>`[WebGPU] Start to run kernel "${r}"...`)),this.temporaryData=[];try{return o(t,s[1]),0}catch(e){return(0,i.LOG_DEBUG)("warning",`[WebGPU] Kernel "${r}" failed. Error: ${e}`),1}finally{for(const e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}}},7675:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const r=n(7917),i=n(3838),o=n(4955),s=n(6952);class a{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){return new Float32Array(this.module.HEAP8.buffer,this.data,s.ShapeUtil.size(this.dims))}reshape(e){if(s.ShapeUtil.size(e)!==s.ShapeUtil.size(this.dims))throw new Error("Invalid new shape");return new a(this.module,this.dataType,this.data,e)}}class u{get customData(){return this.backend.currentKernelCustomData}constructor(e,t,n){this.module=e,this.backend=t;const r=e.HEAPU32;let i=n>>2;this.opKernelContext=r[i++];const o=r[i++],s=[];for(let t=0;t<o;t++){const t=r[i++],n=r[i++],o=r[i++],u=[];for(let e=0;e<o;e++)u.push(r[i++]);s.push(new a(e,t,n,u))}this.inputs=s}compute(e,t){var n,i,o;const u=null!==(i=null===(n=null==t?void 0:t.inputs)||void 0===n?void 0:n.map((e=>"number"==typeof e?this.inputs[e]:e)))&&void 0!==i?i:this.inputs,l=null!==(o=null==t?void 0:t.outputs)&&void 0!==o?o:[];return this.backend.run(e,u,l,((e,t,n)=>new a(this.module,t,this.output(e,n),n)),((e,t)=>{const n=(0,r.getTensorElementSize)(e);if(!n)throw new Error(`Unsupported data type: ${e}`);const i=n*s.ShapeUtil.size(t);return new a(this.module,e,this.backend.gpuDataManager.create(i).id,t)}))}output(e,t){const n=this.module.stackSave();try{const n=this.module.stackAlloc(4*(1+t.length));let r=n>>2;this.module.HEAPU32[r++]=t.length;for(let e=0;e<t.length;e++)this.module.HEAPU32[r++]=t[e];return this.module._JsepOutput(this.opKernelContext,e,n)}finally{this.module.stackRestore(n)}}}t.init=async e=>{const t=e.jsepInit;if(t&&navigator.gpu){const n=new i.WebGpuBackend;await n.initialize(),t({backend:n},(e=>n.alloc(e)),(e=>n.free(e)),((t,r,i,s=!1)=>{if(s)(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepCopyGpuToGpu: src=${t}, dst=${r}, size=${i}`)),n.memcpy(t,r);else{(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${t}, gpuDataId=${r}, size=${i}`));const s=e.HEAPU8.subarray(t,t+i);n.upload(r,s)}}),(async(t,r,i)=>{(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${t}, dataOffset=${r}, size=${i}`)),await n.download(t,(()=>e.HEAPU8.subarray(r,r+i)))}),((e,t,r)=>n.createKernel(e,t,r)),(e=>n.releaseKernel(e)),((t,r)=>{(0,o.LOG_DEBUG)("verbose",(()=>`[WebGPU] jsepRun: kernel=${t}, contextDataOffset=${r}`));const i=new u(e,n,r);return n.computeKernel(t,i)}))}}},4955:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LOG_DEBUG=t.LOG=void 0;const r=n(8453),i=n(7917),o=["V","I","W","E","F"];t.LOG=(e,t)=>{const n=(0,i.logLevelStringToEnum)(e);var s,a;n>=(0,i.logLevelStringToEnum)(r.env.logLevel)&&(s=n,a="function"==typeof t?t():t,console.log(`[${o[s]},${(new Date).toISOString()}]${a}`))},t.LOG_DEBUG=(...e)=>{r.env.debug&&(0,t.LOG)(...e)}},6952:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_CLIP=t.MIN_CLIP=t.GemmUtil=t.PoolConvUtil=t.ShapeUtil=t.BroadcastUtil=t.MatMulUtil=void 0;class n{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}}t.MatMulUtil=n;class r{static calcShape(e,t,r=!1){const i=e.length,o=t.length;if(0===i)return t;if(0===o)return e;const s=Math.max(e.length,t.length),a=new Array(s);if(r){if(i<2||o<2)return;const r=n.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(void 0===r)return;[a[s-2],a[s-1]]=r}for(let n=r?3:1;n<=s;n++){const r=i-n<0?1:e[i-n],u=o-n<0?1:t[o-n];if(r!==u&&r>1&&u>1)return;a[s-n]=Math.max(r,u)}return a}static isValidBroadcast(e,t){const n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==e[n-i]&&e[n-i]!==t[r-i])return!1;return!0}}t.BroadcastUtil=r;class i{static size(e){return i.getSizeFromDimensionRange(e,0,e.length)}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return i.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return i.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=e[i]}return r}static computeStrides(e){const t=e.length;if(0===t)return[];if(1===t)return[1];const n=new Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((n=>this.normalizeAxis(n,null!=t?t:e.length)))}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){const n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}}t.ShapeUtil=i;class o{static adjustPoolAttributes(e,t,n,r,i,o){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw new Error("dilations should be greater than or equal to 1")}else i.push(1);for(let e=0;e<2*n.length;e++)if(e<o.length){if(o[e]<0)throw new Error("pad should be greater than or equal to 1")}else o.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw new Error("kernel shapes need to be greater than 0");if(o[e]>=n[e]||o[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,n,r,i,s,a){if(a){if(i.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let u=0;u<e.length-2;u++)o.adjustPadAndReturnShape(e[u+(s?1:2)],t[u],n[u],r[u],i,u,u+e.length-2,a)}}static computePoolOutputShape(e,t,n,r,i,s,a){if(t.length<=0)throw new Error("input shape must be of size greater than 0");const u=[t[0],t[1]];return o.computeShapeHelper(e,t,u,n,r,i,s,a),u}static computeConvOutputShape(e,t,n,r,i,s,a){if(e.length<=0||t.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const u=[e[0],t[0]];return o.computeShapeHelper(!1,e,u,n,r,i,s,a),u}static computeShapeHelper(e,t,n,r,i,s,a,u){if(e)for(let e=0;e<t.length-2;e++)n.push(1);else for(let e=0;e<t.length-2;e++)n.push(o.adjustPadAndReturnShape(t[e+2],r[e],i[e],s[e],a,e,e+t.length-2,u))}static adjustPadAndReturnShape(e,t,n,r,i,o,s,a){const u=n*(r-1)+1;if(!a||"NOTSET"===a)return Math.floor((e+i[o]+i[s]-u)/t+1);switch(a){case"VALID":return i[o]=0,i[s]=0,Math.floor((e-u)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((e+t-1)/t-1)*t+r-e;return i[o]="SAME_LOWER"===a?Math.floor((n+1)/2):Math.floor(n/2),i[s]=n-i[o],Math.floor((e+n-r)/t+1)}default:throw new Error("Unsupported AutoPad type")}}}t.PoolConvUtil=o,t.GemmUtil=class{static getShapeOfGemmResult(e,t,n,i,o){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let s,a,u;t?(s=e[1],a=e[0]):(s=e[0],a=e[1]);let l=-1;if(i?(u=n[0],l=1):(u=n[1],l=0),n[l]!==a)throw new Error("dimension mismatch");if(s<=0||u<=0||a<=0)throw new Error("invalid shape specified");if(o&&!r.isValidBroadcast(o,[s,u]))throw new Error("gemm: invalid bias shape for broadcast");return[s,u,a]}},t.MIN_CLIP=-34028234663852886e22,t.MAX_CLIP=34028234663852886e22},387:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAttributeWithCacheKey=void 0;class n{constructor(e){Object.assign(this,e)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this._cacheKey}}t.createAttributeWithCacheKey=e=>new n(e)},7771:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createGpuDataManager=void 0;const r=n(4955),i=n(1163),o=e=>16*Math.ceil(e/16);let s=0;class a{constructor(e){this.backend=e,this.storageCache=new Map,this.downloadCache=new Map,this.buffersForUploadingPending=[],this.buffersPending=[]}upload(e,t){const n=t.buffer,i=t.byteOffset,s=t.byteLength,a=o(s),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(u.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${s}`);const l=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=l.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,i,s)),l.unmap();const d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(l,0,u.gpuData.buffer,0,a),(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] GpuDataManager.upload(id=${e})`)),this.buffersForUploadingPending.push(l)}memcpy(e,t){const n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");const r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");const i=o(n.originalSize);this.backend.getCommandEncoder().copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){const n=o(e),a=this.backend.device.createBuffer({size:n,usage:t}),u={id:s++,type:i.GpuDataType.default,buffer:a};return this.storageCache.set(u.id,{gpuData:u,originalSize:e}),(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${u.id}`)),u}get(e){var t;return null===(t=this.storageCache.get(e))||void 0===t?void 0:t.gpuData}release(e){const t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`)),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),this.downloadCache.get(e)&&this.downloadCache.delete(e),t.originalSize}async download(e){const t=this.downloadCache.get(e);if(t)return t.data;const n=this.storageCache.get(e);if(!n)throw new Error("data does not exist");const r=this.backend.getCommandEncoder();this.backend.endComputePass();const i=this.backend.device.createBuffer({size:n.originalSize,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});r.copyBufferToBuffer(n.gpuData.buffer,0,i,0,n.originalSize),this.backend.flush();const o=new Promise((e=>{i.mapAsync(GPUMapMode.READ).then((()=>{const t=i.getMappedRange().slice(0);i.destroy(),e(t)}))}));return this.downloadCache.set(e,{data:o}),o}refreshPendingBuffers(){for(const e of this.buffersForUploadingPending)e.destroy();for(const e of this.buffersPending)e.destroy()}}t.createGpuDataManager=(...e)=>new a(...e)},8510:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WEBGPU_OP_RESOLVE_RULES=void 0;const s=o(n(504)),a=n(9770),u=n(4271),l=n(1522),c=o(n(5262)),d=n(2625),h=o(n(9302));t.WEBGPU_OP_RESOLVE_RULES=new Map([["Abs",[h.abs]],["Acos",[h.acos]],["Acosh",[h.acosh]],["Add",[s.add]],["Asin",[h.asin]],["Asinh",[h.asinh]],["Atan",[h.atan]],["Atanh",[h.atanh]],["AveragePool",[c.averagePool,c.parseAveragePoolAttributes]],["Ceil",[h.ceil]],["ClipV10",[h.clipV10]],["Clip",[h.clip]],["Conv",[a.conv,a.parseConvAttributes]],["Cos",[h.cos]],["Cosh",[h.cosh]],["Div",[s.div]],["Elu",[h.elu,h.parseAlphaAttributes]],["Erf",[h.erf]],["Exp",[h.exp]],["Floor",[h.floor]],["Gemm",[u.gemm,u.parseGemmAttributes]],["GlobalAveragePool",[c.globalAveragePool,c.parseGlobalAveragePoolAttributes]],["GlobalMaxPool",[c.globalMaxPool,c.parseGlobalMaxPoolAttributes]],["LeakyRelu",[h.leakyRelu,h.parseAlphaAttributes]],["MatMul",[l.matMul]],["MaxPool",[c.maxPool,c.parseMaxPoolAttributes]],["Mul",[s.mul]],["Neg",[h.neg]],["Pow",[s.pow]],["Reciprocal",[h.reciprocal]],["Relu",[h.relu]],["Sigmoid",[h.sigmoid]],["Sin",[h.sin]],["Sinh",[h.sinh]],["Sqrt",[h.sqrt]],["Sub",[s.sub]],["Tan",[h.tan]],["Tanh",[h.tanh]],["ThresholdedRelu",[h.thresholdedRelu,h.parseAlphaAttributes]],["Transpose",[d.transpose,d.parseTransposeAttributes]]])},1427:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.biasActivationSnippet=t.activationFnSnippet=t.typeSnippet=void 0,t.typeSnippet=e=>{switch(e){case 1:return"f32";case 2:return"vec2<f32>";case 3:return"vec3<f32>";case 4:return"vec4<f32>";default:throw new Error(`${e}-component is not supported.`)}},t.activationFnSnippet=(e,t=!1,n=!1,r=3)=>"",t.biasActivationSnippet=(e,t)=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n ${t?"value = activation(value, coords);":""}\n `},9456:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createConv2DMatMulProgramInfo=void 0;const r=n(4955),i=n(6952),o=n(1163),s=n(1427),a=n(4085),u=n(158);t.createConv2DMatMulProgramInfo=(e,t,n,l,c,d,h,p,f)=>{const g="NHWC"===n.format,m=g?e[0].dims[3]:e[0].dims[1],b=l[0],y=g?l[2]:l[3],v=g?l[1]:l[2],w=g?l[3]:l[1],S=((m%4==0||m%3==0)&&g||y%4==0&&!g)&&w%4==0,_=g?w:y*v,T=g?y*v:w,x=S?[8,8,1]:[_<=4?4:16,_>4&&T<=4?4:16,1],E=S?[4,4,1]:[_<=4?1:2,_>4&&T<=4?1:2,1],C=[Math.ceil(_/x[0]/E[0]),Math.ceil(T/x[1]/E[1]),Math.ceil(b/x[2]/E[1])];(0,r.LOG_DEBUG)("verbose",(()=>`[conv2d_mm_webgpu] dispatch = ${C}`));const P=S?g&&m%4!=0?3:4:E[0],O=x[1]*E[1],A=x[0]*E[0],k=Math.max(x[0]*P,x[1]),I=c%O==0,M=d%A==0,R=h%k==0,D=S?[P,4,4]:[1,1,1],$=[`@group(0) @binding(0) var<storage, read> x: array<${S&&4===P?"vec4<f32>":"f32"}>;`,`@group(0) @binding(1) var<storage, read> w: array<${S?"vec4<f32>":"f32"}>;`];let L=`\n fn setOutputAtIndex(flatIndex : i32, value : ${S?"vec4<f32>":"f32"}) {\n result[flatIndex] = ${S?"vec4<f32>":"f32"}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${S?"vec4<f32>":"f32"}) {\n let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${S?"/ 4":""}, value);\n }`;return p&&($.push(`@group(0) @binding(2) var<storage, read> bias: array<${S?"vec4<f32>":"f32"}>;`),L+=`\n fn getBiasByOutputCoords(coords : vec4<i32>) -> ${S?"vec4<f32>":"f32"} {\n return bias[coords.${g?"w":"y"}${S?"/ 4":""}];\n }`),Object.assign(Object.assign({},t),{outputs:[{dims:l,dataType:e[0].dataType,gpuDataType:o.GpuDataType.default}],dispatchGroup:()=>({x:C[0],y:C[1],z:C[2]}),getShaderSource:()=>`\n ${a.utilFunctions}\n //struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,\n // outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,\n // dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${$.join("")}\n @group(0) @binding(${$.length}) var<storage, read_write> result: array<${S?"vec4<f32>":"f32"}>;\n //@group(0) @binding(${$.length+1}) var<uniform> uniforms: Uniforms;\n\n const xShape : vec4<i32> = vec4<i32>(${e[0].dims.join(",")});\n const wShape : vec4<i32> = vec4<i32>(${e[1].dims.join(",")});\n const outShape : vec4<i32> = vec4<i32>(${l.join(",")});\n const outShapeStrides : vec3<i32> = vec3<i32>(${i.ShapeUtil.computeStrides(l).slice(0,3).join(",")});\n const filterDims : vec2<i32> = vec2<i32>(${n.kernelShape[0]}, ${n.kernelShape[1]});\n const pad : vec2<i32> = vec2<i32>(${n.pads[0]}, ${n.pads[1]});\n const stride : vec2<i32> = vec2<i32>(${n.strides[0]}, ${n.strides[1]});\n const dilation : vec2<i32> = vec2<i32>(${n.dilations[0]}, ${n.dilations[1]});\n const dimAOuter : i32 = ${c};\n const dimBOuter : i32 = ${d};\n const dimInner : i32 = ${h};\n ${L}\n ${((e,t,n,r,i=!1,o,a=!1,u=4,l=4,c=4)=>{const d=e?"\n let coord = vec4<i32>(batch, xRow, xCol, xCh);\n ":"\n let coord = vec4<i32>(batch, xCh, xRow, xCol);\n ",h=e?"\n let coords = vec4<i32>(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4<i32>(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",p=e?"xShape[1]":"xShape[2]",f=e?"xShape[2]":"xShape[3]",g=e?"row":"col",m=e?"col":"row",b=`\n let inChannels = wShape[2];\n let outWidth = ${e?"outShape[2]":"outShape[3]"};\n let outRow = ${g} / outWidth;\n let outCol = ${g} % outWidth;\n\n let WRow = ${m} / (filterDims[1] * inChannels);\n let WCol = ${m} / inChannels % filterDims[1];\n let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0];\n let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1];\n let xCh = ${m} % inChannels;\n var resData = ${(0,s.typeSnippet)(u)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${p} && xCol >= 0 && xCol < ${f}) {\n ${d}\n let xIndex = getIndexFromCoords4D(coord, xShape);\n ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return"resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(u)}\n }\n return resData;`,y=e?t&&r?`\n let col = colIn * ${u};\n ${b}`:`\n let col = colIn * ${u};\n if (row < dimAOuter && col < dimInner) {\n ${b}\n }\n return ${(0,s.typeSnippet)(u)}(0.0);`:r&&n?`\n let col = colIn * ${u};\n ${b}`:`\n let col = colIn * ${u};\n if (row < dimInner && col < dimBOuter) {\n ${b}\n }\n return ${(0,s.typeSnippet)(u)}(0.0);`,v=`${(e=>{switch(e){case 1:return"return w[row * wShape[3] + colIn];";case 4:return"return w[row * wShape[3] / 4 + colIn];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(l)}`,w=(0,s.typeSnippet)(c),S=e?(0,s.typeSnippet)(u):(0,s.typeSnippet)(l),_=e?(0,s.typeSnippet)(l):(0,s.typeSnippet)(u);return`\n ${(0,s.activationFnSnippet)(o,a,4===c,4)}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${S} {\n ${e?y:v}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${_} {\n ${e?v:y}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${w}) {\n let col = colIn * ${c};\n if (row < dimAOuter && col < dimBOuter)\n {\n var value = valueIn;\n let outWidth = ${e?"outShape[2]":"outShape[3]"};\n ${h}\n ${(0,s.biasActivationSnippet)(i,o)}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`})(g,I,M,R,p,void 0,!1,D[0],D[1],D[2])}\n ${S?(0,u.makeMatMulPackedVec4Source)(E,x,!g,k):(0,u.makeMatMulPackedSource)(E,x,!g,k,!1,void 0,f)}`})}},4085:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.utilFunctions=void 0,t.utilFunctions="\nfn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n outShapeStrides.x, outShapeStrides.y, outShapeStrides.z, 1));\n}\n"},158:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.makeMatMulPackedSource=t.makeMatMulPackedVec4Source=void 0,t.makeMatMulPackedVec4Source=(e,t,n=!1,r=32,i=!1,o=32,s=!1)=>{const a=t[1]*e[1],u=t[0]*e[0],l=n?a:r,c=n?r:a,d=l/t[0],h=r/t[1];if((!n||4!==d||4!==e[1])&&(n||3!==d&&4!==d)||l%t[0]!=0||r%t[1]!=0||4!==e[0])throw new Error(`If transposeA ${n} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${d} must be 3 or 4.\n tileAWidth ${l} must be divisible by workgroupSize[0]${t[0]}. tileInner ${r} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar<workgroup> mm_Asub : array<array<vec${d}<f32>, ${l/d}>, ${c}>;\nvar<workgroup> mm_Bsub : array<array<vec4<f32>, ${u/e[0]}>, ${r}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${d};\nconst tileInner = ${r};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n @builtin(global_invocation_id) globalId : vec3<u32>,\n @builtin(workgroup_id) workgroupId : vec3<u32>) {\n let localRow = i32(localId.y);\n let tileRow = ${s?"0":"localRow * rowPerThread"};\n let tileCol = i32(localId.x);\n\n let globalRow = ${s?"0":"i32(globalId.y) * rowPerThread"};\n let globalCol = i32(globalId.x);\n let batch = ${i?"0":"i32(globalId.z)"};\n let globalRowStart = i32(workgroupId.y) * ${a};\n\n let numTiles = ${i?`${Math.ceil(o/r)}`:"(dimInner - 1) / tileInner + 1"};\n var kStart = ${i?`i32(globalId.z) * ${o}`:"0"};\n\n var acc: array<vec4<f32>, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${h};\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${p=n,p?"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol);\n ":"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol);\n "}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol);\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${3===d?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${((e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`)(n,d)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`;var p};const n=e=>e?"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol);\n ":"\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol);\n ";t.makeMatMulPackedSource=(e,t,r=!1,i=32,o=!1,s=32,a=!1)=>{const u=e[1]*t[1],l=e[0]*t[0],c=r?u:i,d=r?i:u;if(d%t[1]!=0||c%t[0]!=0||i%t[1]!=0)throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);const h=d/t[1],p=c/t[0],f=i/t[1],g=a?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${u};\n let globalColStart = i32(workgroupId.x) * ${l};\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) {\n ${n(r)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${l}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol);\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<f32, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${r?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${u};\n\nlet tileRowA = i32(localId.y) * ${h};\nlet tileColA = i32(localId.x) * ${p};\nlet tileRowB = i32(localId.y) * ${f};\n// Loop over shared dimension.\nfor (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${p}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${n(r)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol);\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<f32, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${(e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];")(r)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var<workgroup> mm_Asub : array<array<f32, ${c}>, ${d}>;\n var<workgroup> mm_Bsub : array<array<f32, ${l}>, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n @builtin(global_invocation_id) globalId : vec3<u32>,\n @builtin(workgroup_id) workgroupId : vec3<u32>) {\n let batch = ${o?"0":"i32(globalId.z)"};\n let numTiles = ${o?`${Math.ceil(s/i)}`:"(dimInner - 1) / tileInner + 1"};\n var kStart = ${o?`i32(globalId.z) * ${s}`:"0"};\n\n var acc : array<array<f32, colPerThread>, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${g}\n }\n`}},504:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sub=t.pow=t.mul=t.div=t.add=void 0;const r=n(6952),i=n(1163),o=n(2075),s=(e,t,n,s,a)=>{const u={name:t,inputTypes:[i.GpuDataType.default,i.GpuDataType.default],cacheHint:a};return Object.assign(Object.assign({},u),{get:()=>((e,t,n,s,a,u=t.dataType)=>{var l,c;const d=!r.ShapeUtil.areEqual(t.dims,n.dims);let h=t.dims,p=r.ShapeUtil.size(t.dims),f=!1;if(d){const e=r.BroadcastUtil.calcShape(t.dims,n.dims,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");h=e,p=r.ShapeUtil.size(h);let i=1;for(let e=0;e<h.length;e++){const r=null!==(l=t.dims[t.dims.length-e])&&void 0!==l?l:1;if(r!==(null!==(c=n.dims[n.dims.length-e])&&void 0!==c?c:1))break;i*=r}i%4==0&&(f=!0)}else f=!0;return Object.assign(Object.assign({},e),{getShaderSource:e=>((e,t,n,i,s,a,u,l,c="f32",d="f32",h="f32")=>{const p=r.ShapeUtil.size(i),f=Math.ceil(p/4);let g,m;"string"==typeof u?g=m=(e,t)=>`${u}((${e}),(${t}))`:"function"==typeof u?g=m=u:(g=u.scalar,m=u.vector);let b="";const y=(0,o.createIndicesHelper)("output",i);if(a){const e=e=>{const t=r.ShapeUtil.computeStrides(e),n=[];for(let r=e.length-1;r>=0;r--){const o=0===i.length?"0u":1===i.length?"(*outputIndices)":`(*outputIndices)[${r+i.length-e.length}]`;n.push(`${t[r]}u * (${o} % ${e[r]}u)`)}return n.length>0?n.join("+"):"0u"};b=`\n ${y.o2iImpl}\n\n fn calcOffsetA(outputIndices: ptr<function, ${y.iType}>) -> u32 {\n return ${e(t)};\n }\n\n fn calcOffsetB(outputIndices: ptr<function, ${y.iType}>) -> u32 {\n return ${e(n)};\n }\n `}let v;if(s)v=a?`\n ${y.indicesVariableDeclaration("outputIndices")}\n ${y.o2iCall("global_idx * 4u","outputIndices")}\n let offsetA = calcOffsetA(&outputIndices);\n let offsetB = calcOffsetB(&outputIndices);\n outputData[global_idx] = ${m("aData[offsetA / 4u]","bData[offsetB / 4u]")};`:`outputData[global_idx] = ${m("aData[global_idx]","bData[global_idx]")};`;else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");const e=e=>{const t=`aData[indexA${e}][componentA${e}]`,n=`bData[indexB${e}][componentB${e}]`;return`\n ${y.o2iCall(`global_idx * 4u + ${e}u`,"outputIndices")}\n let offsetA${e} = calcOffsetA(&outputIndices);\n let offsetB${e} = calcOffsetB(&outputIndices);\n let indexA${e} = offsetA${e} / 4u;\n let indexB${e} = offsetB${e} / 4u;\n let componentA${e} = offsetA${e} % 4u;\n let componentB${e} = offsetB${e} % 4u;\n outputData[global_idx][${e}] = ${g(t,n)};`};v=`\n ${y.indicesVariableDeclaration("outputIndices")}\n ${e(0)}\n ${e(1)}\n ${e(2)}\n ${e(3)}`}return`\n @group(0) @binding(0) var<storage, read> aData : array<vec4<${c}>>;\n @group(0) @binding(1) var<storage, read> bData : array<vec4<${d}>>;\n @group(0) @binding(2) var<storage, read_write> outputData : array<vec4<${h}>>;\n\n ${null!=l?l:""}\n ${b}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(f)}\n ${v}\n }`})(e,t.dims,n.dims,h,f,d,s,a),outputs:[{dims:h,dataType:u,gpuDataType:i.GpuDataType.default}],dispatchGroup:()=>({x:Math.ceil(p/64/(f?4:1))})})})(u,e[0],e[1],n,s)})};t.add=e=>{e.compute(s(e.inputs,"Add",((e,t)=>`${e}+${t}`)))},t.div=e=>{e.compute(s(e.inputs,"Div",((e,t)=>`${e}/${t}`)))},t.mul=e=>{e.compute(s(e.inputs,"Mul",((e,t)=>`${e}*${t}`)))},t.pow=e=>{e.compute(s(e.inputs,"Pow",{scalar:(e,t)=>`pow_f32(${e},${t})`,vector:(e,t)=>`pow_vf32(${e},${t})`},"\n fn pow_f32(a : f32, b : f32) -> f32 {\n if (b == 0.0) {\n return 1.0;\n } else if (a < 0.0 && b != floor(b)) {\n return pow(a, b); // NaN\n }\n return select(sign(a), 1.0, round(abs(b) % 2.0) != 1.0) * pow(abs(a), b);\n }\n fn pow_vf32(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {\n // TODO: implement vectorized pow\n return vec4<f32>(pow_f32(a.x, b.x), pow_f32(a.y, b.y), pow_f32(a.z, b.z), pow_f32(a.w, b.w));\n }\n "))},t.sub=e=>{e.compute(s(e.inputs,"Sub",((e,t)=>`${e}-${t}`)))}},2075:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createShaderHelper=t.createIndicesHelper=t.WORKGROUP_SIZE=void 0;const r=n(6952);t.WORKGROUP_SIZE=64,t.createIndicesHelper=(e,t)=>{const n=t.length<2?"u32":`array<u32, ${t.length}>`,i=r.ShapeUtil.computeStrides(t);let o="";for(let e=0;e<t.length-1;e++)o+=`\n let dim${e} = current / ${i[e]}u;\n let rest${e} = current % ${i[e]}u;\n (*indices)[${e}] = dim${e};\n current = rest${e};\n `;o+=`(*indices)[${t.length-1}] = current;`;const s=t.length<2?"":`\n fn ih_o2i_${e}(offset: u32, indices: ptr<function, ${n}>) {\n var current = offset;\n ${o}\n }`,a=[];if(0===t.length)a.push("0u");else if(t.length<2)a.push("(*indices)");else for(let e=t.length-1;e>=0;e--)a.push(`${i[e]}u * ((*indices)[${e}])`);return{o2iImpl:s,o2iCall:(n,r)=>t.length<2?`${r}=${n};`:`ih_o2i_${e}(${n}, &${r});`,i2oImpl:t.length<2?"":`\n fn ih_i2o_${e}(indices: ptr<function, ${n}>) -> u32 {\n return ${a.join("+")};\n }`,i2oExpression:(n,r)=>t.length<2?`(${r?"*":""}${n})`:`ih_i2o_${e}(${r?"":"&"}${n})`,indicesVariableDeclaration:(e,t)=>`var ${e}:${n}${t?`=${n}(${t.join(",")})`:""};`,iType:n}};class i{constructor(e){this.normalizedDispatchGroup=e}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=t.WORKGROUP_SIZE){const n="number"==typeof e?e:e[0],r="number"==typeof e?1:e[1],i="number"==typeof e?1:e[2],o=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${n}, ${r}, ${i})\n fn main(${o?"@builtin(global_invocation_id) global_id : vec3<u32>":"@builtin(local_invocation_index) local_index : u32,\n @builtin(workgroup_id) workgroup_id : vec3<u32>"}) {\n ${o?"let global_idx = global_id.x;":`let global_idx = (workgroup_id.z * ${this.normalizedDispatchGroup[0]*this.normalizedDispatchGroup[1]}u +\n workgroup_id.y * ${this.normalizedDispatchGroup[0]}u + workgroup_id.x) * ${n*r*i}u + local_index;`}\n `}}t.createShaderHelper=e=>new i(e)},9192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createGroupedConvProgramInfoLoader=void 0;const r=n(6952),i=n(1163),o=n(2075),s=n(9770),a=n(3997);t.createGroupedConvProgramInfoLoader=(e,t,n)=>{const u=(l=e.length>2,c=t.cacheKey,{name:"GroupedConv",inputTypes:l?[i.GpuDataType.default,i.GpuDataType.default,i.GpuDataType.default]:[i.GpuDataType.default,i.GpuDataType.default],cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=e.length>2,c=l?"value += b[output_channel];":"",d=e[0].dims,h=e[1].dims,p=h[0]/n.group,f="f32",{activationFunction:g,applyActivation:m}=(0,a.getActicationSnippet)(n),b=[`@group(0) @binding(0) var<storage, read> x : array<${f}>;`,`@group(0) @binding(1) var<storage, read> w : array<${f}>;`];l&&b.push(`@group(0) @binding(2) var<storage, read> b : array<${f}>;`);const y="NHWC"===n.format,v=(0,s.calculateOutputShape)(d,h,n.dilations,n.pads,n.strides,y),w=r.ShapeUtil.size(v),S=(0,o.createIndicesHelper)("output",v),_=(0,o.createIndicesHelper)("x",d),T=(0,o.createIndicesHelper)("w",h);return Object.assign(Object.assign({},t),{outputs:[{dims:u?u(v):v,dataType:e[0].dataType,gpuDataType:i.GpuDataType.default}],getShaderSource:e=>`\n const strides: vec2<u32> = vec2(${n.strides[0]}u, ${n.strides[1]}u);\n const pads: vec2<u32> = vec2(${n.pads[0]}u, ${n.pads[1]}u);\n\n ${b.join("\n")}\n @group(0) @binding(${b.length}) var<storage, read_write> output : array<${f}>;\n\n ${g}\n ${S.o2iImpl}\n ${_.i2oImpl}\n ${T.i2oImpl}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(w)}\n\n ${S.indicesVariableDeclaration("outputIndices")}\n ${S.o2iCall("global_idx","outputIndices")}\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${y?3:1}];\n let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${y?1:2}], outputIndices[${y?2:3}]) * strides - pads;\n let group_id: u32 = output_channel / ${p}u;\n\n var value: ${f} = ${f}(0);\n for (var wInChannel: u32 = 0u; wInChannel < ${h[1]}u; wInChannel++) {\n let input_channel = group_id * ${h[1]}u + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < ${h[2]}u; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * ${n.dilations[0]}u;\n\n if (xHeight < 0u || xHeight >= ${d[y?1:2]}u) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < ${h[3]}u; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * ${n.dilations[1]}u;\n if (xWidth < 0u || xWidth >= ${d[y?2:3]}u) {\n continue;\n }\n\n ${_.indicesVariableDeclaration("xIndices",y?["batch","xHeight","xWidth","input_channel"]:["batch","input_channel","xHeight","xWidth"])}\n let xVal = x[${_.i2oExpression("xIndices")}];\n ${T.indicesVariableDeclaration("wIndices",["output_channel","wInChannel","wHeight","wWidth"])}\n let wVal = w[${T.i2oExpression("wIndices")}];\n value += xVal*wVal;\n }\n }\n }\n ${c}\n ${m}\n output[global_idx] = value;\n }`,dispatchGroup:()=>({x:Math.ceil(w/64)})})})(e,u,t,n)})}},9770:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.conv=t.parseConvAttributes=t.calculateOutputShape=void 0;const r=n(6952),i=n(387),o=n(9192),s=n(3822),a=n(3997),u=n(2625);t.calculateOutputShape=(e,t,n,r,i,o)=>{const s=e[0],a=e.slice(o?1:2,o?3:4),u=a.length,l=t[0],c=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),d=a.map(((e,t)=>e+r[t]+r[t+u])).map(((e,t)=>Math.floor((e-c[t]+i[t])/i[t])));return d.splice(0,0,s),d.splice(o?3:1,0,l),d};const l=(0,i.createAttributeWithCacheKey)({perm:[2,3,1,0]}),c=(e,t)=>{const n=e.kernelShape.slice();for(let e=2;e<t[1].dims.length;++e)0===n[e-2]&&(n[e-2]=t[1].dims[e]);const i=e.pads.slice();r.PoolConvUtil.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,i,"NHWC"===e.format,e.autoPad);const o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:i,cacheKey:e.cacheKey}),o};t.parseConvAttributes=e=>{const t=(0,a.parseInternalActivationAttributes)(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,s=e.group,u=e.kernel_shape,l=e.pads,c=e.strides,d=e.w_is_const();return(0,i.createAttributeWithCacheKey)(Object.assign({autoPad:r,format:n,dilations:o,group:s,kernelShape:u,pads:l,strides:c,wIsConst:d},t))},t.conv=(e,n)=>{((e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");const n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(1!==e[0].dataType||1!==e[1].dataType)throw new Error("Conv input(X,W) should be float tensor");if(3===e.length&&1!==e[2].dataType)throw new Error("Conv input(bias) should be float tensor")})(e.inputs,n),3===e.inputs[0].dims.length?((e,t)=>{const n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);const i=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),a=[1].concat(t.dilations),u=[1].concat(t.kernelShape),l=c(Object.assign(Object.assign({},t),{pads:i,strides:s,dilations:a,kernelShape:u}),r);e.compute((0,o.createGroupedConvProgramInfoLoader)(r,l,(e=>n?[e[0],e[2],e[3]]:[])))})(e,n):((e,n,r)=>{var i;const a=c(r,n),d=3===n.length,h="NHWC"===r.format,p=n[0].dims[h?1:2],f=n[0].dims[h?2:3],g=n[0].dims[h?3:1],m=n[1].dims[2],b=n[1].dims[3],y=(0,t.calculateOutputShape)(n[0].dims,n[1].dims,r.dilations,a.pads,r.strides,h),v=y[h?1:2],w=y[h?2:3],S=y[h?3:1];if(h&&m===p&&b===f&&"VALID"===r.autoPad||1===m&&1===b&&1===r.dilations[0]&&1===r.dilations[1]&&1===r.strides[0]&&1===r.strides[1]&&("SAME_UPPER"===r.autoPad||"SAME_LOWER"===r.autoPad||"VALID"===r.autoPad))return void e.compute((0,o.createGroupedConvProgramInfoLoader)(n,a));if(!h||1!==r.group)return void e.compute((0,o.createGroupedConvProgramInfoLoader)(n,a));const _=h?v*w:S,T=h?S:v*w,x=m*b*g,E=null!==(i=e.customData.wT)&&void 0!==i?i:e.compute(Object.assign(Object.assign({},u.transposeProgramMetadata),{cacheHint:l.cacheKey,get:()=>(0,u.createTransposeProgramInfo)(n[1],l.perm)}),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.customData.wT&&(e.customData.wT=E);const C=[n[0],E];d&&(h||1!==n[2].dims.length?C.push(n[2]):C.push(n[2].reshape([n[2].dims[0],1,1]))),e.compute((0,s.createConv2DMatMulProgramInfoLoader)(C,a,y,_,T,x,d,!0),{inputs:C})})(e,e.inputs,n)}},3822:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createConv2DMatMulProgramInfoLoader=void 0;const r=n(1163),i=n(9456);t.createConv2DMatMulProgramInfoLoader=(e,t,n,o,s,a,u,l)=>{const c=((e,t)=>({name:"Conv2DMatMul",inputTypes:e?[r.GpuDataType.default,r.GpuDataType.default,r.GpuDataType.default]:[r.GpuDataType.default,r.GpuDataType.default],cacheHint:t}))(u,t.cacheKey);return Object.assign(Object.assign({},c),{get:()=>(0,i.createConv2DMatMulProgramInfo)(e,c,t,n,o,s,a,u,l)})}},3997:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseInternalActivationAttributes=t.getActicationSnippet=void 0;const r=n(6952);t.getActicationSnippet=e=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:"value = max(value, 0.0);"};case"Sigmoid":return{activationFunction:"",applyActivation:"value = (1.0 / (1.0 + exp(-value)));"};case"Clip":return{activationFunction:`const clip_min_=f32(${e.clipMin});const clip_max_=f32(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},t.parseInternalActivationAttributes=e=>{const t=(null==e?void 0:e.activation)||"";if("Clip"===t){const[n,i]=(null==e?void 0:e.activation_params)||[r.MIN_CLIP,r.MAX_CLIP];return{activation:t,clipMax:i,clipMin:n,activationCacheKey:`${t}:${n},${i}`}}return{activation:t,activationCacheKey:t}}},4271:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseGemmAttributes=t.gemm=void 0;const r=n(6952),i=n(387),o=n(1163);t.gemm=(e,t)=>{(e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(1!==e[0].dataType||1!==e[1].dataType||3===e.length&&1!==e[2].dataType)throw new Error("Invalid input type.");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")})(e.inputs),e.compute(((e,t)=>{const n={name:"Gemm",inputTypes:3===e.length?[o.GpuDataType.default,o.GpuDataType.default,o.GpuDataType.default]:[o.GpuDataType.default,o.GpuDataType.default],cacheHint:t.cacheKey};return Object.assign(Object.assign({},n),{get:()=>((e,t,n)=>{const i=t[0].dims.slice(),s=t[1].dims.slice(),[a,u,l]=r.GemmUtil.getShapeOfGemmResult(i,n.transA,s,n.transB,3===t.length?t[2].dims:void 0),c=[a,u];if(!c)throw new Error("Can't use gemm on the given tensors");const d=r.ShapeUtil.size(c);let h="";n.transA&&n.transB?h="value += a[k * M + m] * b[n * K + k];":n.transA&&!n.transB?h="value += a[k * M + m] * b[k * N + n];":!n.transA&&n.transB?h="value += a[m * K + k] * b[n * K + k];":n.transA||n.transB||(h="value += a[m * K + k] * b[k * N + n];");const p="f32",f=1===n.alpha?"":"value *= alpha;",g=3===t.length?`value += beta * c[${((e,t,n)=>{if(0===n.length)return"0u";const r=1===n.length&&1!==e||2===n.length&&n[0]!==e,i=n[n.length-1]!==t;let o="0u";return r||(o+=`+ m * ${n[n.length-1]}u`),i||(o+="+n"),o})(a,u,t[2].dims)}];`:"",m=[`@group(0) @binding(0) var<storage, read> a : array<${p}>;`,`@group(0) @binding(1) var<storage, read> b : array<${p}>;`];return 3===t.length&&m.push(`@group(0) @binding(2) var<storage, read> c : array<${p}>;`),Object.assign(Object.assign({},e),{outputs:[{dims:c,dataType:t[0].dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:e=>`\n const M: u32 = ${a}u;\n const N: u32 = ${u}u;\n const K: u32 = ${l}u;\n const alpha = ${p}(${n.alpha});\n const beta = ${p}(${n.beta});\n\n ${m.join("\n")}\n @group(0) @binding(${t.length}) var<storage, read_write> output : array<${p}>;\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(d)}\n\n let m = global_id.x / N;\n let n = global_id.x % N;\n\n var value = ${p}(0);\n for (var k: u32 = 0u; k<${l}u; k++) {\n ${h}\n }\n\n ${f}\n ${g}\n output[global_id.x] = value;\n\n }`,dispatchGroup:()=>({x:Math.ceil(d/64)})})})(n,e,t)})})(e.inputs,t))},t.parseGemmAttributes=e=>(0,i.createAttributeWithCacheKey)(e)},1522:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matMul=t.createMatmulProgramInfoLoader=void 0;const r=n(6952),i=n(1163),o=n(3997);t.createMatmulProgramInfoLoader=(e,t)=>{const n=(s=e.length>2,a=t.activationCacheKey,{name:"MatMul",inputTypes:s?[i.GpuDataType.default,i.GpuDataType.default,i.GpuDataType.default]:[i.GpuDataType.default,i.GpuDataType.default],cacheHint:a});var s,a;return Object.assign(Object.assign({},n),{get:()=>((e,t,n)=>{const s=t[0].dims,a=t[1].dims,u=r.BroadcastUtil.calcShape(s,a,!0);if(!u)throw new Error("Can't use matmul on the given tensors");const l=r.ShapeUtil.size(u),c="f32",{activationFunction:d,applyActivation:h}=(0,o.getActicationSnippet)(n),p=u[u.length-2],f=s[s.length-1],g=u[u.length-1];return Object.assign(Object.assign({},e),{outputs:[{dims:u,dataType:t[0].dataType,gpuDataType:i.GpuDataType.default}],getShaderSource:e=>`\n const M: u32 = ${p}u;\n const N: u32 = ${g}u;\n const K: u32 = ${f}u;\n\n @group(0) @binding(0) var<storage, read> a : array<${c}>;\n @group(0) @binding(1) var<storage, read> b : array<${c}>;\n @group(0) @binding(2) var<storage, read_write> output : array<${c}>;\n\n ${d}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(l)}\n\n let stack = global_idx / (M * N);\n let mn = global_idx % (M * N);\n let n = global_idx % N;\n let m = mn / N;\n\n let offsetA = stack * (M * K);\n let offsetB = stack * (K * N);\n\n var value = ${c}(0);\n for (var k: u32 = 0u; k<${f}u; k++) {\n value += a[offsetA + m * K + k] * b[offsetB + k * N + n];\n }\n ${h}\n output[global_idx] = value;\n }`,dispatchGroup:()=>({x:Math.ceil(l/64)})})})(n,e,t)})},t.matMul=e=>{(e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.");if(1!==e[0].dataType||1!==e[1].dataType)throw new Error("inputs should be float type")})(e.inputs),e.compute((0,t.createMatmulProgramInfoLoader)(e.inputs,{activation:"",activationCacheKey:""}))}},5262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.globalMaxPool=t.parseGlobalMaxPoolAttributes=t.parseMaxPoolAttributes=t.maxPool=t.globalAveragePool=t.parseGlobalAveragePoolAttributes=t.averagePool=t.parseAveragePoolAttributes=void 0;const r=n(6952),i=n(387),o=n(1163),s=n(2075),a=e=>{if(!e||1!==e.length)throw new Error("Pool ops requires 1 input.");if(4!==e[0].dims.length)throw new Error("Pool ops supports 2-D inputs only for now.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},u=(e,t,n)=>{const i="NHWC"===t.format,o=i?[e[0].dims[0],e[0].dims[3],e[0].dims[1],e[0].dims[2]]:e[0].dims.slice(),s=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),u=t.strides.slice(),l=s?t.dilations.slice():[],c=t.pads.slice();r.PoolConvUtil.adjustPoolAttributes(n,o,a,u,l,c);const d=r.PoolConvUtil.computePoolOutputShape(n,o,u,l,a,c,t.autoPad),h=Object.assign({},t);return s?Object.assign(h,{kernelShape:a,strides:u,pads:c,dilations:l,cacheKey:t.cacheKey}):Object.assign(h,{kernelShape:a,strides:u,pads:c,cacheKey:t.cacheKey}),[h,i?[d[0],d[2],d[3],d[1]]:d]},l=(e,t,n,i,o,a,u,l)=>{const c="NHWC"===i.format,d=t.length,h=r.ShapeUtil.size(n),p=(0,s.createIndicesHelper)("output",n),f=(0,s.createIndicesHelper)("x",t);if(i.kernelShape.length<=2){const n=i.kernelShape[i.kernelShape.length-1],r=i.strides[i.strides.length-1],s=i.pads[i.pads.length/2-1],g=d-(c?2:1);let m="",b="",y="";if(m=s+i.pads[i.pads.length-1]!==0?`\n for (var i: u32 = 0u; i < ${n}u; i++) {\n xIndices[${g}] = indices[${g}] * ${r} - ${s} + i;\n if (xIndices[${g}] < 0 || xIndices[${g}] >= ${t[g]}) {\n pad++;\n continue;\n }\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n }`:`\n for (var i: u32 = 0u; i < ${n}u; i++) {\n xIndices[${g}] = indices[${g}] * ${r} - ${s} + i;\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n }`,2===i.kernelShape.length){const e=i.kernelShape[i.kernelShape.length-2],r=i.strides[i.strides.length-2],o=i.pads[i.pads.length/2-2],s=i.pads[i.pads.length-2],a=d-(c?3:2),u=t[a];b=o+s!==0?`\n for (var j: u32 = 0u; j < ${e}u; j++) {\n xIndices[${a}] = indices[${a}] * ${r} - ${o} + j;\n if (xIndices[${a}] < 0 || xIndices[${a}] >= ${u}) {\n pad+= ${n};\n continue;\n }\n `:`\n for (var j: u32 = 0u; j < ${e}u; j++) {\n xIndices[${a}] = indices[${a}] * ${r} - ${o} + j;\n `,y="\n }\n "}return`\n @group(0) @binding(0) var<storage, read> x : array<${u}>;\n @group(0) @binding(1) var<storage, read_write> output : array<${u}>;\n\n ${p.o2iImpl}\n ${f.i2oImpl}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n ${p.indicesVariableDeclaration("indices")}\n ${p.o2iCall("global_idx","indices")}\n ${p.indicesVariableDeclaration("xIndices")}\n ${p.o2iCall("global_idx","xIndices")}\n\n var value: ${u} = ${u}(${l});\n var pad = 0;\n ${b}\n ${m}\n ${y}\n ${a}\n\n output[global_idx] = value;\n }`}{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");const n=r.ShapeUtil.size(i.kernelShape),s=r.ShapeUtil.computeStrides(i.kernelShape),g=s.length,m=i.pads.length;let b="";return b=i.pads.reduce(((e,t)=>e+t))?`\n if (xIndices[j] >= inputDims[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n }`:`\n }\n let x_val = x[${f.i2oExpression("xIndices")}];\n ${o}\n `,`\n @group(0) @binding(0) var<storage, read> x : array<${u}>;\n @group(0) @binding(1) var<storage, read_write> output : array<${u}>;\n\n ${p.o2iImpl}\n ${f.i2oImpl}\n\n const pads = array<u32, ${m}>(${i.pads.map((e=>`${e}u`)).join(",")});\n const inputDims = array<u32, ${d}>(${t.map((e=>`${e}u`)).join(",")});\n const kernelStrides = array<u32, ${g}>(${s.map((e=>`${e}u`)).join(",")});\n const strides = array<u32, ${g}>(${i.strides.map((e=>`${e}u`)).join(",")});\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n ${p.indicesVariableDeclaration("indices")}\n ${p.o2iCall("global_idx","indices")}\n ${p.indicesVariableDeclaration("xIndices")}\n ${p.o2iCall("global_idx","xIndices")}\n\n var offsets: array<u32, ${g}>;\n\n var value = ${u}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < ${n}u; i++) {\n var offset = i;\n for (var j = 0u; j < ${g-1}u; j++) {\n offsets[j] = offset / kernelStrides[j];\n offset -= offsets[j] * kernelStrides[j];\n }\n offsets[${g-1}] = offset;\n\n isPad = false;\n for (var j = ${d-g}u; j < ${d}u; j++) {\n xIndices[j] = indices[j] * strides[j - ${d-g}u]\n + offsets[j - ${d-g}u] - pads[j - 2u];\n ${b}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},c=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),d=(e,t,n,i)=>{const[s,a]=u(e,i,n),c=r.ShapeUtil.size(s.kernelShape),d="f32";let h="";return s.countIncludePad?h+=`value /= ${d}(${c});`:h+=`value /= ${d}(${c} - pad);`,Object.assign(Object.assign({},t),{outputs:[{dims:a,dataType:e[0].dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:t=>l(t,e[0].dims,a,s,"value += x_val;",h,d,"0.0"),dispatchGroup:()=>({x:Math.ceil(r.ShapeUtil.size(a)/64)})})};t.parseAveragePoolAttributes=e=>{const t=0!==e.count_include_pad,n=c(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,i.createAttributeWithCacheKey)(Object.assign({countIncludePad:t},n))},t.averagePool=(e,t)=>{a(e.inputs);const n={name:"AveragePool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>d(e.inputs,n,!1,t)}))};const h={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""};t.parseGlobalAveragePoolAttributes=e=>{const t=e.format;return Object.assign(Object.assign({format:t},h),{cacheKey:t})},t.globalAveragePool=(e,t)=>{a(e.inputs);const n={name:"GlobalAveragePool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>d(e.inputs,n,!0,t)}))};const p=(e,t,n,i)=>{const[s,a]=u(e,i,n);return Object.assign(Object.assign({},t),{outputs:[{dims:a,dataType:e[0].dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:t=>l(t,e[0].dims,a,s,"\n value = max(x_val, value);\n ","","f32","-1e5"),dispatchGroup:()=>({x:Math.ceil(r.ShapeUtil.size(a)/64)})})};t.maxPool=(e,t)=>{a(e.inputs);const n={name:"MaxPool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>p(e.inputs,n,!1,t)}))},t.parseMaxPoolAttributes=e=>{const t=e.storage_order,n=e.dilations,r=c(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==r.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,i.createAttributeWithCacheKey)(Object.assign({storageOrder:t,dilations:n},r))},t.parseGlobalMaxPoolAttributes=e=>{const t=e.format;return Object.assign(Object.assign({format:t},h),{cacheKey:t})},t.globalMaxPool=(e,t)=>{a(e.inputs);const n={name:"GlobalMaxPool",inputTypes:[o.GpuDataType.default],cacheHint:t.cacheKey};e.compute(Object.assign(Object.assign({},n),{get:()=>p(e.inputs,n,!0,t)}))}},2625:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseTransposeAttributes=t.transpose=t.createTransposeProgramInfo=t.transposeProgramMetadata=void 0;const r=n(6952),i=n(387),o=n(1163),s=n(2075);t.transposeProgramMetadata={name:"Transpose",inputTypes:[o.GpuDataType.default]};const a=(e,t)=>t&&t.length!==e.length?[...e.keys()].reverse():t;t.createTransposeProgramInfo=(e,n)=>{const i=e.dims,u=a(i,n),l=((e,t)=>r.ShapeUtil.sortBasedOnPerm(e,a(e,t)))(i,u),c=i.length,d=r.ShapeUtil.size(l),h=(0,s.createIndicesHelper)("output",l),p=(0,s.createIndicesHelper)("a",i);return Object.assign(Object.assign({},t.transposeProgramMetadata),{outputs:[{dims:l,dataType:e.dataType,gpuDataType:o.GpuDataType.default}],getShaderSource:e=>`\n @group(0) @binding(0) var<storage, read> a : array<f32>;\n @group(0) @binding(1) var<storage, read_write> output : array<f32>;\n\n ${((e,t)=>{const n=[];n.push(`fn perm(a: ptr<function, array<u32, ${t}>>, i: ptr<function, array<u32, ${t}>>) {`);for(let r=0;r<t;++r)n.push(`\t(*a)[${e[r]}]=(*i)[${r}];`);return n.push("\t}"),n.join("\n")})(u,c)}\n ${h.o2iImpl}\n ${p.i2oImpl}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(d)}\n\n ${h.indicesVariableDeclaration("indices")}\n ${h.o2iCall("global_idx","indices")}\n ${p.indicesVariableDeclaration("aIndices")}\n perm(&aIndices, &indices);\n\n output[global_idx] = a[${p.i2oExpression("aIndices")}];\n }`,dispatchGroup:()=>({x:Math.ceil(d/64)})})},t.transpose=(e,n)=>{(e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if(1!==e[0].dataType)throw new Error("input should be float tensor")})(e.inputs),e.compute(Object.assign(Object.assign({},t.transposeProgramMetadata),{cacheHint:n.cacheKey,get:()=>(0,t.createTransposeProgramInfo)(e.inputs[0],n.perm)}))},t.parseTransposeAttributes=e=>(0,i.createAttributeWithCacheKey)({perm:e.perm})},9302:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thresholdedRelu=t.tanh=t.tan=t.sqrt=t.sinh=t.sin=t.sigmoid=t.relu=t.reciprocal=t.neg=t.leakyRelu=t.floor=t.exp=t.erf=t.elu=t.parseAlphaAttributes=t.cosh=t.cos=t.ceil=t.clip=t.clipV10=t.atanh=t.atan=t.asinh=t.asin=t.acosh=t.acos=t.abs=void 0;const r=n(6952),i=n(387),o=n(1163),s=(e,t,n,i,s)=>{const a={name:t,inputTypes:[o.GpuDataType.default],cacheHint:s};return Object.assign(Object.assign({},a),{get:()=>((e,t,n,i)=>Object.assign(Object.assign({},e),{getShaderSource:e=>((e,t,n,r)=>{const i=Math.ceil(t/4);let o="";return o="string"==typeof n?`${n}(a)`:n("a"),`\n @group(0) @binding(0) var<storage, read> inputData : array<vec4<f32>>;\n @group(0) @binding(1) var<storage, read_write> outputData : array<vec4<f32>>;\n\n ${null!=r?r:""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n\n let a = inputData[global_idx];\n outputData[global_idx] = ${o};\n }`})(e,r.ShapeUtil.size(t.dims),n,i),outputs:[{dims:t.dims,dataType:t.dataType,gpuDataType:o.GpuDataType.default}],dispatchGroup:e=>({x:Math.ceil(r.ShapeUtil.size(e[0].dims)/64/4)})}))(a,e,n,i)})};t.abs=e=>{e.compute(s(e.inputs[0],"Abs","abs"))},t.acos=e=>{e.compute(s(e.inputs[0],"Acos","acos"))},t.acosh=e=>{e.compute(s(e.inputs[0],"Acosh","acosh"))},t.asin=e=>{e.compute(s(e.inputs[0],"Asin","asin"))},t.asinh=e=>{e.compute(s(e.inputs[0],"Asinh","asinh"))},t.atan=e=>{e.compute(s(e.inputs[0],"Atan","atan"))},t.atanh=e=>{e.compute(s(e.inputs[0],"Atanh","atanh"))},t.clipV10=(e,t)=>{e.compute(s(e.inputs[0],"Clip",(e=>`clamp(${e}, clip_min_, clip_max_)`),`\n const clip_min_: vec4<f32> = vec4(f32(${t.min}));\n const clip_max_: vec4<f32> = vec4(f32(${t.max}));\n`,t.cacheKey),{inputs:[0]})},t.clip=e=>{const n=(e=>{const t=e.length>=2?e[1].getFloat32Array()[0]:r.MIN_CLIP,n=e.length>=3?e[2].getFloat32Array()[0]:r.MAX_CLIP;return(0,i.createAttributeWithCacheKey)({min:t,max:n})})(e.inputs);(0,t.clipV10)(e,n)},t.ceil=e=>{e.compute(s(e.inputs[0],"Ceil","ceil"))},t.cos=e=>{e.compute(s(e.inputs[0],"Cos","cos"))},t.cosh=e=>{e.compute(s(e.inputs[0],"Cosh","cosh"))},t.parseAlphaAttributes=e=>(0,i.createAttributeWithCacheKey)(e),t.elu=(e,t)=>{e.compute(s(e.inputs[0],"Elu",(e=>`elu_vf32(${e})`),`\n const elu_alpha_: f32 = f32(${t.alpha});\n\n fn elu_f32(a: f32) -> f32 {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<f32>) -> vec4<f32> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},t.erf=e=>{e.compute(s(e.inputs[0],"Erf",(e=>`erf_vf32(${e})`),"\n const r0: f32 = 0.3275911;\n const r1: f32 = 0.254829592;\n const r2: f32 = -0.284496736;\n const r3: f32 = 1.421413741;\n const r4: f32 = -1.453152027;\n const r5: f32 = 1.061405429;\n\n fn erf_vf32(v: vec4<f32>) -> vec4<f32> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n }"))},t.exp=e=>{e.compute(s(e.inputs[0],"Exp","exp"))},t.floor=e=>{e.compute(s(e.inputs[0],"Floor","floor"))},t.leakyRelu=(e,t)=>{e.compute(s(e.inputs[0],"LeakyRelu",(e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<f32>(0.0))`),`const leaky_relu_alpha_: f32 = f32(${t.alpha});`,t.cacheKey))},t.neg=e=>{e.compute(s(e.inputs[0],"Neg",(e=>`-${e}`)))},t.reciprocal=e=>{e.compute(s(e.inputs[0],"Reciprocal",(e=>`1.0/${e}`)))},t.relu=e=>{e.compute(s(e.inputs[0],"Relu",(e=>`select(vec4<f32>(0.0), ${e}, ${e} > vec4<f32>(0.0))`)))},t.sigmoid=e=>{e.compute(s(e.inputs[0],"Sigmoid",(e=>`(1.0 / (1.0 + exp(-${e})))`)))},t.sin=e=>{e.compute(s(e.inputs[0],"Sin","sin"))},t.sinh=e=>{e.compute(s(e.inputs[0],"Sinh","sinh"))},t.sqrt=e=>{e.compute(s(e.inputs[0],"Sqrt","sqrt"))},t.tan=e=>{e.compute(s(e.inputs[0],"Tan","tan"))},t.tanh=e=>{e.compute(s(e.inputs[0],"Tanh","tanh"))},t.thresholdedRelu=(e,t)=>(e.compute(s(e.inputs[0],"ThresholdedRelu",(e=>`select(vec4<f32>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`),`const thresholded_relu_alpha_: vec4<f32> = vec4<f32>(${t.alpha});`,t.cacheKey)),0)},8305:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgramManager=void 0;const r=n(4955),i=n(2075);t.ProgramManager=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r){const i=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.profilingEnabled&&o.writeTimestamp(this.backend.profilingQuerySet,0),o.setPipeline(e.computePipeline);const s=[];for(const e of t)s.push({binding:s.length,resource:{buffer:e.buffer}});for(const e of n)s.push({binding:s.length,resource:{buffer:e.buffer}});const a=i.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:s});if(o.setBindGroup(0,a),o.dispatchWorkgroups(...r),this.backend.pendingDispatchNumber++,this.backend.profilingEnabled){o.writeTimestamp(this.backend.profilingQuerySet,1);const e=this.backend.gpuDataManager.create(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),t=this.backend.gpuDataManager.create(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.backend.endComputePass(),this.backend.getCommandEncoder().resolveQuerySet(this.backend.profilingQuerySet,0,2,e.buffer,0),this.backend.getCommandEncoder().copyBufferToBuffer(e.buffer,0,t.buffer,0,16),this.backend.flush();const n=this.backend.currentKernelId,r=this.backend.kernels.get(n)[0];t.buffer.mapAsync(GPUMapMode.READ).then((()=>{const i=new BigUint64Array(t.buffer.getMappedRange()),o=i[0],s=i[1];t.buffer.unmap(),void 0===this.backend.profilingTimeBase&&(this.backend.profilingTimeBase=o);const a=Number(o-this.backend.profilingTimeBase),u=Number(s-this.backend.profilingTimeBase);if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u))throw new RangeError("incorrect timestamp range");this.backend.gpuDataManager.release(e.id),this.backend.gpuDataManager.release(t.id),console.log(`[profiling] kernel "${n}|${r}" execution time: ${u-a} ns`)}))}this.backend.pendingDispatchNumber>=16&&this.backend.flush()}dispose(){}build(e,t){const n=this.backend.device,o=e.getShaderSource((0,i.createShaderHelper)(t)),s=n.createShaderModule({code:o});return(0,r.LOG_DEBUG)("verbose",(()=>`[WebGPU] shader code: ${o}`)),{programInfo:e,computePipeline:n.createComputePipeline({compute:{module:s,entryPoint:"main"},layout:"auto"})}}normalizeDispatchGroupSize(e){const t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,r="number"==typeof e?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];const o=t*n*r;let s=Math.ceil(Math.sqrt(o));if(s>i){if(s=Math.ceil(Math.cbrt(o)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}return[s,s,1]}}},1163:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.GpuDataType=void 0,(n=t.GpuDataType||(t.GpuDataType={}))[n.default=0]="default",n[n.upload=1]="upload",n[n.profile=2]="profile"},3899:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.iterateExtraOptions=void 0,t.iterateExtraOptions=(e,n,r,i)=>{if("object"==typeof e&&null!==e){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach((([e,o])=>{const s=n?n+e:e;if("object"==typeof o)(0,t.iterateExtraOptions)(o,s+".",r,i);else if("string"==typeof o||"number"==typeof o)i(s,o.toString());else{if("boolean"!=typeof o)throw new Error("Can't handle extra config type: "+typeof o);i(s,o?"1":"0")}}))}},9544:function(e,t,n){"use strict";var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=t.initWasm=void 0;const a=n(8453),u=n(7675),l=s(n(1259)),c=n(263),d=()=>!!a.env.wasm.proxy&&"undefined"!=typeof document;let h,p,f,g=!1,m=!1,b=!1;const y=[],v=[],w=[],S=[],_=[],T=[],x=()=>{if(g||!m||b||!h)throw new Error("worker not ready")},E=e=>{switch(e.data.type){case"init-wasm":g=!1,e.data.err?(b=!0,p[1](e.data.err)):(m=!0,p[0]());break;case"init-ort":e.data.err?f[1](e.data.err):f[0]();break;case"create_allocate":e.data.err?y.shift()[1](e.data.err):y.shift()[0](e.data.out);break;case"create_finalize":e.data.err?v.shift()[1](e.data.err):v.shift()[0](e.data.out);break;case"create":e.data.err?w.shift()[1](e.data.err):w.shift()[0](e.data.out);break;case"release":e.data.err?S.shift()[1](e.data.err):S.shift()[0]();break;case"run":e.data.err?_.shift()[1](e.data.err):_.shift()[0](e.data.out);break;case"end-profiling":e.data.err?T.shift()[1](e.data.err):T.shift()[0]()}},C="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;t.initWasm=async()=>{if(d()){if(m)return;if(g)throw new Error("multiple calls to 'initWasm()' detected.");if(b)throw new Error("previous call to 'initWasm()' failed.");return g=!0,void 0===a.env.wasm.wasmPaths&&C&&0!==C.indexOf("blob:")&&(a.env.wasm.wasmPaths=C.substr(0,+C.lastIndexOf("/")+1)),new Promise(((e,t)=>{null==h||h.terminate(),h=n(8050).Z(),h.onmessage=E,p=[e,t];const r={type:"init-wasm",in:a.env.wasm};h.postMessage(r)}))}return(0,c.initializeWebAssembly)(a.env.wasm)},t.initOrt=async(e,t)=>{if(d())return x(),new Promise(((n,r)=>{f=[n,r];const i={type:"init-ort",in:{numThreads:e,loggingLevel:t}};h.postMessage(i)}));l.initOrt(e,t),await(0,u.init)((0,c.getInstance)())},t.createSessionAllocate=async e=>d()?(x(),new Promise(((t,n)=>{y.push([t,n]);const r={type:"create_allocate",in:{model:e}};h.postMessage(r,[e.buffer])}))):l.createSessionAllocate(e),t.createSessionFinalize=async(e,t)=>d()?(x(),new Promise(((n,r)=>{v.push([n,r]);const i={type:"create_finalize",in:{modeldata:e,options:t}};h.postMessage(i)}))):l.createSessionFinalize(e,t),t.createSession=async(e,t)=>d()?(x(),new Promise(((n,r)=>{w.push([n,r]);const i={type:"create",in:{model:e,options:t}};h.postMessage(i,[e.buffer])}))):l.createSession(e,t),t.releaseSession=async e=>{if(d())return x(),new Promise(((t,n)=>{S.push([t,n]);const r={type:"release",in:e};h.postMessage(r)}));l.releaseSession(e)},t.run=async(e,t,n,r,i)=>d()?(x(),new Promise(((o,s)=>{_.push([o,s]);const a={type:"run",in:{sessionId:e,inputIndices:t,inputs:n,outputIndices:r,options:i}};h.postMessage(a,l.extractTransferableBuffers(n))}))):l.run(e,t,n,r,i),t.endProfiling=async e=>{if(d())return x(),new Promise(((t,n)=>{T.push([t,n]);const r={type:"end-profiling",in:e};h.postMessage(r)}));l.endProfiling(e)}},7918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setRunOptions=void 0;const r=n(3899),i=n(9444),o=n(263);t.setRunOptions=e=>{const t=(0,o.getInstance)();let n=0;const s=[],a=e||{};try{if(void 0===(null==e?void 0:e.logSeverityLevel))a.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===(null==e?void 0:e.logVerbosityLevel))a.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===(null==e?void 0:e.terminate)&&(a.terminate=!1);let o=0;if(void 0!==(null==e?void 0:e.tag)&&(o=(0,i.allocWasmString)(e.tag,s)),n=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),0===n)throw new Error("Can't create run options");return void 0!==(null==e?void 0:e.extra)&&(0,r.iterateExtraOptions)(e.extra,"",new WeakSet,((e,r)=>{const o=(0,i.allocWasmString)(e,s),a=(0,i.allocWasmString)(r,s);if(0!==t._OrtAddRunConfigEntry(n,o,a))throw new Error(`Can't set a run config entry: ${e} - ${r}`)})),[n,s]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),s.forEach(t._free),e}}},6640:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),i=n(8453),o=n(2850),s=n(9544),a=n(7917);let u;t.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(e){const t=await fetch(e),n=await t.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(n))}async loadModel(e,t){if(u||(await(0,s.initOrt)(i.env.wasm.numThreads,(0,a.logLevelStringToEnum)(i.env.logLevel)),u=!0),"string"==typeof e)if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(e);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(n,t)}else{const n=await this.createSessionAllocate(e);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(n,t)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(e,t)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(e,t,n){const r=[],o=[];Object.entries(e).forEach((e=>{const t=e[0],n=e[1],i=this.inputNames.indexOf(t);if(-1===i)throw new Error(`invalid input '${t}'`);r.push(n),o.push(i)}));const a=[];Object.entries(t).forEach((e=>{const t=e[0],n=this.outputNames.indexOf(t);if(-1===n)throw new Error(`invalid output '${t}'`);a.push(n)}));const u=await(0,s.run)(this.sessionId,o,r.map((e=>[e.type,e.dims,e.data])),a,n),l={};for(let e=0;e<u.length;e++)l[this.outputNames[a[e]]]=new i.Tensor(u[e][0],u[e][2],u[e][1]);return l}startProfiling(){}endProfiling(){(0,s.endProfiling)(this.sessionId)}}},7622:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSessionOptions=void 0;const r=n(3899),i=n(9444),o=n(263);t.setSessionOptions=e=>{var t,n,s,a;const u=(0,o.getInstance)();let l=0;const c=[],d=e||{};(e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});const t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)})(d);try{const e=(e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}})(null!==(t=d.graphOptimizationLevel)&&void 0!==t?t:"all"),h=(e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}})(null!==(n=d.executionMode)&&void 0!==n?n:"sequential"),p="string"==typeof d.logId?(0,i.allocWasmString)(d.logId,c):0,f=null!==(s=d.logSeverityLevel)&&void 0!==s?s:2;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log serverity level is not valid: ${f}`);const g=null!==(a=d.logVerbosityLevel)&&void 0!==a?a:0;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log verbosity level is not valid: ${g}`);const m="string"==typeof d.optimizedModelFilePath?(0,i.allocWasmString)(d.optimizedModelFilePath,c):0;if(l=u._OrtCreateSessionOptions(e,!!d.enableCpuMemArena,!!d.enableMemPattern,h,!!d.enableProfiling,0,p,f,g,m),0===l)throw new Error("Can't create session options");return d.executionProviders&&((e,t,n)=>{for(const r of t){let t="string"==typeof r?r:r.name;switch(t){case"xnnpack":t="XNNPACK";break;case"webgpu":t="JS";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${t}`)}const s=(0,i.allocWasmString)(t,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(e,s))throw new Error(`Can't append execution provider: ${t}`)}})(l,d.executionProviders,c),void 0!==d.extra&&(0,r.iterateExtraOptions)(d.extra,"",new WeakSet,((e,t)=>{const n=(0,i.allocWasmString)(e,c),r=(0,i.allocWasmString)(t,c);if(0!==u._OrtAddSessionConfigEntry(l,n,r))throw new Error(`Can't set a session config entry: ${e} - ${t}`)})),[l,c]}catch(e){throw 0!==l&&u._OrtReleaseSessionOptions(l),c.forEach(u._free),e}}},9444:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allocWasmString=void 0;const r=n(263);t.allocWasmString=(e,t)=>{const n=(0,r.getInstance)(),i=n.lengthBytesUTF8(e)+1,o=n._malloc(i);return n.stringToUTF8(e,o,i),t.push(o),o}},7917:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelStringToEnum=t.tensorTypeToTypedArrayConstructor=t.getTensorElementSize=t.tensorDataTypeEnumToString=t.tensorDataTypeStringToEnum=void 0,t.tensorDataTypeStringToEnum=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},t.tensorDataTypeEnumToString=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},t.getTensorElementSize=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],t.tensorTypeToTypedArrayConstructor=e=>{switch(e){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},t.logLevelStringToEnum=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}}},1259:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTransferableBuffers=t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=void 0;const r=n(7918),i=n(7622),o=n(9444),s=n(7917),a=n(263);t.initOrt=(e,t)=>{const n=(0,a.getInstance)()._OrtInit(e,t);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const u=new Map;t.createSessionAllocate=e=>{const t=(0,a.getInstance)(),n=t._malloc(e.byteLength);return t.HEAPU8.set(e,n),[n,e.byteLength]},t.createSessionFinalize=(e,t)=>{const n=(0,a.getInstance)();let r=0,o=0,s=[];try{if([o,s]=(0,i.setSessionOptions)(t),r=n._OrtCreateSession(e[0],e[1],o),0===r)throw new Error("Can't create a session")}finally{n._free(e[0]),0!==o&&n._OrtReleaseSessionOptions(o),s.forEach(n._free)}const l=n._OrtGetInputCount(r),c=n._OrtGetOutputCount(r),d=[],h=[],p=[],f=[];for(let e=0;e<l;e++){const t=n._OrtGetInputName(r,e);if(0===t)throw new Error("Can't get an input name");h.push(t),d.push(n.UTF8ToString(t))}for(let e=0;e<c;e++){const t=n._OrtGetOutputName(r,e);if(0===t)throw new Error("Can't get an output name");f.push(t),p.push(n.UTF8ToString(t))}return u.set(r,[r,h,f]),[r,d,p]},t.createSession=(e,n)=>{const r=(0,t.createSessionAllocate)(e);return(0,t.createSessionFinalize)(r,n)},t.releaseSession=e=>{const t=(0,a.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],i=n[1],o=n[2];i.forEach(t._OrtFree),o.forEach(t._OrtFree),t._OrtReleaseSession(r),u.delete(e)},t.run=async(e,t,n,i,l)=>{const c=(0,a.getInstance)(),d=u.get(e);if(!d)throw new Error("invalid session id");const h=d[0],p=d[1],f=d[2],g=t.length,m=i.length;let b=0,y=[];const v=[],w=[];try{[b,y]=(0,r.setRunOptions)(l);for(let e=0;e<g;e++){const t=n[e][0],r=n[e][1],i=n[e][2];let a,u;if(Array.isArray(i)){u=4*i.length,a=c._malloc(u),w.push(a);let e=a/4;for(let t=0;t<i.length;t++){if("string"!=typeof i[t])throw new TypeError(`tensor data at index ${t} is not a string`);c.HEAPU32[e++]=(0,o.allocWasmString)(i[t],w)}}else u=i.byteLength,a=c._malloc(u),w.push(a),c.HEAPU8.set(new Uint8Array(i.buffer,i.byteOffset,u),a);const l=c.stackSave(),d=c.stackAlloc(4*r.length);try{let e=d/4;r.forEach((t=>c.HEAP32[e++]=t));const n=c._OrtCreateTensor((0,s.tensorDataTypeStringToEnum)(t),a,u,d,r.length);if(0===n)throw new Error("Can't create a tensor");v.push(n)}finally{c.stackRestore(l)}}const e=c.stackSave(),a=c.stackAlloc(4*g),u=c.stackAlloc(4*g),d=c.stackAlloc(4*m),S=c.stackAlloc(4*m);try{let e=a/4,n=u/4,r=d/4,o=S/4;for(let r=0;r<g;r++)c.HEAPU32[e++]=v[r],c.HEAPU32[n++]=p[t[r]];for(let e=0;e<m;e++)c.HEAPU32[r++]=0,c.HEAPU32[o++]=f[i[e]];let l=c._OrtRun(h,u,a,g,S,m,d,b);const y=c.jsepRunPromise;y&&void 0!==y.then&&(l=await y);const w=[];if(0===l)for(let e=0;e<m;e++){const t=c.HEAPU32[d/4+e],n=c.stackSave(),r=c.stackAlloc(16);let i,o=0;try{if(l=c._OrtGetTensorData(t,r,r+4,r+8,r+12),0!==l)throw new Error(`Can't access output tensor data. error code = ${l}`);let e=r/4;const n=c.HEAPU32[e++];o=c.HEAPU32[e++];const a=c.HEAPU32[e++],u=c.HEAPU32[e++],d=[];for(let e=0;e<u;e++)d.push(c.HEAPU32[a/4+e]);c._OrtFree(a);const h=0===d.length?1:d.reduce(((e,t)=>e*t));if(i=(0,s.tensorDataTypeEnumToString)(n),"string"===i){const e=[];let t=o/4;for(let n=0;n<h;n++){const r=c.HEAPU32[t++],i=n===h-1?void 0:c.HEAPU32[t]-r;e.push(c.UTF8ToString(r,i))}w.push([i,d,e])}else{const e=new((0,s.tensorTypeToTypedArrayConstructor)(i))(h);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(c.HEAPU8.subarray(o,o+e.byteLength)),w.push([i,d,e])}}finally{c.stackRestore(n),"string"===i&&o&&c._free(o),c._OrtReleaseTensor(t)}}if(0===l)return w;throw new Error(`failed to call OrtRun(). error code = ${l}.`)}finally{c.stackRestore(e)}}finally{v.forEach(c._OrtReleaseTensor),w.forEach(c._free),c._OrtReleaseRunOptions(b),y.forEach(c._free)}},t.endProfiling=e=>{const t=(0,a.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],i=t._OrtEndProfiling(r);if(0===i)throw new Error("Can't get an profile file name");t._OrtFree(i)},t.extractTransferableBuffers=e=>{const t=[];for(const n of e){const e=n[2];!Array.isArray(e)&&e.buffer&&t.push(e.buffer)}return t}},263:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.dispose=t.getInstance=t.initializeWebAssembly=void 0;const s=o(n(6449)),a=n(932),u=n(3474);let l,c=!1,d=!1,h=!1;t.initializeWebAssembly=async e=>{if(c)return Promise.resolve();if(d)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(h)throw new Error("previous call to 'initializeWebAssembly()' failed.");d=!0;const t=e.initTimeout,r=e.numThreads,i=e.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(e){return!1}})(),p=i&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(e){return!1}})(),f=e.wasmPaths,g="string"==typeof f?f:void 0,m=((e,t)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":e?"ort-wasm-simd.wasm":"ort-wasm.wasm")(p,o),b="object"==typeof f?f[m]:void 0;let y=!1;const v=[];if(t>0&&v.push(new Promise((e=>{setTimeout((()=>{y=!0,e()}),t)}))),v.push(new Promise(((e,t)=>{const r=o?u:a,i={locateFile:(e,t)=>o&&e.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):e.endsWith(".wasm")?b||(null!=g?g:t)+m:t+e};if(o)if("undefined"==typeof Blob)i.mainScriptUrlOrBlob=s.join("/","ort-wasm-threaded.js");else{const e=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;i.mainScriptUrlOrBlob=new Blob([e],{type:"text/javascript"})}r(i).then((t=>{d=!1,c=!0,l=t,e()}),(e=>{d=!1,h=!0,t(e)}))}))),await Promise.race(v),y)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},t.getInstance=()=>{if(c&&l)return l;throw new Error("WebAssembly is not initialized yet.")},t.dispose=()=>{var e;!c||d||h||(d=!0,null===(e=l.PThread)||void 0===e||e.terminateAllThreads(),l=void 0,d=!1,c=!1,h=!0)}},8050:(e,t,n)=>{"use strict";n.d(t,{Z:()=>o});var r=n(6614),i=n.n(r);function o(){return i()('/*!\n* ONNX Runtime Web v1.15.1\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var e={899:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.iterateExtraOptions=void 0,t.iterateExtraOptions=(e,n,r,a)=>{if("object"==typeof e&&null!==e){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach((([e,o])=>{const i=n?n+e:e;if("object"==typeof o)(0,t.iterateExtraOptions)(o,i+".",r,a);else if("string"==typeof o||"number"==typeof o)a(i,o.toString());else{if("boolean"!=typeof o)throw new Error("Can\'t handle extra config type: "+typeof o);a(i,o?"1":"0")}}))}},918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setRunOptions=void 0;const r=n(899),a=n(444),o=n(263);t.setRunOptions=e=>{const t=(0,o.getInstance)();let n=0;const i=[],s=e||{};try{if(void 0===(null==e?void 0:e.logSeverityLevel))s.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===(null==e?void 0:e.logVerbosityLevel))s.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===(null==e?void 0:e.terminate)&&(s.terminate=!1);let o=0;if(void 0!==(null==e?void 0:e.tag)&&(o=(0,a.allocWasmString)(e.tag,i)),n=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,o),0===n)throw new Error("Can\'t create run options");return void 0!==(null==e?void 0:e.extra)&&(0,r.iterateExtraOptions)(e.extra,"",new WeakSet,((e,r)=>{const o=(0,a.allocWasmString)(e,i),s=(0,a.allocWasmString)(r,i);if(0!==t._OrtAddRunConfigEntry(n,o,s))throw new Error(`Can\'t set a run config entry: ${e} - ${r}`)})),[n,i]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),i.forEach(t._free),e}}},622:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSessionOptions=void 0;const r=n(899),a=n(444),o=n(263);t.setSessionOptions=e=>{var t,n,i,s;const u=(0,o.getInstance)();let c=0;const l=[],f=e||{};(e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});const t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)})(f);try{const e=(e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}})(null!==(t=f.graphOptimizationLevel)&&void 0!==t?t:"all"),p=(e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}})(null!==(n=f.executionMode)&&void 0!==n?n:"sequential"),d="string"==typeof f.logId?(0,a.allocWasmString)(f.logId,l):0,m=null!==(i=f.logSeverityLevel)&&void 0!==i?i:2;if(!Number.isInteger(m)||m<0||m>4)throw new Error(`log serverity level is not valid: ${m}`);const g=null!==(s=f.logVerbosityLevel)&&void 0!==s?s:0;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log verbosity level is not valid: ${g}`);const h="string"==typeof f.optimizedModelFilePath?(0,a.allocWasmString)(f.optimizedModelFilePath,l):0;if(c=u._OrtCreateSessionOptions(e,!!f.enableCpuMemArena,!!f.enableMemPattern,p,!!f.enableProfiling,0,d,m,g,h),0===c)throw new Error("Can\'t create session options");return f.executionProviders&&((e,t,n)=>{for(const r of t){let t="string"==typeof r?r:r.name;switch(t){case"xnnpack":t="XNNPACK";break;case"webgpu":t="JS";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${t}`)}const i=(0,a.allocWasmString)(t,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(e,i))throw new Error(`Can\'t append execution provider: ${t}`)}})(c,f.executionProviders,l),void 0!==f.extra&&(0,r.iterateExtraOptions)(f.extra,"",new WeakSet,((e,t)=>{const n=(0,a.allocWasmString)(e,l),r=(0,a.allocWasmString)(t,l);if(0!==u._OrtAddSessionConfigEntry(c,n,r))throw new Error(`Can\'t set a session config entry: ${e} - ${t}`)})),[c,l]}catch(e){throw 0!==c&&u._OrtReleaseSessionOptions(c),l.forEach(u._free),e}}},444:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allocWasmString=void 0;const r=n(263);t.allocWasmString=(e,t)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(e)+1,o=n._malloc(a);return n.stringToUTF8(e,o,a),t.push(o),o}},917:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelStringToEnum=t.tensorTypeToTypedArrayConstructor=t.getTensorElementSize=t.tensorDataTypeEnumToString=t.tensorDataTypeStringToEnum=void 0,t.tensorDataTypeStringToEnum=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},t.tensorDataTypeEnumToString=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},t.getTensorElementSize=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],t.tensorTypeToTypedArrayConstructor=e=>{switch(e){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},t.logLevelStringToEnum=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}}},259:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTransferableBuffers=t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=void 0;const r=n(918),a=n(622),o=n(444),i=n(917),s=n(263);t.initOrt=(e,t)=>{const n=(0,s.getInstance)()._OrtInit(e,t);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;t.createSessionAllocate=e=>{const t=(0,s.getInstance)(),n=t._malloc(e.byteLength);return t.HEAPU8.set(e,n),[n,e.byteLength]},t.createSessionFinalize=(e,t)=>{const n=(0,s.getInstance)();let r=0,o=0,i=[];try{if([o,i]=(0,a.setSessionOptions)(t),r=n._OrtCreateSession(e[0],e[1],o),0===r)throw new Error("Can\'t create a session")}finally{n._free(e[0]),0!==o&&n._OrtReleaseSessionOptions(o),i.forEach(n._free)}const c=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],d=[],m=[];for(let e=0;e<c;e++){const t=n._OrtGetInputName(r,e);if(0===t)throw new Error("Can\'t get an input name");p.push(t),f.push(n.UTF8ToString(t))}for(let e=0;e<l;e++){const t=n._OrtGetOutputName(r,e);if(0===t)throw new Error("Can\'t get an output name");m.push(t),d.push(n.UTF8ToString(t))}return u.set(r,[r,p,m]),[r,f,d]},t.createSession=(e,n)=>{const r=(0,t.createSessionAllocate)(e);return(0,t.createSessionFinalize)(r,n)},t.releaseSession=e=>{const t=(0,s.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],o=n[2];a.forEach(t._OrtFree),o.forEach(t._OrtFree),t._OrtReleaseSession(r),u.delete(e)},t.run=async(e,t,n,a,c)=>{const l=(0,s.getInstance)(),f=u.get(e);if(!f)throw new Error("invalid session id");const p=f[0],d=f[1],m=f[2],g=t.length,h=a.length;let y=0,v=[];const b=[],w=[];try{[y,v]=(0,r.setRunOptions)(c);for(let e=0;e<g;e++){const t=n[e][0],r=n[e][1],a=n[e][2];let s,u;if(Array.isArray(a)){u=4*a.length,s=l._malloc(u),w.push(s);let e=s/4;for(let t=0;t<a.length;t++){if("string"!=typeof a[t])throw new TypeError(`tensor data at index ${t} is not a string`);l.HEAPU32[e++]=(0,o.allocWasmString)(a[t],w)}}else u=a.byteLength,s=l._malloc(u),w.push(s),l.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),s);const c=l.stackSave(),f=l.stackAlloc(4*r.length);try{let e=f/4;r.forEach((t=>l.HEAP32[e++]=t));const n=l._OrtCreateTensor((0,i.tensorDataTypeStringToEnum)(t),s,u,f,r.length);if(0===n)throw new Error("Can\'t create a tensor");b.push(n)}finally{l.stackRestore(c)}}const e=l.stackSave(),s=l.stackAlloc(4*g),u=l.stackAlloc(4*g),f=l.stackAlloc(4*h),_=l.stackAlloc(4*h);try{let e=s/4,n=u/4,r=f/4,o=_/4;for(let r=0;r<g;r++)l.HEAPU32[e++]=b[r],l.HEAPU32[n++]=d[t[r]];for(let e=0;e<h;e++)l.HEAPU32[r++]=0,l.HEAPU32[o++]=m[a[e]];let c=l._OrtRun(p,u,s,g,_,h,f,y);const v=l.jsepRunPromise;v&&void 0!==v.then&&(c=await v);const w=[];if(0===c)for(let e=0;e<h;e++){const t=l.HEAPU32[f/4+e],n=l.stackSave(),r=l.stackAlloc(16);let a,o=0;try{if(c=l._OrtGetTensorData(t,r,r+4,r+8,r+12),0!==c)throw new Error(`Can\'t access output tensor data. error code = ${c}`);let e=r/4;const n=l.HEAPU32[e++];o=l.HEAPU32[e++];const s=l.HEAPU32[e++],u=l.HEAPU32[e++],f=[];for(let e=0;e<u;e++)f.push(l.HEAPU32[s/4+e]);l._OrtFree(s);const p=0===f.length?1:f.reduce(((e,t)=>e*t));if(a=(0,i.tensorDataTypeEnumToString)(n),"string"===a){const e=[];let t=o/4;for(let n=0;n<p;n++){const r=l.HEAPU32[t++],a=n===p-1?void 0:l.HEAPU32[t]-r;e.push(l.UTF8ToString(r,a))}w.push([a,f,e])}else{const e=new((0,i.tensorTypeToTypedArrayConstructor)(a))(p);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(l.HEAPU8.subarray(o,o+e.byteLength)),w.push([a,f,e])}}finally{l.stackRestore(n),"string"===a&&o&&l._free(o),l._OrtReleaseTensor(t)}}if(0===c)return w;throw new Error(`failed to call OrtRun(). error code = ${c}.`)}finally{l.stackRestore(e)}}finally{b.forEach(l._OrtReleaseTensor),w.forEach(l._free),l._OrtReleaseRunOptions(y),v.forEach(l._free)}},t.endProfiling=e=>{const t=(0,s.getInstance)(),n=u.get(e);if(!n)throw new Error("invalid session id");const r=n[0],a=t._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");t._OrtFree(a)},t.extractTransferableBuffers=e=>{const t=[];for(const n of e){const e=n[2];!Array.isArray(e)&&e.buffer&&t.push(e.buffer)}return t}},263:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return a(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.dispose=t.getInstance=t.initializeWebAssembly=void 0;const i=o(n(449)),s=n(932),u=n(474);let c,l=!1,f=!1,p=!1;t.initializeWebAssembly=async e=>{if(l)return Promise.resolve();if(f)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(p)throw new Error("previous call to \'initializeWebAssembly()\' failed.");f=!0;const t=e.initTimeout,r=e.numThreads,a=e.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(e){return!1}})(),d=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(e){return!1}})(),m=e.wasmPaths,g="string"==typeof m?m:void 0,h=((e,t)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":e?"ort-wasm-simd.wasm":"ort-wasm.wasm")(d,o),y="object"==typeof m?m[h]:void 0;let v=!1;const b=[];if(t>0&&b.push(new Promise((e=>{setTimeout((()=>{v=!0,e()}),t)}))),b.push(new Promise(((e,t)=>{const r=o?u:s,a={locateFile:(e,t)=>o&&e.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):e.endsWith(".wasm")?y||(null!=g?g:t)+h:t+e};if(o)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=i.join("/","ort-wasm-threaded.js");else{const e=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([e],{type:"text/javascript"})}r(a).then((t=>{f=!1,l=!0,c=t,e()}),(e=>{f=!1,p=!0,t(e)}))}))),await Promise.race(b),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},t.getInstance=()=>{if(l&&c)return c;throw new Error("WebAssembly is not initialized yet.")},t.dispose=()=>{var e;!l||f||p||(f=!0,null===(e=c.PThread)||void 0===e||e.terminateAllThreads(),c=void 0,f=!1,l=!1,p=!0)}},474:(e,t,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){function t(){return P.buffer!=D&&G(P.buffer),F}function r(){return P.buffer!=D&&G(P.buffer),U}function a(){return P.buffer!=D&&G(P.buffer),I}function o(){return P.buffer!=D&&G(P.buffer),W}function i(){return P.buffer!=D&&G(P.buffer),j}var s,u,c;e=e||{},s||(s=void 0!==e?e:{}),s.ready=new Promise((function(e,t){u=e,c=t}));var l,f,p,d,m,g,h=Object.assign({},s),y="./this.program",v=(e,t)=>{throw t},b="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=s.ENVIRONMENT_IS_PTHREAD||!1,S="";function T(e){return s.locateFile?s.locateFile(e,S):S+e}if(_){let t;S=w?n(908).dirname(S)+"/":"//",g=()=>{m||(d=n(384),m=n(908))},l=function(e,t){return g(),e=m.normalize(e),d.readFileSync(e,t?void 0:"utf8")},p=e=>((e=l(e,!0)).buffer||(e=new Uint8Array(e)),e),f=(e,t,n)=>{g(),e=m.normalize(e),d.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(y=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof ie))throw e})),process.on("unhandledRejection",(function(e){throw e})),v=(e,t)=>{if(C)throw process.exitCode=e,t;t instanceof ie||x("exiting due to exception: "+t),process.exit(e)},s.inspect=function(){return"[Emscripten Module object]"};try{t=n(925)}catch(e){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),e}n.g.Worker=t.Worker}else(b||w)&&(w?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),_scriptDir&&(S=_scriptDir),S=0!==S.indexOf("blob:")?S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},w&&(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),f=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var A=console.log.bind(console),E=console.warn.bind(console);_&&(g(),A=e=>d.writeSync(1,e+"\\n"),E=e=>d.writeSync(2,e+"\\n"));var M,R=s.print||A,x=s.printErr||E;Object.assign(s,h),h=null,s.thisProgram&&(y=s.thisProgram),s.quit&&(v=s.quit),s.wasmBinary&&(M=s.wasmBinary);var C=s.noExitRuntime||!0;"object"!=typeof WebAssembly&&ne("no native wasm support detected");var P,k,D,F,U,I,W,j,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function Y(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&L)return L.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,n):e.subarray(t,n));for(r="";t<n;){var a=e[t++];if(128&a){var o=63&e[t++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|o);else{var i=63&e[t++];65536>(a=224==(240&a)?(15&a)<<12|o<<6|i:(7&a)<<18|o<<12|i<<6|63&e[t++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function z(e,t){return(e>>>=0)?Y(r(),e,t):""}function B(e,t,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var i=e.charCodeAt(o);if(55296<=i&&57343>=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++o)),127>=i){if(n>=r)break;t[n++>>>0]=i}else{if(2047>=i){if(n+1>=r)break;t[n++>>>0]=192|i>>6}else{if(65535>=i){if(n+2>=r)break;t[n++>>>0]=224|i>>12}else{if(n+3>=r)break;t[n++>>>0]=240|i>>18,t[n++>>>0]=128|i>>12&63}t[n++>>>0]=128|i>>6&63}t[n++>>>0]=128|63&i}}return t[n>>>0]=0,n-a}function N(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function G(e){D=e,s.HEAP8=F=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAP32=I=new Int32Array(e),s.HEAPU8=U=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAPU32=W=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=j=new Float64Array(e)}O&&(D=s.buffer);var q=s.INITIAL_MEMORY||16777216;if(O)P=s.wasmMemory,D=s.buffer;else if(s.wasmMemory)P=s.wasmMemory;else if(!((P=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");P&&(D=P.buffer),q=D.byteLength,G(D);var $,V=[],J=[],Q=[];function X(){var e=s.preRun.shift();V.unshift(e)}var K,Z=0,ee=null,te=null;function ne(e){throw O?postMessage({cmd:"onAbort",arg:e}):s.onAbort&&s.onAbort(e),x(e="Aborted("+e+")"),H=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),c(e),e}function re(){return K.startsWith("data:application/octet-stream;base64,")}function ae(){var e=K;try{if(e==K&&M)return new Uint8Array(M);if(p)return p(e);throw"both async and sync fetching of the wasm failed"}catch(e){ne(e)}}K="ort-wasm-threaded.wasm",re()||(K=T(K));var oe={};function ie(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function se(e){(e=fe.La[e])||ne(),fe.Xa(e)}function ue(e){var t=fe.lb();if(!t)return 6;fe.Ra.push(t),fe.La[e.Ka]=t,t.Ka=e.Ka;var n={cmd:"run",start_routine:e.pb,arg:e.ib,pthread_ptr:e.Ka};return t.Qa=()=>{n.time=performance.now(),t.postMessage(n,e.vb)},t.loaded&&(t.Qa(),delete t.Qa),0}function ce(e){if(O)return He(1,1,e);C||(fe.qb(),s.onExit&&s.onExit(e),H=!0),v(e,new ie(e))}function le(e,t){if(!t&&O)throw de(e),"unwind";ce(e)}var fe={Oa:[],Ra:[],$a:[],La:{},Ua:function(){O&&fe.mb()},xb:function(){},mb:function(){fe.receiveObjectTransfer=fe.ob,fe.threadInitTLS=fe.Za,fe.setExitStatus=fe.Ya,C=!1},Ya:function(){},qb:function(){for(var e of Object.values(fe.La))fe.Xa(e);for(e of fe.Oa)e.terminate();fe.Oa=[]},Xa:function(e){var t=e.Ka;delete fe.La[t],fe.Oa.push(e),fe.Ra.splice(fe.Ra.indexOf(e),1),e.Ka=0,ct(t)},ob:function(){},Za:function(){fe.$a.forEach((e=>e()))},nb:function(e,t){e.onmessage=n=>{var r=(n=n.data).cmd;if(e.Ka&&(fe.kb=e.Ka),n.targetThread&&n.targetThread!=rt()){var a=fe.La[n.yb];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?De(n.queue):"spawnThread"===r?ue(n):"cleanupThread"===r?se(n.thread):"killThread"===r?(n=n.thread,r=fe.La[n],delete fe.La[n],r.terminate(),ct(n),fe.Ra.splice(fe.Ra.indexOf(r),1),r.Ka=0):"cancelThread"===r?fe.La[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,t&&t(e),e.Qa&&(e.Qa(),delete e.Qa)):"print"===r?R("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?e.postMessage(n):"onAbort"===r?s.onAbort&&s.onAbort(n.arg):r&&x("worker sent an unknown command "+r);fe.kb=void 0},e.onerror=e=>{throw x("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},_&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){}))),e.postMessage({cmd:"load",urlOrBlob:s.mainScriptUrlOrBlob||_scriptDir,wasmMemory:P,wasmModule:k})},hb:function(){var e=T("ort-wasm-threaded.worker.js");fe.Oa.push(new Worker(e))},lb:function(){return 0==fe.Oa.length&&(fe.hb(),fe.nb(fe.Oa[0])),fe.Oa.pop()}};function pe(e){for(;0<e.length;)e.shift()(s)}function de(e){if(O)return He(2,0,e);try{le(e)}catch(e){e instanceof ie||"unwind"==e||v(1,e)}}s.PThread=fe,s.establishStackSpace=function(){var e=rt(),t=a()[e+44>>2>>>0];e=a()[e+48>>2>>>0],ft(t,t-e),dt(t)};var me,ge,he=[];function ye(e){this.Pa=e-24,this.gb=function(e){o()[this.Pa+4>>2>>>0]=e},this.cb=function(e){o()[this.Pa+8>>2>>>0]=e},this.eb=function(){a()[this.Pa>>2>>>0]=0},this.bb=function(){t()[this.Pa+12>>0>>>0]=0},this.fb=function(){t()[this.Pa+13>>0>>>0]=0},this.Ua=function(e,t){this.ab(),this.gb(e),this.cb(t),this.eb(),this.bb(),this.fb()},this.ab=function(){o()[this.Pa+16>>2>>>0]=0}}function ve(e,t,n,r){return O?He(3,1,e,t,n,r):be(e,t,n,r)}function be(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?ve(e,t,n,r):(e={pb:n,Ka:e,ib:r,vb:a},O?(e.wb="spawnThread",postMessage(e,a),0):ue(e))}function we(e,t,n){return O?He(4,1,e,t,n):0}function _e(e,t){if(O)return He(5,1,e,t)}function Oe(e,t){if(O)return He(6,1,e,t)}function Se(e,t,n){if(O)return He(7,1,e,t,n)}function Te(e,t,n){return O?He(8,1,e,t,n):0}function Ae(e,t){if(O)return He(9,1,e,t)}function Ee(e,t,n){if(O)return He(10,1,e,t,n)}function Me(e,t,n,r){if(O)return He(11,1,e,t,n,r)}function Re(e,t,n,r){if(O)return He(12,1,e,t,n,r)}function xe(e,t,n,r){if(O)return He(13,1,e,t,n,r)}function Ce(e){if(O)return He(14,1,e)}function Pe(e,t){if(O)return He(15,1,e,t)}function ke(e,t,n){if(O)return He(16,1,e,t,n)}function De(e){Atomics.store(a(),e>>2,1),rt()&&ut(e),Atomics.compareExchange(a(),e>>2,1,0)}function Fe(e){return o()[e>>>2]+4294967296*a()[e+4>>>2]}function Ue(e,t,n,r,a,o){return O?He(17,1,e,t,n,r,a,o):-52}function Ie(e,t,n,r,a,o){if(O)return He(18,1,e,t,n,r,a,o)}function We(e){var n=N(e)+1,r=at(n);return r&&B(e,t(),r,n),r}function je(e,t,n){function r(e){return(e=e.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?e[1]:"GMT"}if(O)return He(19,1,e,t,n);var i=(new Date).getFullYear(),s=new Date(i,0,1),u=new Date(i,6,1);i=s.getTimezoneOffset();var c=u.getTimezoneOffset(),l=Math.max(i,c);a()[e>>2>>>0]=60*l,a()[t>>2>>>0]=Number(i!=c),e=r(s),t=r(u),e=We(e),t=We(t),c<i?(o()[n>>2>>>0]=e,o()[n+4>>2>>>0]=t):(o()[n>>2>>>0]=t,o()[n+4>>2>>>0]=e)}function He(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=pt();return e=e(),dt(t),e}((()=>{for(var a=mt(8*n),o=a>>3,s=0;s<n;s++){var u=r[2+s];i()[o+s>>>0]=u}return st(e,n,a,t)}))}s.invokeEntryPoint=function(e,t){var n=he[e];n||(e>=he.length&&(he.length=e+1),he[e]=n=$.get(e)),e=n(t),C?fe.Ya(e):lt(e)},s.executeNotifiedProxyingQueue=De,ge=_?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:O?()=>performance.now()-s.__performance_now_clock_drift:()=>performance.now();var Le,Ye=[],ze={};function Be(){if(!Le){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:y||"./this.program"};for(e in ze)void 0===ze[e]?delete t[e]:t[e]=ze[e];var n=[];for(e in t)n.push(e+"="+t[e]);Le=n}return Le}function Ne(e,n){if(O)return He(20,1,e,n);var r=0;return Be().forEach((function(a,i){var s=n+r;for(i=o()[e+4*i>>2>>>0]=s,s=0;s<a.length;++s)t()[i++>>0>>>0]=a.charCodeAt(s);t()[i>>0>>>0]=0,r+=a.length+1})),0}function Ge(e,t){if(O)return He(21,1,e,t);var n=Be();o()[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),o()[t>>2>>>0]=r,0}function qe(e){return O?He(22,1,e):52}function $e(e,t,n,r){return O?He(23,1,e,t,n,r):52}function Ve(e,t,n,r,a){return O?He(24,1,e,t,n,r,a):70}var Je=[null,[],[]];function Qe(e,t,n,a){if(O)return He(25,1,e,t,n,a);for(var i=0,s=0;s<n;s++){var u=o()[t>>2>>>0],c=o()[t+4>>2>>>0];t+=8;for(var l=0;l<c;l++){var f=r()[u+l>>>0],p=Je[e];0===f||10===f?((1===e?R:x)(Y(p,0)),p.length=0):p.push(f)}i+=c}return o()[a>>2>>>0]=i,0}function Xe(e){return 0==e%4&&(0!=e%100||0==e%400)}var Ke=[31,29,31,30,31,30,31,31,30,31,30,31],Ze=[31,28,31,30,31,30,31,31,30,31,30,31];function et(e,n,r,o){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function s(e,t){return i(e,t,"0")}function u(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function c(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function l(e){var t=e.Ma;for(e=new Date(new Date(e.Na+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(Xe(e.getFullYear())?Ke:Ze)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=c(new Date(e.getFullYear(),0,4)),n=c(n),0>=u(t,e)?0>=u(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var f=a()[o+40>>2>>>0];for(var p in o={tb:a()[o>>2>>>0],sb:a()[o+4>>2>>>0],Sa:a()[o+8>>2>>>0],Va:a()[o+12>>2>>>0],Ta:a()[o+16>>2>>>0],Na:a()[o+20>>2>>>0],Ja:a()[o+24>>2>>>0],Ma:a()[o+28>>2>>>0],zb:a()[o+32>>2>>>0],rb:a()[o+36>>2>>>0],ub:f?z(f):""},r=z(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),m="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(e){return d[e.Ja].substring(0,3)},"%A":function(e){return d[e.Ja]},"%b":function(e){return m[e.Ta].substring(0,3)},"%B":function(e){return m[e.Ta]},"%C":function(e){return s((e.Na+1900)/100|0,2)},"%d":function(e){return s(e.Va,2)},"%e":function(e){return i(e.Va,2," ")},"%g":function(e){return l(e).toString().substring(2)},"%G":function(e){return l(e)},"%H":function(e){return s(e.Sa,2)},"%I":function(e){return 0==(e=e.Sa)?e=12:12<e&&(e-=12),s(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.Ta-1;t+=(Xe(e.Na+1900)?Ke:Ze)[n++]);return s(e.Va+t,3)},"%m":function(e){return s(e.Ta+1,2)},"%M":function(e){return s(e.sb,2)},"%n":function(){return"\\n"},"%p":function(e){return 0<=e.Sa&&12>e.Sa?"AM":"PM"},"%S":function(e){return s(e.tb,2)},"%t":function(){return"\\t"},"%u":function(e){return e.Ja||7},"%U":function(e){return s(Math.floor((e.Ma+7-e.Ja)/7),2)},"%V":function(e){var t=Math.floor((e.Ma+7-(e.Ja+6)%7)/7);if(2>=(e.Ja+371-e.Ma-2)%7&&t++,t)53==t&&(4==(n=(e.Ja+371-e.Ma)%7)||3==n&&Xe(e.Na)||(t=1));else{t=52;var n=(e.Ja+7-e.Ma-1)%7;(4==n||5==n&&Xe(e.Na%400-1))&&t++}return s(t,2)},"%w":function(e){return e.Ja},"%W":function(e){return s(Math.floor((e.Ma+7-(e.Ja+6)%7)/7),2)},"%y":function(e){return(e.Na+1900).toString().substring(2)},"%Y":function(e){return e.Na+1900},"%z":function(e){var t=0<=(e=e.rb);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.ub},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](o)));return p=function(e){var t=Array(N(e)+1);return B(e,t,0,t.length),t}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(e,n){t().set(e,n>>>0)}(p,e),p.length-1)}fe.Ua();var tt=[null,ce,de,ve,we,_e,Oe,Se,Te,Ae,Ee,Me,Re,xe,Ce,Pe,ke,Ue,Ie,je,Ne,Ge,qe,$e,Ve,Qe],nt={b:function(e){return at(e+24)+24},c:function(e,t,n){throw new ye(e).Ua(t,n),e},L:function(e){ot(e,!w,1,!b),fe.Za()},l:function(e){O?postMessage({cmd:"cleanupThread",thread:e}):se(e)},D:be,i:we,R:_e,z:Oe,B:Se,T:Te,P:Ae,I:Ee,O:Me,p:Re,A:xe,x:Ce,Q:Pe,y:ke,r:function(){},j:function(){ne("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},s:function(){ne("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},q:function(){return Date.now()},E:function(){return 2097152},V:function(){return!0},F:function(e,t,n,r){if(e==t)setTimeout((()=>De(r)));else if(O)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{if(!(e=fe.La[e]))return;e.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},K:function(){return-1},W:function(e,t){e=new Date(1e3*Fe(e)),a()[t>>2>>>0]=e.getUTCSeconds(),a()[t+4>>2>>>0]=e.getUTCMinutes(),a()[t+8>>2>>>0]=e.getUTCHours(),a()[t+12>>2>>>0]=e.getUTCDate(),a()[t+16>>2>>>0]=e.getUTCMonth(),a()[t+20>>2>>>0]=e.getUTCFullYear()-1900,a()[t+24>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[t+28>>2>>>0]=e},X:function(e,t){e=new Date(1e3*Fe(e)),a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),a()[t+20>>2>>>0]=e.getFullYear()-1900,a()[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1),r=(e.getTime()-n.getTime())/864e5|0;a()[t+28>>2>>>0]=r,a()[t+36>>2>>>0]=-60*e.getTimezoneOffset(),r=new Date(e.getFullYear(),6,1).getTimezoneOffset(),e=0|(r!=(n=n.getTimezoneOffset())&&e.getTimezoneOffset()==Math.min(n,r)),a()[t+32>>2>>>0]=e},Y:function(e){var t=new Date(a()[e+20>>2>>>0]+1900,a()[e+16>>2>>>0],a()[e+12>>2>>>0],a()[e+8>>2>>>0],a()[e+4>>2>>>0],a()[e>>2>>>0],0),n=a()[e+32>>2>>>0],r=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),u=Math.min(s,i);return 0>n?a()[e+32>>2>>>0]=Number(i!=s&&u==r):0<n!=(u==r)&&(i=Math.max(s,i),t.setTime(t.getTime()+6e4*((0<n?u:i)-r))),a()[e+24>>2>>>0]=t.getDay(),n=(t.getTime()-o.getTime())/864e5|0,a()[e+28>>2>>>0]=n,a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},G:Ue,H:Ie,Z:function e(t,n,r){e.jb||(e.jb=!0,je(t,n,r))},d:function(){ne("")},m:function(){if(!_&&!w){var e="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";me||(me={}),me[e]||(me[e]=1,_&&(e="warning: "+e),x(e))}},w:function(){return 4294901760},f:ge,S:function(e,t,n){r().copyWithin(e>>>0,t>>>0,t+n>>>0)},g:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},J:function(e,t,n){Ye.length=t,n>>=3;for(var r=0;r<t;r++)Ye[r]=i()[n+r>>>0];return(0>e?oe[-e-1]:tt[e]).apply(null,Ye)},v:function(e){var t=r().length;if((e>>>=0)<=t||4294901760<e)return!1;for(var n=1;4>=n;n*=2){var a=t*(1+.2/n);a=Math.min(a,e+100663296);var o=Math;a=Math.max(e,a),o=o.min.call(o,4294901760,a+(65536-a%65536)%65536);e:{try{P.grow(o-D.byteLength+65535>>>16),G(P.buffer);var i=1;break e}catch(e){}i=void 0}if(i)return!0}return!1},U:function(){throw"unwind"},M:Ne,N:Ge,k:le,h:qe,o:$e,t:Ve,n:Qe,u:function e(r,a){e.Wa||(e.Wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(_)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>ne("randomDevice")}());for(var o=0;o<a;o++)t()[r+o>>0>>>0]=e.Wa();return 0},a:P||s.wasmMemory,C:et,e:function(e,t,n,r){return et(e,t,n,r)}};!function(){function e(e,t){s.asm=e.exports,fe.$a.push(s.asm.wa),$=s.asm.za,J.unshift(s.asm._),k=t,O||(Z--,s.monitorRunDependencies&&s.monitorRunDependencies(Z),0==Z&&(null!==ee&&(clearInterval(ee),ee=null),te&&(e=te,te=null,e())))}function t(t){e(t.instance,t.module)}function n(e){return function(){if(!M&&(b||w)){if("function"==typeof fetch&&!K.startsWith("file://"))return fetch(K,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at \'"+K+"\'";return e.arrayBuffer()})).catch((function(){return ae()}));if(f)return new Promise((function(e,t){f(K,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return ae()}))}().then((function(e){return WebAssembly.instantiate(e,r)})).then((function(e){return e})).then(e,(function(e){x("failed to asynchronously prepare wasm: "+e),ne(e)}))}var r={a:nt};if(O||(Z++,s.monitorRunDependencies&&s.monitorRunDependencies(Z)),s.instantiateWasm)try{return s.instantiateWasm(r,e)}catch(e){return x("Module.instantiateWasm callback failed with error: "+e),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||re()||K.startsWith("file://")||_||"function"!=typeof fetch?n(t):fetch(K,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(t,(function(e){return x("wasm streaming compile failed: "+e),x("falling back to ArrayBuffer instantiation"),n(t)}))}))).catch(c)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm._).apply(null,arguments)},s._OrtInit=function(){return(s._OrtInit=s.asm.$).apply(null,arguments)},s._OrtCreateSessionOptions=function(){return(s._OrtCreateSessionOptions=s.asm.aa).apply(null,arguments)},s._OrtAppendExecutionProvider=function(){return(s._OrtAppendExecutionProvider=s.asm.ba).apply(null,arguments)},s._OrtAddSessionConfigEntry=function(){return(s._OrtAddSessionConfigEntry=s.asm.ca).apply(null,arguments)},s._OrtReleaseSessionOptions=function(){return(s._OrtReleaseSessionOptions=s.asm.da).apply(null,arguments)},s._OrtCreateSession=function(){return(s._OrtCreateSession=s.asm.ea).apply(null,arguments)},s._OrtReleaseSession=function(){return(s._OrtReleaseSession=s.asm.fa).apply(null,arguments)},s._OrtGetInputCount=function(){return(s._OrtGetInputCount=s.asm.ga).apply(null,arguments)},s._OrtGetOutputCount=function(){return(s._OrtGetOutputCount=s.asm.ha).apply(null,arguments)},s._OrtGetInputName=function(){return(s._OrtGetInputName=s.asm.ia).apply(null,arguments)},s._OrtGetOutputName=function(){return(s._OrtGetOutputName=s.asm.ja).apply(null,arguments)},s._OrtFree=function(){return(s._OrtFree=s.asm.ka).apply(null,arguments)},s._OrtCreateTensor=function(){return(s._OrtCreateTensor=s.asm.la).apply(null,arguments)},s._OrtGetTensorData=function(){return(s._OrtGetTensorData=s.asm.ma).apply(null,arguments)},s._OrtReleaseTensor=function(){return(s._OrtReleaseTensor=s.asm.na).apply(null,arguments)},s._OrtCreateRunOptions=function(){return(s._OrtCreateRunOptions=s.asm.oa).apply(null,arguments)},s._OrtAddRunConfigEntry=function(){return(s._OrtAddRunConfigEntry=s.asm.pa).apply(null,arguments)},s._OrtReleaseRunOptions=function(){return(s._OrtReleaseRunOptions=s.asm.qa).apply(null,arguments)},s._OrtRun=function(){return(s._OrtRun=s.asm.ra).apply(null,arguments)},s._OrtEndProfiling=function(){return(s._OrtEndProfiling=s.asm.sa).apply(null,arguments)};var rt=s._pthread_self=function(){return(rt=s._pthread_self=s.asm.ta).apply(null,arguments)},at=s._malloc=function(){return(at=s._malloc=s.asm.ua).apply(null,arguments)};s._free=function(){return(s._free=s.asm.va).apply(null,arguments)},s.__emscripten_tls_init=function(){return(s.__emscripten_tls_init=s.asm.wa).apply(null,arguments)};var ot=s.__emscripten_thread_init=function(){return(ot=s.__emscripten_thread_init=s.asm.xa).apply(null,arguments)};s.__emscripten_thread_crashed=function(){return(s.__emscripten_thread_crashed=s.asm.ya).apply(null,arguments)};var it,st=s._emscripten_run_in_main_runtime_thread_js=function(){return(st=s._emscripten_run_in_main_runtime_thread_js=s.asm.Aa).apply(null,arguments)},ut=s.__emscripten_proxy_execute_task_queue=function(){return(ut=s.__emscripten_proxy_execute_task_queue=s.asm.Ba).apply(null,arguments)},ct=s.__emscripten_thread_free_data=function(){return(ct=s.__emscripten_thread_free_data=s.asm.Ca).apply(null,arguments)},lt=s.__emscripten_thread_exit=function(){return(lt=s.__emscripten_thread_exit=s.asm.Da).apply(null,arguments)},ft=s._emscripten_stack_set_limits=function(){return(ft=s._emscripten_stack_set_limits=s.asm.Ea).apply(null,arguments)},pt=s.stackSave=function(){return(pt=s.stackSave=s.asm.Fa).apply(null,arguments)},dt=s.stackRestore=function(){return(dt=s.stackRestore=s.asm.Ga).apply(null,arguments)},mt=s.stackAlloc=function(){return(mt=s.stackAlloc=s.asm.Ha).apply(null,arguments)};function gt(){function e(){if(!it&&(it=!0,s.calledRun=!0,!H)&&(O||pe(J),u(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),!O)){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;){var e=s.postRun.shift();Q.unshift(e)}pe(Q)}}if(!(0<Z))if(O)u(s),O||pe(J),postMessage({cmd:"loaded"});else{if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)X();pe(V),0<Z||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),e()}),1)):e())}}if(s.___cxa_is_pointer_type=function(){return(s.___cxa_is_pointer_type=s.asm.Ia).apply(null,arguments)},s.UTF8ToString=z,s.stringToUTF8=function(e,t,n){return B(e,r(),t,n)},s.lengthBytesUTF8=N,s.keepRuntimeAlive=function(){return C},s.wasmMemory=P,s.stackSave=pt,s.stackRestore=dt,s.stackAlloc=mt,s.ExitStatus=ie,s.PThread=fe,te=function e(){it||gt(),it||(te=e)},s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);0<s.preInit.length;)s.preInit.pop()();return gt(),e.ready});e.exports=r},932:(e,t,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,r,a;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){r=e,a=t}));var o,i,s,u,c,l,f=Object.assign({},t),p="./this.program",d=(e,t)=>{throw t},m="object"==typeof window,g="function"==typeof importScripts,h="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,y="";h?(y=g?n(908).dirname(y)+"/":"//",l=()=>{c||(u=n(384),c=n(908))},o=function(e,t){return l(),e=c.normalize(e),u.readFileSync(e,t?void 0:"utf8")},s=e=>((e=o(e,!0)).buffer||(e=new Uint8Array(e)),e),i=(e,t,n)=>{l(),e=c.normalize(e),u.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof $))throw e})),process.on("unhandledRejection",(function(e){throw e})),d=(e,t)=>{if(_)throw process.exitCode=e,t;t instanceof $||w("exiting due to exception: "+t),process.exit(e)},t.inspect=function(){return"[Emscripten Module object]"}):(m||g)&&(g?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),_scriptDir&&(y=_scriptDir),y=0!==y.indexOf("blob:")?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),i=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var v,b=t.print||console.log.bind(console),w=t.printErr||console.warn.bind(console);Object.assign(t,f),f=null,t.thisProgram&&(p=t.thisProgram),t.quit&&(d=t.quit),t.wasmBinary&&(v=t.wasmBinary);var _=t.noExitRuntime||!0;"object"!=typeof WebAssembly&&B("no native wasm support detected");var O,S,T,A,E,M,R=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function C(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&x)return x.decode(e.subarray(t,n));for(r="";t<n;){var a=e[t++];if(128&a){var o=63&e[t++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|o);else{var i=63&e[t++];65536>(a=224==(240&a)?(15&a)<<12|o<<6|i:(7&a)<<18|o<<12|i<<6|63&e[t++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function P(e,t){return(e>>>=0)?C(A,e,t):""}function k(e,t,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var i=e.charCodeAt(o);if(55296<=i&&57343>=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++o)),127>=i){if(n>=r)break;t[n++>>>0]=i}else{if(2047>=i){if(n+1>=r)break;t[n++>>>0]=192|i>>6}else{if(65535>=i){if(n+2>=r)break;t[n++>>>0]=224|i>>12}else{if(n+3>=r)break;t[n++>>>0]=240|i>>18,t[n++>>>0]=128|i>>12&63}t[n++>>>0]=128|i>>6&63}t[n++>>>0]=128|63&i}}return t[n>>>0]=0,n-a}function D(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function F(){var e=O.buffer;S=e,t.HEAP8=T=new Int8Array(e),t.HEAP16=new Int16Array(e),t.HEAP32=E=new Int32Array(e),t.HEAPU8=A=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=M=new Uint32Array(e),t.HEAPF32=new Float32Array(e),t.HEAPF64=new Float64Array(e)}var U=[],I=[],W=[];function j(){var e=t.preRun.shift();U.unshift(e)}var H,L=0,Y=null,z=null;function B(e){throw t.onAbort&&t.onAbort(e),w(e="Aborted("+e+")"),R=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),a(e),e}function N(){return H.startsWith("data:application/octet-stream;base64,")}if(H="ort-wasm.wasm",!N()){var G=H;H=t.locateFile?t.locateFile(G,y):y+G}function q(){var e=H;try{if(e==H&&v)return new Uint8Array(v);if(s)return s(e);throw"both async and sync fetching of the wasm failed"}catch(e){B(e)}}function $(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function V(e){for(;0<e.length;)e.shift()(t)}function J(e){this.sa=e-24,this.Ia=function(e){M[this.sa+4>>2>>>0]=e},this.Ba=function(e){M[this.sa+8>>2>>>0]=e},this.Ga=function(){E[this.sa>>2>>>0]=0},this.Aa=function(){T[this.sa+12>>0>>>0]=0},this.Ha=function(){T[this.sa+13>>0>>>0]=0},this.ya=function(e,t){this.za(),this.Ia(e),this.Ba(t),this.Ga(),this.Aa(),this.Ha()},this.za=function(){M[this.sa+16>>2>>>0]=0}}function Q(e){var t=D(e)+1,n=ie(t);return n&&k(e,T,n,t),n}var X={};function K(){if(!Z){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(e in X)void 0===X[e]?delete t[e]:t[e]=X[e];var n=[];for(e in t)n.push(e+"="+t[e]);Z=n}return Z}var Z,ee=[null,[],[]];function te(e){return 0==e%4&&(0!=e%100||0==e%400)}var ne=[31,29,31,30,31,30,31,31,30,31,30,31],re=[31,28,31,30,31,30,31,31,30,31,30,31];function ae(e,t,n,r){function a(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function o(e,t){return a(e,t,"0")}function i(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function s(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.qa;for(e=new Date(new Date(e.ra+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(te(e.getFullYear())?ne:re)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=s(new Date(e.getFullYear(),0,4)),n=s(n),0>=i(t,e)?0>=i(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var c=E[r+40>>2>>>0];for(var l in r={Ea:E[r>>2>>>0],Da:E[r+4>>2>>>0],ta:E[r+8>>2>>>0],va:E[r+12>>2>>>0],ua:E[r+16>>2>>>0],ra:E[r+20>>2>>>0],la:E[r+24>>2>>>0],qa:E[r+28>>2>>>0],Ja:E[r+32>>2>>>0],Ca:E[r+36>>2>>>0],Fa:c?P(c):""},n=P(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),c[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in c={"%a":function(e){return f[e.la].substring(0,3)},"%A":function(e){return f[e.la]},"%b":function(e){return p[e.ua].substring(0,3)},"%B":function(e){return p[e.ua]},"%C":function(e){return o((e.ra+1900)/100|0,2)},"%d":function(e){return o(e.va,2)},"%e":function(e){return a(e.va,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return o(e.ta,2)},"%I":function(e){return 0==(e=e.ta)?e=12:12<e&&(e-=12),o(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.ua-1;t+=(te(e.ra+1900)?ne:re)[n++]);return o(e.va+t,3)},"%m":function(e){return o(e.ua+1,2)},"%M":function(e){return o(e.Da,2)},"%n":function(){return"\\n"},"%p":function(e){return 0<=e.ta&&12>e.ta?"AM":"PM"},"%S":function(e){return o(e.Ea,2)},"%t":function(){return"\\t"},"%u":function(e){return e.la||7},"%U":function(e){return o(Math.floor((e.qa+7-e.la)/7),2)},"%V":function(e){var t=Math.floor((e.qa+7-(e.la+6)%7)/7);if(2>=(e.la+371-e.qa-2)%7&&t++,t)53==t&&(4==(n=(e.la+371-e.qa)%7)||3==n&&te(e.ra)||(t=1));else{t=52;var n=(e.la+7-e.qa-1)%7;(4==n||5==n&&te(e.ra%400-1))&&t++}return o(t,2)},"%w":function(e){return e.la},"%W":function(e){return o(Math.floor((e.qa+7-(e.la+6)%7)/7),2)},"%y":function(e){return(e.ra+1900).toString().substring(2)},"%Y":function(e){return e.ra+1900},"%z":function(e){var t=0<=(e=e.Ca);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.Fa},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),c)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),c[l](r)));return l=function(e){var t=Array(D(e)+1);return k(e,t,0,t.length),t}(n=n.replace(/\\0\\0/g,"%")),l.length>t?0:(T.set(l,e>>>0),l.length-1)}var oe={a:function(e){return ie(e+24)+24},b:function(e,t,n){throw new J(e).ya(t,n),e},g:function(){return 0},I:function(){},w:function(){},y:function(){},K:function(){return 0},G:function(){},C:function(){},F:function(){},k:function(){},x:function(){},u:function(){},H:function(){},v:function(){},n:function(){},p:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},o:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},l:function(){return Date.now()},L:function(){return!0},M:function(e,t){e=new Date(1e3*(M[e>>>2]+4294967296*E[e+4>>>2])),E[t>>2>>>0]=e.getUTCSeconds(),E[t+4>>2>>>0]=e.getUTCMinutes(),E[t+8>>2>>>0]=e.getUTCHours(),E[t+12>>2>>>0]=e.getUTCDate(),E[t+16>>2>>>0]=e.getUTCMonth(),E[t+20>>2>>>0]=e.getUTCFullYear()-1900,E[t+24>>2>>>0]=e.getUTCDay(),E[t+28>>2>>>0]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},N:function(e,t){e=new Date(1e3*(M[e>>>2]+4294967296*E[e+4>>>2])),E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),E[t+20>>2>>>0]=e.getFullYear()-1900,E[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1);E[t+28>>2>>>0]=(e.getTime()-n.getTime())/864e5|0,E[t+36>>2>>>0]=-60*e.getTimezoneOffset();var r=new Date(e.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[t+32>>2>>>0]=0|(r!=n&&e.getTimezoneOffset()==Math.min(n,r))},O:function(e){var t=new Date(E[e+20>>2>>>0]+1900,E[e+16>>2>>>0],E[e+12>>2>>>0],E[e+8>>2>>>0],E[e+4>>2>>>0],E[e>>2>>>0],0),n=E[e+32>>2>>>0],r=t.getTimezoneOffset(),a=new Date(t.getFullYear(),0,1),o=new Date(t.getFullYear(),6,1).getTimezoneOffset(),i=a.getTimezoneOffset(),s=Math.min(i,o);return 0>n?E[e+32>>2>>>0]=Number(o!=i&&s==r):0<n!=(s==r)&&(o=Math.max(i,o),t.setTime(t.getTime()+6e4*((0<n?s:o)-r))),E[e+24>>2>>>0]=t.getDay(),E[e+28>>2>>>0]=(t.getTime()-a.getTime())/864e5|0,E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},z:function(){return-52},B:function(){},m:function e(t,n,r){e.xa||(e.xa=!0,function(e,t,n){function r(e){return(e=e.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?e[1]:"GMT"}var a=(new Date).getFullYear(),o=new Date(a,0,1),i=new Date(a,6,1);a=o.getTimezoneOffset();var s=i.getTimezoneOffset();E[e>>2>>>0]=60*Math.max(a,s),E[t>>2>>>0]=Number(a!=s),e=r(o),t=r(i),e=Q(e),t=Q(t),s<a?(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t):(M[n>>2>>>0]=t,M[n+4>>2>>>0]=e)}(t,n,r))},d:function(){B("")},t:function(){return 4294901760},h:h?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now(),J:function(e,t,n){A.copyWithin(e>>>0,t>>>0,t+n>>>0)},f:function(e){var t=A.length;if(4294901760<(e>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var a=Math;r=Math.max(e,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);e:{try{O.grow(a-S.byteLength+65535>>>16),F();var o=1;break e}catch(e){}o=void 0}if(o)return!0}return!1},D:function(e,t){var n=0;return K().forEach((function(r,a){var o=t+n;for(a=M[e+4*a>>2>>>0]=o,o=0;o<r.length;++o)T[a++>>0>>>0]=r.charCodeAt(o);T[a>>0>>>0]=0,n+=r.length+1})),0},E:function(e,t){var n=K();M[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),M[t>>2>>>0]=r,0},r:function(e){_||(t.onExit&&t.onExit(e),R=!0),d(e,new $(e))},e:function(){return 52},j:function(){return 52},q:function(){return 70},i:function(e,t,n,r){for(var a=0,o=0;o<n;o++){var i=M[t>>2>>>0],s=M[t+4>>2>>>0];t+=8;for(var u=0;u<s;u++){var c=A[i+u>>>0],l=ee[e];0===c||10===c?((1===e?b:w)(C(l,0)),l.length=0):l.push(c)}a+=s}return M[r>>2>>>0]=a,0},s:function e(t,r){e.wa||(e.wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(h)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>B("randomDevice")}());for(var a=0;a<r;a++)T[t+a>>0>>>0]=e.wa();return 0},A:ae,c:function(e,t,n,r){return ae(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,O=t.asm.P,F(),I.unshift(t.asm.Q),L--,t.monitorRunDependencies&&t.monitorRunDependencies(L),0==L&&(null!==Y&&(clearInterval(Y),Y=null),z&&(e=z,z=null,e()))}function n(t){e(t.instance)}function r(e){return function(){if(!v&&(m||g)){if("function"==typeof fetch&&!H.startsWith("file://"))return fetch(H,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at \'"+H+"\'";return e.arrayBuffer()})).catch((function(){return q()}));if(i)return new Promise((function(e,t){i(H,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return q()}))}().then((function(e){return WebAssembly.instantiate(e,o)})).then((function(e){return e})).then(e,(function(e){w("failed to asynchronously prepare wasm: "+e),B(e)}))}var o={a:oe};if(L++,t.monitorRunDependencies&&t.monitorRunDependencies(L),t.instantiateWasm)try{return t.instantiateWasm(o,e)}catch(e){return w("Module.instantiateWasm callback failed with error: "+e),!1}(v||"function"!=typeof WebAssembly.instantiateStreaming||N()||H.startsWith("file://")||h||"function"!=typeof fetch?r(n):fetch(H,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(n,(function(e){return w("wasm streaming compile failed: "+e),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Q).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.R).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.S).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.T).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.U).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm.V).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.W).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.X).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.Y).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.Z).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm._).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.$).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.aa).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.ba).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.ca).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.da).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.ea).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.fa).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.ga).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.ha).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.ia).apply(null,arguments)};var ie=t._malloc=function(){return(ie=t._malloc=t.asm.ja).apply(null,arguments)};t._free=function(){return(t._free=t.asm.ka).apply(null,arguments)};var se,ue=t.stackSave=function(){return(ue=t.stackSave=t.asm.ma).apply(null,arguments)},ce=t.stackRestore=function(){return(ce=t.stackRestore=t.asm.na).apply(null,arguments)},le=t.stackAlloc=function(){return(le=t.stackAlloc=t.asm.oa).apply(null,arguments)};function fe(){function e(){if(!se&&(se=!0,t.calledRun=!0,!R)){if(V(I),r(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();W.unshift(e)}V(W)}}if(!(0<L)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)j();V(U),0<L||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.___cxa_is_pointer_type=function(){return(t.___cxa_is_pointer_type=t.asm.pa).apply(null,arguments)},t.UTF8ToString=P,t.stringToUTF8=function(e,t,n){return k(e,A,t,n)},t.lengthBytesUTF8=D,t.stackSave=ue,t.stackRestore=ce,t.stackAlloc=le,z=function e(){se||fe(),se||(z=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return fe(),e.ready});e.exports=r},154:e=>{"use strict";e.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},760:()=>{},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},t={};function n(r){var a=t[r];if(void 0!==a)return a.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";const e=n(259),t=n(263);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,t.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(e=>postMessage({type:"init-wasm",err:e})));break;case"init-ort":try{const{numThreads:t,loggingLevel:r}=n.data.in;(0,e.initOrt)(t,r),postMessage({type:"init-ort"})}catch(e){postMessage({type:"init-ort",err:e})}break;case"create_allocate":try{const{model:t}=n.data.in,r=(0,e.createSessionAllocate)(t);postMessage({type:"create_allocate",out:r})}catch(e){postMessage({type:"create_allocate",err:e})}break;case"create_finalize":try{const{modeldata:t,options:r}=n.data.in,a=(0,e.createSessionFinalize)(t,r);postMessage({type:"create_finalize",out:a})}catch(e){postMessage({type:"create_finalize",err:e})}break;case"create":try{const{model:t,options:r}=n.data.in,a=(0,e.createSession)(t,r);postMessage({type:"create",out:a})}catch(e){postMessage({type:"create",err:e})}break;case"release":try{const t=n.data.in;(0,e.releaseSession)(t),postMessage({type:"release"})}catch(e){postMessage({type:"release",err:e})}break;case"run":try{const{sessionId:t,inputIndices:r,inputs:a,outputIndices:o,options:i}=n.data.in;(0,e.run)(t,r,a,o,i).then((t=>{postMessage({type:"run",out:t},(0,e.extractTransferableBuffers)(t))}),(e=>{postMessage({type:"run",err:e})}))}catch(e){postMessage({type:"run",err:e})}break;case"end-profiling":try{const t=n.data.in;(0,e.endProfiling)(t),postMessage({type:"end-profiling"})}catch(e){postMessage({type:"end-profiling",err:e})}}}})()})();\n',"Worker",void 0,void 0)}},6614:e=>{"use strict";e.exports=function(e,t,n,r){var i=self||window;try{try{var o;try{o=new i.Blob([e])}catch(t){(o=new(i.BlobBuilder||i.WebKitBlobBuilder||i.MozBlobBuilder||i.MSBlobBuilder)).append(e),o=o.getBlob()}var s=i.URL||i.webkitURL,a=s.createObjectURL(o),u=new i[t](a,n);return s.revokeObjectURL(a),u}catch(r){return new i[t]("data:application/javascript,".concat(encodeURIComponent(e)),n)}}catch(e){if(!r)throw Error("Inline worker is not supported");return new i[t](r,n)}}},3474:(e,t,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){function t(){return M.buffer!=D&&W(M.buffer),$}function i(){return M.buffer!=D&&W(M.buffer),L}function o(){return M.buffer!=D&&W(M.buffer),F}function s(){return M.buffer!=D&&W(M.buffer),U}function a(){return M.buffer!=D&&W(M.buffer),N}var u,l,c;e=e||{},u||(u=void 0!==e?e:{}),u.ready=new Promise((function(e,t){l=e,c=t}));var d,h,p,f,g,m,b=Object.assign({},u),y="./this.program",v=(e,t)=>{throw t},w="object"==typeof window,S="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,T=u.ENVIRONMENT_IS_PTHREAD||!1,x="";function E(e){return u.locateFile?u.locateFile(e,x):x+e}if(_){let t;x=S?n(908).dirname(x)+"/":"//",m=()=>{g||(f=n(1384),g=n(908))},d=function(e,t){return m(),e=g.normalize(e),f.readFileSync(e,t?void 0:"utf8")},p=e=>((e=d(e,!0)).buffer||(e=new Uint8Array(e)),e),h=(e,t,n)=>{m(),e=g.normalize(e),f.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(y=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof ae))throw e})),process.on("unhandledRejection",(function(e){throw e})),v=(e,t)=>{if(I)throw process.exitCode=e,t;t instanceof ae||k("exiting due to exception: "+t),process.exit(e)},u.inspect=function(){return"[Emscripten Module object]"};try{t=n(9925)}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}n.g.Worker=t.Worker}else(w||S)&&(S?x=self.location.href:"undefined"!=typeof document&&document.currentScript&&(x=document.currentScript.src),r&&(x=r),x=0!==x.indexOf("blob:")?x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(d=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},S&&(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),h=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var C=console.log.bind(console),P=console.warn.bind(console);_&&(m(),C=e=>f.writeSync(1,e+"\n"),P=e=>f.writeSync(2,e+"\n"));var O,A=u.print||C,k=u.printErr||P;Object.assign(u,b),b=null,u.thisProgram&&(y=u.thisProgram),u.quit&&(v=u.quit),u.wasmBinary&&(O=u.wasmBinary);var I=u.noExitRuntime||!0;"object"!=typeof WebAssembly&&re("no native wasm support detected");var M,R,D,$,L,F,U,N,j=!1,B="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&B)return B.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,n):e.subarray(t,n));for(r="";t<n;){var i=e[t++];if(128&i){var o=63&e[t++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var s=63&e[t++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function V(e,t){return(e>>>=0)?z(i(),e,t):""}function G(e,t,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var s=e.charCodeAt(o);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-i}function H(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function W(e){D=e,u.HEAP8=$=new Int8Array(e),u.HEAP16=new Int16Array(e),u.HEAP32=F=new Int32Array(e),u.HEAPU8=L=new Uint8Array(e),u.HEAPU16=new Uint16Array(e),u.HEAPU32=U=new Uint32Array(e),u.HEAPF32=new Float32Array(e),u.HEAPF64=N=new Float64Array(e)}T&&(D=u.buffer);var q=u.INITIAL_MEMORY||16777216;if(T)M=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)M=u.wasmMemory;else if(!((M=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw k("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");M&&(D=M.buffer),q=D.byteLength,W(D);var K,X=[],J=[],Q=[];function Y(){var e=u.preRun.shift();X.unshift(e)}var Z,ee=0,te=null,ne=null;function re(e){throw T?postMessage({cmd:"onAbort",arg:e}):u.onAbort&&u.onAbort(e),k(e="Aborted("+e+")"),j=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),c(e),e}function ie(){return Z.startsWith("data:application/octet-stream;base64,")}function oe(){var e=Z;try{if(e==Z&&O)return new Uint8Array(O);if(p)return p(e);throw"both async and sync fetching of the wasm failed"}catch(e){re(e)}}Z="ort-wasm-threaded.wasm",ie()||(Z=E(Z));var se={};function ae(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ue(e){(e=he.La[e])||re(),he.Xa(e)}function le(e){var t=he.lb();if(!t)return 6;he.Ra.push(t),he.La[e.Ka]=t,t.Ka=e.Ka;var n={cmd:"run",start_routine:e.pb,arg:e.ib,pthread_ptr:e.Ka};return t.Qa=()=>{n.time=performance.now(),t.postMessage(n,e.vb)},t.loaded&&(t.Qa(),delete t.Qa),0}function ce(e){if(T)return je(1,1,e);I||(he.qb(),u.onExit&&u.onExit(e),j=!0),v(e,new ae(e))}function de(e,t){if(!t&&T)throw fe(e),"unwind";ce(e)}var he={Oa:[],Ra:[],$a:[],La:{},Ua:function(){T&&he.mb()},xb:function(){},mb:function(){he.receiveObjectTransfer=he.ob,he.threadInitTLS=he.Za,he.setExitStatus=he.Ya,I=!1},Ya:function(){},qb:function(){for(var e of Object.values(he.La))he.Xa(e);for(e of he.Oa)e.terminate();he.Oa=[]},Xa:function(e){var t=e.Ka;delete he.La[t],he.Oa.push(e),he.Ra.splice(he.Ra.indexOf(e),1),e.Ka=0,ct(t)},ob:function(){},Za:function(){he.$a.forEach((e=>e()))},nb:function(e,t){e.onmessage=n=>{var r=(n=n.data).cmd;if(e.Ka&&(he.kb=e.Ka),n.targetThread&&n.targetThread!=it()){var i=he.La[n.yb];i?i.postMessage(n,n.transferList):k('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?De(n.queue):"spawnThread"===r?le(n):"cleanupThread"===r?ue(n.thread):"killThread"===r?(n=n.thread,r=he.La[n],delete he.La[n],r.terminate(),ct(n),he.Ra.splice(he.Ra.indexOf(r),1),r.Ka=0):"cancelThread"===r?he.La[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,t&&t(e),e.Qa&&(e.Qa(),delete e.Qa)):"print"===r?A("Thread "+n.threadId+": "+n.text):"printErr"===r?k("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?e.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&k("worker sent an unknown command "+r);he.kb=void 0},e.onerror=e=>{throw k("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},_&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){}))),e.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:M,wasmModule:R})},hb:function(){var e=E("ort-wasm-threaded.worker.js");he.Oa.push(new Worker(e))},lb:function(){return 0==he.Oa.length&&(he.hb(),he.nb(he.Oa[0])),he.Oa.pop()}};function pe(e){for(;0<e.length;)e.shift()(u)}function fe(e){if(T)return je(2,0,e);try{de(e)}catch(e){e instanceof ae||"unwind"==e||v(1,e)}}u.PThread=he,u.establishStackSpace=function(){var e=it(),t=o()[e+44>>2>>>0];e=o()[e+48>>2>>>0],ht(t,t-e),ft(t)};var ge,me,be=[];function ye(e){this.Pa=e-24,this.gb=function(e){s()[this.Pa+4>>2>>>0]=e},this.cb=function(e){s()[this.Pa+8>>2>>>0]=e},this.eb=function(){o()[this.Pa>>2>>>0]=0},this.bb=function(){t()[(this.Pa+12|0)>>>0]=0},this.fb=function(){t()[(this.Pa+13|0)>>>0]=0},this.Ua=function(e,t){this.ab(),this.gb(e),this.cb(t),this.eb(),this.bb(),this.fb()},this.ab=function(){s()[this.Pa+16>>2>>>0]=0}}function ve(e,t,n,r){return T?je(3,1,e,t,n,r):we(e,t,n,r)}function we(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return k("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return T&&0===i.length?ve(e,t,n,r):(e={pb:n,Ka:e,ib:r,vb:i},T?(e.wb="spawnThread",postMessage(e,i),0):le(e))}function Se(e,t,n){return T?je(4,1,e,t,n):0}function _e(e,t){if(T)return je(5,1,e,t)}function Te(e,t){if(T)return je(6,1,e,t)}function xe(e,t,n){if(T)return je(7,1,e,t,n)}function Ee(e,t,n){return T?je(8,1,e,t,n):0}function Ce(e,t){if(T)return je(9,1,e,t)}function Pe(e,t,n){if(T)return je(10,1,e,t,n)}function Oe(e,t,n,r){if(T)return je(11,1,e,t,n,r)}function Ae(e,t,n,r){if(T)return je(12,1,e,t,n,r)}function ke(e,t,n,r){if(T)return je(13,1,e,t,n,r)}function Ie(e){if(T)return je(14,1,e)}function Me(e,t){if(T)return je(15,1,e,t)}function Re(e,t,n){if(T)return je(16,1,e,t,n)}function De(e){Atomics.store(o(),e>>2,1),it()&&lt(e),Atomics.compareExchange(o(),e>>2,1,0)}function $e(e){return s()[e>>>2]+4294967296*o()[e+4>>>2]}function Le(e,t,n,r,i,o){return T?je(17,1,e,t,n,r,i,o):-52}function Fe(e,t,n,r,i,o){if(T)return je(18,1,e,t,n,r,i,o)}function Ue(e){var n=H(e)+1,r=ot(n);return r&&G(e,t(),r,n),r}function Ne(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}if(T)return je(19,1,e,t,n);var i=(new Date).getFullYear(),a=new Date(i,0,1),u=new Date(i,6,1);i=a.getTimezoneOffset();var l=u.getTimezoneOffset(),c=Math.max(i,l);o()[e>>2>>>0]=60*c,o()[t>>2>>>0]=Number(i!=l),e=r(a),t=r(u),e=Ue(e),t=Ue(t),l<i?(s()[n>>2>>>0]=e,s()[n+4>>2>>>0]=t):(s()[n>>2>>>0]=t,s()[n+4>>2>>>0]=e)}function je(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=pt();return e=e(),ft(t),e}((()=>{for(var i=gt(8*n),o=i>>3,s=0;s<n;s++){var u=r[2+s];a()[o+s>>>0]=u}return ut(e,n,i,t)}))}u.invokeEntryPoint=function(e,t){var n=be[e];n||(e>=be.length&&(be.length=e+1),be[e]=n=K.get(e)),e=n(t),I?he.Ya(e):dt(e)},u.executeNotifiedProxyingQueue=De,me=_?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:T?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var Be,ze=[],Ve={};function Ge(){if(!Be){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:y||"./this.program"};for(e in Ve)void 0===Ve[e]?delete t[e]:t[e]=Ve[e];var n=[];for(e in t)n.push(e+"="+t[e]);Be=n}return Be}function He(e,n){if(T)return je(20,1,e,n);var r=0;return Ge().forEach((function(i,o){var a=n+r;for(o=s()[e+4*o>>2>>>0]=a,a=0;a<i.length;++a)t()[(0|o++)>>>0]=i.charCodeAt(a);t()[(0|o)>>>0]=0,r+=i.length+1})),0}function We(e,t){if(T)return je(21,1,e,t);var n=Ge();s()[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),s()[t>>2>>>0]=r,0}function qe(e){return T?je(22,1,e):52}function Ke(e,t,n,r){return T?je(23,1,e,t,n,r):52}function Xe(e,t,n,r,i){return T?je(24,1,e,t,n,r,i):70}var Je=[null,[],[]];function Qe(e,t,n,r){if(T)return je(25,1,e,t,n,r);for(var o=0,a=0;a<n;a++){var u=s()[t>>2>>>0],l=s()[t+4>>2>>>0];t+=8;for(var c=0;c<l;c++){var d=i()[u+c>>>0],h=Je[e];0===d||10===d?((1===e?A:k)(z(h,0)),h.length=0):h.push(d)}o+=l}return s()[r>>2>>>0]=o,0}function Ye(e){return 0==e%4&&(0!=e%100||0==e%400)}var Ze=[31,29,31,30,31,30,31,31,30,31,30,31],et=[31,28,31,30,31,30,31,31,30,31,30,31];function tt(e,n,r,i){function s(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function a(e,t){return s(e,t,"0")}function u(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function l(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function c(e){var t=e.Ma;for(e=new Date(new Date(e.Na+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(Ye(e.getFullYear())?Ze:et)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=l(new Date(e.getFullYear(),0,4)),n=l(n),0>=u(t,e)?0>=u(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var d=o()[i+40>>2>>>0];for(var h in i={tb:o()[i>>2>>>0],sb:o()[i+4>>2>>>0],Sa:o()[i+8>>2>>>0],Va:o()[i+12>>2>>>0],Ta:o()[i+16>>2>>>0],Na:o()[i+20>>2>>>0],Ja:o()[i+24>>2>>>0],Ma:o()[i+28>>2>>>0],zb:o()[i+32>>2>>>0],rb:o()[i+36>>2>>>0],ub:d?V(d):""},r=V(r),d={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(h,"g"),d[h]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),f="January February March April May June July August September October November December".split(" ");for(h in d={"%a":function(e){return p[e.Ja].substring(0,3)},"%A":function(e){return p[e.Ja]},"%b":function(e){return f[e.Ta].substring(0,3)},"%B":function(e){return f[e.Ta]},"%C":function(e){return a((e.Na+1900)/100|0,2)},"%d":function(e){return a(e.Va,2)},"%e":function(e){return s(e.Va,2," ")},"%g":function(e){return c(e).toString().substring(2)},"%G":function(e){return c(e)},"%H":function(e){return a(e.Sa,2)},"%I":function(e){return 0==(e=e.Sa)?e=12:12<e&&(e-=12),a(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.Ta-1;t+=(Ye(e.Na+1900)?Ze:et)[n++]);return a(e.Va+t,3)},"%m":function(e){return a(e.Ta+1,2)},"%M":function(e){return a(e.sb,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.Sa&&12>e.Sa?"AM":"PM"},"%S":function(e){return a(e.tb,2)},"%t":function(){return"\t"},"%u":function(e){return e.Ja||7},"%U":function(e){return a(Math.floor((e.Ma+7-e.Ja)/7),2)},"%V":function(e){var t=Math.floor((e.Ma+7-(e.Ja+6)%7)/7);if(2>=(e.Ja+371-e.Ma-2)%7&&t++,t)53==t&&(4==(n=(e.Ja+371-e.Ma)%7)||3==n&&Ye(e.Na)||(t=1));else{t=52;var n=(e.Ja+7-e.Ma-1)%7;(4==n||5==n&&Ye(e.Na%400-1))&&t++}return a(t,2)},"%w":function(e){return e.Ja},"%W":function(e){return a(Math.floor((e.Ma+7-(e.Ja+6)%7)/7),2)},"%y":function(e){return(e.Na+1900).toString().substring(2)},"%Y":function(e){return e.Na+1900},"%z":function(e){var t=0<=(e=e.rb);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.ub},"%%":function(){return"%"}},r=r.replace(/%%/g,"\0\0"),d)r.includes(h)&&(r=r.replace(new RegExp(h,"g"),d[h](i)));return h=function(e){var t=Array(H(e)+1);return G(e,t,0,t.length),t}(r=r.replace(/\0\0/g,"%")),h.length>n?0:(function(e,n){t().set(e,n>>>0)}(h,e),h.length-1)}he.Ua();var nt=[null,ce,fe,ve,Se,_e,Te,xe,Ee,Ce,Pe,Oe,Ae,ke,Ie,Me,Re,Le,Fe,Ne,He,We,qe,Ke,Xe,Qe],rt={b:function(e){return ot(e+24)+24},c:function(e,t,n){throw new ye(e).Ua(t,n),e},L:function(e){st(e,!S,1,!w),he.Za()},l:function(e){T?postMessage({cmd:"cleanupThread",thread:e}):ue(e)},D:we,i:Se,R:_e,z:Te,B:xe,T:Ee,P:Ce,I:Pe,O:Oe,p:Ae,A:ke,x:Ie,Q:Me,y:Re,r:function(){},j:function(){re("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},s:function(){re("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},q:function(){return Date.now()},E:function(){return 2097152},V:function(){return!0},F:function(e,t,n,r){if(e==t)setTimeout((()=>De(r)));else if(T)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{if(!(e=he.La[e]))return;e.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},K:function(){return-1},W:function(e,t){e=new Date(1e3*$e(e)),o()[t>>2>>>0]=e.getUTCSeconds(),o()[t+4>>2>>>0]=e.getUTCMinutes(),o()[t+8>>2>>>0]=e.getUTCHours(),o()[t+12>>2>>>0]=e.getUTCDate(),o()[t+16>>2>>>0]=e.getUTCMonth(),o()[t+20>>2>>>0]=e.getUTCFullYear()-1900,o()[t+24>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[t+28>>2>>>0]=e},X:function(e,t){e=new Date(1e3*$e(e)),o()[t>>2>>>0]=e.getSeconds(),o()[t+4>>2>>>0]=e.getMinutes(),o()[t+8>>2>>>0]=e.getHours(),o()[t+12>>2>>>0]=e.getDate(),o()[t+16>>2>>>0]=e.getMonth(),o()[t+20>>2>>>0]=e.getFullYear()-1900,o()[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1),r=(e.getTime()-n.getTime())/864e5|0;o()[t+28>>2>>>0]=r,o()[t+36>>2>>>0]=-60*e.getTimezoneOffset(),r=new Date(e.getFullYear(),6,1).getTimezoneOffset(),e=0|(r!=(n=n.getTimezoneOffset())&&e.getTimezoneOffset()==Math.min(n,r)),o()[t+32>>2>>>0]=e},Y:function(e){var t=new Date(o()[e+20>>2>>>0]+1900,o()[e+16>>2>>>0],o()[e+12>>2>>>0],o()[e+8>>2>>>0],o()[e+4>>2>>>0],o()[e>>2>>>0],0),n=o()[e+32>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),0,1),s=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=i.getTimezoneOffset(),u=Math.min(a,s);return 0>n?o()[e+32>>2>>>0]=Number(s!=a&&u==r):0<n!=(u==r)&&(s=Math.max(a,s),t.setTime(t.getTime()+6e4*((0<n?u:s)-r))),o()[e+24>>2>>>0]=t.getDay(),n=(t.getTime()-i.getTime())/864e5|0,o()[e+28>>2>>>0]=n,o()[e>>2>>>0]=t.getSeconds(),o()[e+4>>2>>>0]=t.getMinutes(),o()[e+8>>2>>>0]=t.getHours(),o()[e+12>>2>>>0]=t.getDate(),o()[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},G:Le,H:Fe,Z:function e(t,n,r){e.jb||(e.jb=!0,Ne(t,n,r))},d:function(){re("")},m:function(){if(!_&&!S){var e="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";ge||(ge={}),ge[e]||(ge[e]=1,_&&(e="warning: "+e),k(e))}},w:function(){return 4294901760},f:me,S:function(e,t,n){i().copyWithin(e>>>0,t>>>0,t+n>>>0)},g:function(){return _?n(3993).cpus().length:navigator.hardwareConcurrency},J:function(e,t,n){ze.length=t,n>>=3;for(var r=0;r<t;r++)ze[r]=a()[n+r>>>0];return(0>e?se[-e-1]:nt[e]).apply(null,ze)},v:function(e){var t=i().length;if((e>>>=0)<=t||4294901760<e)return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var o=Math;r=Math.max(e,r),o=o.min.call(o,4294901760,r+(65536-r%65536)%65536);e:{try{M.grow(o-D.byteLength+65535>>>16),W(M.buffer);var s=1;break e}catch(e){}s=void 0}if(s)return!0}return!1},U:function(){throw"unwind"},M:He,N:We,k:de,h:qe,o:Ke,t:Xe,n:Qe,u:function e(r,i){e.Wa||(e.Wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(_)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>re("randomDevice")}());for(var o=0;o<i;o++)t()[(r+o|0)>>>0]=e.Wa();return 0},a:M||u.wasmMemory,C:tt,e:function(e,t,n,r){return tt(e,t,n,r)}};!function(){function e(e,t){u.asm=e.exports,he.$a.push(u.asm.wa),K=u.asm.za,J.unshift(u.asm._),R=t,T||(ee--,u.monitorRunDependencies&&u.monitorRunDependencies(ee),0==ee&&(null!==te&&(clearInterval(te),te=null),ne&&(e=ne,ne=null,e())))}function t(t){e(t.instance,t.module)}function n(e){return function(){if(!O&&(w||S)){if("function"==typeof fetch&&!Z.startsWith("file://"))return fetch(Z,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+Z+"'";return e.arrayBuffer()})).catch((function(){return oe()}));if(h)return new Promise((function(e,t){h(Z,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return oe()}))}().then((function(e){return WebAssembly.instantiate(e,r)})).then((function(e){return e})).then(e,(function(e){k("failed to asynchronously prepare wasm: "+e),re(e)}))}var r={a:rt};if(T||(ee++,u.monitorRunDependencies&&u.monitorRunDependencies(ee)),u.instantiateWasm)try{return u.instantiateWasm(r,e)}catch(e){return k("Module.instantiateWasm callback failed with error: "+e),!1}(O||"function"!=typeof WebAssembly.instantiateStreaming||ie()||Z.startsWith("file://")||_||"function"!=typeof fetch?n(t):fetch(Z,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(t,(function(e){return k("wasm streaming compile failed: "+e),k("falling back to ArrayBuffer instantiation"),n(t)}))}))).catch(c)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm._).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.$).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.aa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.ba).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.ca).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm.da).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.ea).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.fa).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.ga).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.ha).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.ia).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.ja).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.ka).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.la).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.ma).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.na).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.oa).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.pa).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.qa).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.ra).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.sa).apply(null,arguments)};var it=u._pthread_self=function(){return(it=u._pthread_self=u.asm.ta).apply(null,arguments)},ot=u._malloc=function(){return(ot=u._malloc=u.asm.ua).apply(null,arguments)};u._free=function(){return(u._free=u.asm.va).apply(null,arguments)},u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.wa).apply(null,arguments)};var st=u.__emscripten_thread_init=function(){return(st=u.__emscripten_thread_init=u.asm.xa).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.ya).apply(null,arguments)};var at,ut=u._emscripten_run_in_main_runtime_thread_js=function(){return(ut=u._emscripten_run_in_main_runtime_thread_js=u.asm.Aa).apply(null,arguments)},lt=u.__emscripten_proxy_execute_task_queue=function(){return(lt=u.__emscripten_proxy_execute_task_queue=u.asm.Ba).apply(null,arguments)},ct=u.__emscripten_thread_free_data=function(){return(ct=u.__emscripten_thread_free_data=u.asm.Ca).apply(null,arguments)},dt=u.__emscripten_thread_exit=function(){return(dt=u.__emscripten_thread_exit=u.asm.Da).apply(null,arguments)},ht=u._emscripten_stack_set_limits=function(){return(ht=u._emscripten_stack_set_limits=u.asm.Ea).apply(null,arguments)},pt=u.stackSave=function(){return(pt=u.stackSave=u.asm.Fa).apply(null,arguments)},ft=u.stackRestore=function(){return(ft=u.stackRestore=u.asm.Ga).apply(null,arguments)},gt=u.stackAlloc=function(){return(gt=u.stackAlloc=u.asm.Ha).apply(null,arguments)};function mt(){function e(){if(!at&&(at=!0,u.calledRun=!0,!j)&&(T||pe(J),l(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!T)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var e=u.postRun.shift();Q.unshift(e)}pe(Q)}}if(!(0<ee))if(T)l(u),T||pe(J),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)Y();pe(X),0<ee||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),e()}),1)):e())}}if(u.___cxa_is_pointer_type=function(){return(u.___cxa_is_pointer_type=u.asm.Ia).apply(null,arguments)},u.UTF8ToString=V,u.stringToUTF8=function(e,t,n){return G(e,i(),t,n)},u.lengthBytesUTF8=H,u.keepRuntimeAlive=function(){return I},u.wasmMemory=M,u.stackSave=pt,u.stackRestore=ft,u.stackAlloc=gt,u.ExitStatus=ae,u.PThread=he,ne=function e(){at||mt(),at||(ne=e)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return mt(),e.ready});e.exports=i},932:(e,t,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,i,o;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){i=e,o=t}));var s,a,u,l,c,d,h=Object.assign({},t),p="./this.program",f=(e,t)=>{throw t},g="object"==typeof window,m="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,y="";b?(y=m?n(908).dirname(y)+"/":"//",d=()=>{c||(l=n(1384),c=n(908))},s=function(e,t){return d(),e=c.normalize(e),l.readFileSync(e,t?void 0:"utf8")},u=e=>((e=s(e,!0)).buffer||(e=new Uint8Array(e)),e),a=(e,t,n)=>{d(),e=c.normalize(e),l.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof K))throw e})),process.on("unhandledRejection",(function(e){throw e})),f=(e,t)=>{if(_)throw process.exitCode=e,t;t instanceof K||S("exiting due to exception: "+t),process.exit(e)},t.inspect=function(){return"[Emscripten Module object]"}):(g||m)&&(m?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),r&&(y=r),y=0!==y.indexOf("blob:")?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},m&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),a=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var v,w=t.print||console.log.bind(console),S=t.printErr||console.warn.bind(console);Object.assign(t,h),h=null,t.thisProgram&&(p=t.thisProgram),t.quit&&(f=t.quit),t.wasmBinary&&(v=t.wasmBinary);var _=t.noExitRuntime||!0;"object"!=typeof WebAssembly&&G("no native wasm support detected");var T,x,E,C,P,O,A=!1,k="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function I(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&k)return k.decode(e.subarray(t,n));for(r="";t<n;){var i=e[t++];if(128&i){var o=63&e[t++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var s=63&e[t++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function M(e,t){return(e>>>=0)?I(C,e,t):""}function R(e,t,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<e.length;++o){var s=e.charCodeAt(o);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-i}function D(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function $(){var e=T.buffer;x=e,t.HEAP8=E=new Int8Array(e),t.HEAP16=new Int16Array(e),t.HEAP32=P=new Int32Array(e),t.HEAPU8=C=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=O=new Uint32Array(e),t.HEAPF32=new Float32Array(e),t.HEAPF64=new Float64Array(e)}var L=[],F=[],U=[];function N(){var e=t.preRun.shift();L.unshift(e)}var j,B=0,z=null,V=null;function G(e){throw t.onAbort&&t.onAbort(e),S(e="Aborted("+e+")"),A=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),o(e),e}function H(){return j.startsWith("data:application/octet-stream;base64,")}if(j="ort-wasm.wasm",!H()){var W=j;j=t.locateFile?t.locateFile(W,y):y+W}function q(){var e=j;try{if(e==j&&v)return new Uint8Array(v);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){G(e)}}function K(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function X(e){for(;0<e.length;)e.shift()(t)}function J(e){this.sa=e-24,this.Ia=function(e){O[this.sa+4>>2>>>0]=e},this.Ba=function(e){O[this.sa+8>>2>>>0]=e},this.Ga=function(){P[this.sa>>2>>>0]=0},this.Aa=function(){E[(this.sa+12|0)>>>0]=0},this.Ha=function(){E[(this.sa+13|0)>>>0]=0},this.ya=function(e,t){this.za(),this.Ia(e),this.Ba(t),this.Ga(),this.Aa(),this.Ha()},this.za=function(){O[this.sa+16>>2>>>0]=0}}function Q(e){var t=D(e)+1,n=ae(t);return n&&R(e,E,n,t),n}var Y={};function Z(){if(!ee){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(e in Y)void 0===Y[e]?delete t[e]:t[e]=Y[e];var n=[];for(e in t)n.push(e+"="+t[e]);ee=n}return ee}var ee,te=[null,[],[]];function ne(e){return 0==e%4&&(0!=e%100||0==e%400)}var re=[31,29,31,30,31,30,31,31,30,31,30,31],ie=[31,28,31,30,31,30,31,31,30,31,30,31];function oe(e,t,n,r){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function o(e,t){return i(e,t,"0")}function s(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function a(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.qa;for(e=new Date(new Date(e.ra+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(ne(e.getFullYear())?re:ie)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=a(new Date(e.getFullYear(),0,4)),n=a(n),0>=s(t,e)?0>=s(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var l=P[r+40>>2>>>0];for(var c in r={Ea:P[r>>2>>>0],Da:P[r+4>>2>>>0],ta:P[r+8>>2>>>0],va:P[r+12>>2>>>0],ua:P[r+16>>2>>>0],ra:P[r+20>>2>>>0],la:P[r+24>>2>>>0],qa:P[r+28>>2>>>0],Ja:P[r+32>>2>>>0],Ca:P[r+36>>2>>>0],Fa:l?M(l):""},n=M(n),l={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(c,"g"),l[c]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),h="January February March April May June July August September October November December".split(" ");for(c in l={"%a":function(e){return d[e.la].substring(0,3)},"%A":function(e){return d[e.la]},"%b":function(e){return h[e.ua].substring(0,3)},"%B":function(e){return h[e.ua]},"%C":function(e){return o((e.ra+1900)/100|0,2)},"%d":function(e){return o(e.va,2)},"%e":function(e){return i(e.va,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return o(e.ta,2)},"%I":function(e){return 0==(e=e.ta)?e=12:12<e&&(e-=12),o(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.ua-1;t+=(ne(e.ra+1900)?re:ie)[n++]);return o(e.va+t,3)},"%m":function(e){return o(e.ua+1,2)},"%M":function(e){return o(e.Da,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.ta&&12>e.ta?"AM":"PM"},"%S":function(e){return o(e.Ea,2)},"%t":function(){return"\t"},"%u":function(e){return e.la||7},"%U":function(e){return o(Math.floor((e.qa+7-e.la)/7),2)},"%V":function(e){var t=Math.floor((e.qa+7-(e.la+6)%7)/7);if(2>=(e.la+371-e.qa-2)%7&&t++,t)53==t&&(4==(n=(e.la+371-e.qa)%7)||3==n&&ne(e.ra)||(t=1));else{t=52;var n=(e.la+7-e.qa-1)%7;(4==n||5==n&&ne(e.ra%400-1))&&t++}return o(t,2)},"%w":function(e){return e.la},"%W":function(e){return o(Math.floor((e.qa+7-(e.la+6)%7)/7),2)},"%y":function(e){return(e.ra+1900).toString().substring(2)},"%Y":function(e){return e.ra+1900},"%z":function(e){var t=0<=(e=e.Ca);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.Fa},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),l)n.includes(c)&&(n=n.replace(new RegExp(c,"g"),l[c](r)));return c=function(e){var t=Array(D(e)+1);return R(e,t,0,t.length),t}(n=n.replace(/\0\0/g,"%")),c.length>t?0:(E.set(c,e>>>0),c.length-1)}var se={a:function(e){return ae(e+24)+24},b:function(e,t,n){throw new J(e).ya(t,n),e},g:function(){return 0},I:function(){},w:function(){},y:function(){},K:function(){return 0},G:function(){},C:function(){},F:function(){},k:function(){},x:function(){},u:function(){},H:function(){},v:function(){},n:function(){},p:function(){G("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},o:function(){G("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},l:function(){return Date.now()},L:function(){return!0},M:function(e,t){e=new Date(1e3*(O[e>>>2]+4294967296*P[e+4>>>2])),P[t>>2>>>0]=e.getUTCSeconds(),P[t+4>>2>>>0]=e.getUTCMinutes(),P[t+8>>2>>>0]=e.getUTCHours(),P[t+12>>2>>>0]=e.getUTCDate(),P[t+16>>2>>>0]=e.getUTCMonth(),P[t+20>>2>>>0]=e.getUTCFullYear()-1900,P[t+24>>2>>>0]=e.getUTCDay(),P[t+28>>2>>>0]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},N:function(e,t){e=new Date(1e3*(O[e>>>2]+4294967296*P[e+4>>>2])),P[t>>2>>>0]=e.getSeconds(),P[t+4>>2>>>0]=e.getMinutes(),P[t+8>>2>>>0]=e.getHours(),P[t+12>>2>>>0]=e.getDate(),P[t+16>>2>>>0]=e.getMonth(),P[t+20>>2>>>0]=e.getFullYear()-1900,P[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1);P[t+28>>2>>>0]=(e.getTime()-n.getTime())/864e5|0,P[t+36>>2>>>0]=-60*e.getTimezoneOffset();var r=new Date(e.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),P[t+32>>2>>>0]=0|(r!=n&&e.getTimezoneOffset()==Math.min(n,r))},O:function(e){var t=new Date(P[e+20>>2>>>0]+1900,P[e+16>>2>>>0],P[e+12>>2>>>0],P[e+8>>2>>>0],P[e+4>>2>>>0],P[e>>2>>>0],0),n=P[e+32>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),0,1),o=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=i.getTimezoneOffset(),a=Math.min(s,o);return 0>n?P[e+32>>2>>>0]=Number(o!=s&&a==r):0<n!=(a==r)&&(o=Math.max(s,o),t.setTime(t.getTime()+6e4*((0<n?a:o)-r))),P[e+24>>2>>>0]=t.getDay(),P[e+28>>2>>>0]=(t.getTime()-i.getTime())/864e5|0,P[e>>2>>>0]=t.getSeconds(),P[e+4>>2>>>0]=t.getMinutes(),P[e+8>>2>>>0]=t.getHours(),P[e+12>>2>>>0]=t.getDate(),P[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},z:function(){return-52},B:function(){},m:function e(t,n,r){e.xa||(e.xa=!0,function(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}var i=(new Date).getFullYear(),o=new Date(i,0,1),s=new Date(i,6,1);i=o.getTimezoneOffset();var a=s.getTimezoneOffset();P[e>>2>>>0]=60*Math.max(i,a),P[t>>2>>>0]=Number(i!=a),e=r(o),t=r(s),e=Q(e),t=Q(t),a<i?(O[n>>2>>>0]=e,O[n+4>>2>>>0]=t):(O[n>>2>>>0]=t,O[n+4>>2>>>0]=e)}(t,n,r))},d:function(){G("")},t:function(){return 4294901760},h:b?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now(),J:function(e,t,n){C.copyWithin(e>>>0,t>>>0,t+n>>>0)},f:function(e){var t=C.length;if(4294901760<(e>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var i=Math;r=Math.max(e,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);e:{try{T.grow(i-x.byteLength+65535>>>16),$();var o=1;break e}catch(e){}o=void 0}if(o)return!0}return!1},D:function(e,t){var n=0;return Z().forEach((function(r,i){var o=t+n;for(i=O[e+4*i>>2>>>0]=o,o=0;o<r.length;++o)E[(0|i++)>>>0]=r.charCodeAt(o);E[(0|i)>>>0]=0,n+=r.length+1})),0},E:function(e,t){var n=Z();O[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),O[t>>2>>>0]=r,0},r:function(e){_||(t.onExit&&t.onExit(e),A=!0),f(e,new K(e))},e:function(){return 52},j:function(){return 52},q:function(){return 70},i:function(e,t,n,r){for(var i=0,o=0;o<n;o++){var s=O[t>>2>>>0],a=O[t+4>>2>>>0];t+=8;for(var u=0;u<a;u++){var l=C[s+u>>>0],c=te[e];0===l||10===l?((1===e?w:S)(I(c,0)),c.length=0):c.push(l)}i+=a}return O[r>>2>>>0]=i,0},s:function e(t,r){e.wa||(e.wa=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(b)try{var t=n(760);return()=>t.randomBytes(1)[0]}catch(e){}return()=>G("randomDevice")}());for(var i=0;i<r;i++)E[(t+i|0)>>>0]=e.wa();return 0},A:oe,c:function(e,t,n,r){return oe(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,T=t.asm.P,$(),F.unshift(t.asm.Q),B--,t.monitorRunDependencies&&t.monitorRunDependencies(B),0==B&&(null!==z&&(clearInterval(z),z=null),V&&(e=V,V=null,e()))}function n(t){e(t.instance)}function r(e){return function(){if(!v&&(g||m)){if("function"==typeof fetch&&!j.startsWith("file://"))return fetch(j,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+j+"'";return e.arrayBuffer()})).catch((function(){return q()}));if(a)return new Promise((function(e,t){a(j,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return q()}))}().then((function(e){return WebAssembly.instantiate(e,i)})).then((function(e){return e})).then(e,(function(e){S("failed to asynchronously prepare wasm: "+e),G(e)}))}var i={a:se};if(B++,t.monitorRunDependencies&&t.monitorRunDependencies(B),t.instantiateWasm)try{return t.instantiateWasm(i,e)}catch(e){return S("Module.instantiateWasm callback failed with error: "+e),!1}(v||"function"!=typeof WebAssembly.instantiateStreaming||H()||j.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(j,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,i).then(n,(function(e){return S("wasm streaming compile failed: "+e),S("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(o)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Q).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.R).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.S).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.T).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.U).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm.V).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.W).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.X).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.Y).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.Z).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm._).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.$).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.aa).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.ba).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.ca).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.da).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.ea).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.fa).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.ga).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.ha).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.ia).apply(null,arguments)};var ae=t._malloc=function(){return(ae=t._malloc=t.asm.ja).apply(null,arguments)};t._free=function(){return(t._free=t.asm.ka).apply(null,arguments)};var ue,le=t.stackSave=function(){return(le=t.stackSave=t.asm.ma).apply(null,arguments)},ce=t.stackRestore=function(){return(ce=t.stackRestore=t.asm.na).apply(null,arguments)},de=t.stackAlloc=function(){return(de=t.stackAlloc=t.asm.oa).apply(null,arguments)};function he(){function e(){if(!ue&&(ue=!0,t.calledRun=!0,!A)){if(X(F),i(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();U.unshift(e)}X(U)}}if(!(0<B)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)N();X(L),0<B||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.___cxa_is_pointer_type=function(){return(t.___cxa_is_pointer_type=t.asm.pa).apply(null,arguments)},t.UTF8ToString=M,t.stringToUTF8=function(e,t,n){return R(e,C,t,n)},t.lengthBytesUTF8=D,t.stackSave=le,t.stackRestore=ce,t.stackAlloc=de,V=function e(){ue||he(),ue||(V=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return he(),e.ready});e.exports=i},4537:e=>{"use strict";e.exports=function(e,t){for(var n=new Array(arguments.length-1),r=0,i=2,o=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise((function(i,s){n[r]=function(e){if(o)if(o=!1,e)s(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;)t[n++]=arguments[n];i.apply(null,t)}};try{e.apply(t||null,n)}catch(e){o&&(o=!1,s(e))}}))}},7419:(e,t)=>{"use strict";var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var r=new Array(64),i=new Array(123),o=0;o<64;)i[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;n.encode=function(e,t,n){for(var i,o=null,s=[],a=0,u=0;t<n;){var l=e[t++];switch(u){case 0:s[a++]=r[l>>2],i=(3&l)<<4,u=1;break;case 1:s[a++]=r[i|l>>4],i=(15&l)<<2,u=2;break;case 2:s[a++]=r[i|l>>6],s[a++]=r[63&l],u=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0)}return u&&(s[a++]=r[i],s[a++]=61,1===u&&(s[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";n.decode=function(e,t,n){for(var r,o=n,a=0,u=0;u<e.length;){var l=e.charCodeAt(u++);if(61===l&&a>1)break;if(void 0===(l=i[l]))throw Error(s);switch(a){case 0:r=l,a=1;break;case 1:t[n++]=r<<2|(48&l)>>4,r=l,a=2;break;case 2:t[n++]=(15&r)<<4|(60&l)>>2,r=l,a=3;break;case 3:t[n++]=(3&r)<<6|l,a=0}}if(1===a)throw Error(s);return n-o},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},9211:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],r=0;r<n.length;)n[r].fn===t?n.splice(r,1):++r;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<t.length;)t[r].fn.apply(t[r++].ctx,n)}return this}},945:e=>{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),r=128===n[3];function i(e,r,i){t[0]=e,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function o(e,r,i){t[0]=e,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function s(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],t[0]}function a(e,r){return n[3]=e[r],n[2]=e[r+1],n[1]=e[r+2],n[0]=e[r+3],t[0]}e.writeFloatLE=r?i:o,e.writeFloatBE=r?o:i,e.readFloatLE=r?s:a,e.readFloatBE=r?a:s}():function(){function t(e,t,n,r){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,n,r);else if(isNaN(t))e(2143289344,n,r);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,n,r);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,n,r);else{var o=Math.floor(Math.log(t)/Math.LN2);e((i<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,n,r)}}function s(e,t,n){var r=e(t,n),i=2*(r>>31)+1,o=r>>>23&255,s=8388607&r;return 255===o?s?NaN:i*(1/0):0===o?1401298464324817e-60*i*s:i*Math.pow(2,o-150)*(s+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,r),e.readFloatLE=s.bind(null,i),e.readFloatBE=s.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),r=128===n[7];function i(e,r,i){t[0]=e,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function o(e,r,i){t[0]=e,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function s(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],n[4]=e[r+4],n[5]=e[r+5],n[6]=e[r+6],n[7]=e[r+7],t[0]}function a(e,r){return n[7]=e[r],n[6]=e[r+1],n[5]=e[r+2],n[4]=e[r+3],n[3]=e[r+4],n[2]=e[r+5],n[1]=e[r+6],n[0]=e[r+7],t[0]}e.writeDoubleLE=r?i:o,e.writeDoubleBE=r?o:i,e.readDoubleLE=r?s:a,e.readDoubleBE=r?a:s}():function(){function t(e,t,n,r,i,o){var s=r<0?1:0;if(s&&(r=-r),0===r)e(0,i,o+t),e(1/r>0?0:2147483648,i,o+n);else if(isNaN(r))e(0,i,o+t),e(2146959360,i,o+n);else if(r>17976931348623157e292)e(0,i,o+t),e((s<<31|2146435072)>>>0,i,o+n);else{var a;if(r<22250738585072014e-324)e((a=r/5e-324)>>>0,i,o+t),e((s<<31|a/4294967296)>>>0,i,o+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(a=r*Math.pow(2,-u))>>>0,i,o+t),e((s<<31|u+1023<<20|1048576*a&1048575)>>>0,i,o+n)}}}function s(e,t,n,r,i){var o=e(r,i+t),s=e(r,i+n),a=2*(s>>31)+1,u=s>>>20&2047,l=4294967296*(1048575&s)+o;return 2047===u?l?NaN:a*(1/0):0===u?5e-324*a*l:a*Math.pow(2,u-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,r,4,0),e.readDoubleLE=s.bind(null,i,0,4),e.readDoubleBE=s.bind(null,o,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function r(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function o(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},7199:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},6662:e=>{"use strict";e.exports=function(e,t,n){var r=n||8192,i=r>>>1,o=null,s=r;return function(n){if(n<1||n>i)return e(n);s+n>r&&(o=e(r),s=0);var a=t.call(o,s,s+=n);return 7&s&&(s=1+(7|s)),a}}},4997:(e,t)=>{"use strict";var n=t;n.length=function(e){for(var t=0,n=0,r=0;r<e.length;++r)(n=e.charCodeAt(r))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t},n.read=function(e,t,n){if(n-t<1)return"";for(var r,i=null,o=[],s=0;t<n;)(r=e[t++])<128?o[s++]=r:r>191&&r<224?o[s++]=(31&r)<<6|63&e[t++]:r>239&&r<365?(r=((7&r)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[s++]=55296+(r>>10),o[s++]=56320+(1023&r)):o[s++]=(15&r)<<12|(63&e[t++])<<6|63&e[t++],s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))},n.write=function(e,t,n){for(var r,i,o=n,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t[n++]=r:r<2048?(t[n++]=r>>6|192,t[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=e.charCodeAt(s+1)))?(r=65536+((1023&r)<<10)+(1023&i),++s,t[n++]=r>>18|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>12|224,t[n++]=r>>6&63|128,t[n++]=63&r|128);return n-o}},3442:(e,t)=>{"use strict";t.__esModule=!0;var n=function(){function e(t){if(!t)throw new TypeError("Invalid argument; `value` has no value.");this.value=e.EMPTY,t&&e.isGuid(t)&&(this.value=t)}return e.isGuid=function(t){var n=t.toString();return t&&(t instanceof e||e.validator.test(n))},e.create=function(){return new e([e.gen(2),e.gen(1),e.gen(1),e.gen(1),e.gen(3)].join("-"))},e.createEmpty=function(){return new e("emptyguid")},e.parse=function(t){return new e(t)},e.raw=function(){return[e.gen(2),e.gen(1),e.gen(1),e.gen(1),e.gen(3)].join("-")},e.gen=function(e){for(var t="",n=0;n<e;n++)t+=(65536*(1+Math.random())|0).toString(16).substring(1);return t},e.prototype.equals=function(t){return e.isGuid(t)&&this.value===t.toString()},e.prototype.isEmpty=function(){return this.value===e.EMPTY},e.prototype.toString=function(){return this.value},e.prototype.toJSON=function(){return{value:this.value}},e.validator=new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$","i"),e.EMPTY="00000000-0000-0000-0000-000000000000",e}();t.Guid=n},3720:e=>{e.exports=n;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},o={};function s(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=o[e])?r:(n=u(e,(0|e)<0?-1:0,!0),s&&(o[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=i[e])?r:(n=u(e,e<0?-1:0,!1),s&&(i[e]=n),n)}function a(e,t){if(isNaN(e))return t?b:m;if(t){if(e<0)return b;if(e>=p)return _}else{if(e<=-f)return T;if(e+1>=f)return S}return e<0?a(-e,t).neg():u(e%h|0,e/h|0,t)}function u(e,t,r){return new n(e,t,r)}n.fromInt=s,n.fromNumber=a,n.fromBits=u;var l=Math.pow;function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return m;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return c(e.substring(1),t,n).neg();for(var i=a(l(n,8)),o=m,s=0;s<e.length;s+=8){var u=Math.min(8,e.length-s),d=parseInt(e.substring(s,s+u),n);if(u<8){var h=a(l(n,u));o=o.mul(h).add(a(d))}else o=(o=o.mul(i)).add(a(d))}return o.unsigned=t,o}function d(e,t){return"number"==typeof e?a(e,t):"string"==typeof e?c(e,t):u(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}n.fromString=c,n.fromValue=d;var h=4294967296,p=h*h,f=p/2,g=s(1<<24),m=s(0);n.ZERO=m;var b=s(0,!0);n.UZERO=b;var y=s(1);n.ONE=y;var v=s(1,!0);n.UONE=v;var w=s(-1);n.NEG_ONE=w;var S=u(-1,2147483647,!1);n.MAX_VALUE=S;var _=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=_;var T=u(0,-2147483648,!1);n.MIN_VALUE=T;var x=n.prototype;x.toInt=function(){return this.unsigned?this.low>>>0:this.low},x.toNumber=function(){return this.unsigned?(this.high>>>0)*h+(this.low>>>0):this.high*h+(this.low>>>0)},x.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(T)){var t=a(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var i=a(l(e,6),this.unsigned),o=this,s="";;){var u=o.div(i),c=(o.sub(u.mul(i)).toInt()>>>0).toString(e);if((o=u).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},x.getHighBits=function(){return this.high},x.getHighBitsUnsigned=function(){return this.high>>>0},x.getLowBits=function(){return this.low},x.getLowBitsUnsigned=function(){return this.low>>>0},x.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},x.isZero=function(){return 0===this.high&&0===this.low},x.eqz=x.isZero,x.isNegative=function(){return!this.unsigned&&this.high<0},x.isPositive=function(){return this.unsigned||this.high>=0},x.isOdd=function(){return!(1&~this.low)},x.isEven=function(){return!(1&this.low)},x.equals=function(e){return r(e)||(e=d(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},x.eq=x.equals,x.notEquals=function(e){return!this.eq(e)},x.neq=x.notEquals,x.ne=x.notEquals,x.lessThan=function(e){return this.comp(e)<0},x.lt=x.lessThan,x.lessThanOrEqual=function(e){return this.comp(e)<=0},x.lte=x.lessThanOrEqual,x.le=x.lessThanOrEqual,x.greaterThan=function(e){return this.comp(e)>0},x.gt=x.greaterThan,x.greaterThanOrEqual=function(e){return this.comp(e)>=0},x.gte=x.greaterThanOrEqual,x.ge=x.greaterThanOrEqual,x.compare=function(e){if(r(e)||(e=d(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},x.comp=x.compare,x.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(y)},x.neg=x.negate,x.add=function(e){r(e)||(e=d(e));var t=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,s=e.high>>>16,a=65535&e.high,l=e.low>>>16,c=0,h=0,p=0,f=0;return p+=(f+=o+(65535&e.low))>>>16,h+=(p+=i+l)>>>16,c+=(h+=n+a)>>>16,c+=t+s,u((p&=65535)<<16|(f&=65535),(c&=65535)<<16|(h&=65535),this.unsigned)},x.subtract=function(e){return r(e)||(e=d(e)),this.add(e.neg())},x.sub=x.subtract,x.multiply=function(e){if(this.isZero())return m;if(r(e)||(e=d(e)),t)return u(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return m;if(this.eq(T))return e.isOdd()?T:m;if(e.eq(T))return this.isOdd()?T:m;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(g)&&e.lt(g))return a(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,o=this.low>>>16,s=65535&this.low,l=e.high>>>16,c=65535&e.high,h=e.low>>>16,p=65535&e.low,f=0,b=0,y=0,v=0;return y+=(v+=s*p)>>>16,b+=(y+=o*p)>>>16,y&=65535,b+=(y+=s*h)>>>16,f+=(b+=i*p)>>>16,b&=65535,f+=(b+=o*h)>>>16,b&=65535,f+=(b+=s*c)>>>16,f+=n*p+i*h+o*c+s*l,u((y&=65535)<<16|(v&=65535),(f&=65535)<<16|(b&=65535),this.unsigned)},x.mul=x.multiply,x.divide=function(e){if(r(e)||(e=d(e)),e.isZero())throw Error("division by zero");var n,i,o;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?u((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?b:m;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return b;if(e.gt(this.shru(1)))return v;o=b}else{if(this.eq(T))return e.eq(y)||e.eq(w)?T:e.eq(T)?y:(n=this.shr(1).div(e).shl(1)).eq(m)?e.isNegative()?y:w:(i=this.sub(e.mul(n)),o=n.add(i.div(e)));if(e.eq(T))return this.unsigned?b:m;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();o=m}for(i=this;i.gte(e);){n=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(n)/Math.LN2),c=s<=48?1:l(2,s-48),h=a(n),p=h.mul(e);p.isNegative()||p.gt(i);)p=(h=a(n-=c,this.unsigned)).mul(e);h.isZero()&&(h=y),o=o.add(h),i=i.sub(p)}return o},x.div=x.divide,x.modulo=function(e){return r(e)||(e=d(e)),t?u((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},x.mod=x.modulo,x.rem=x.modulo,x.not=function(){return u(~this.low,~this.high,this.unsigned)},x.and=function(e){return r(e)||(e=d(e)),u(this.low&e.low,this.high&e.high,this.unsigned)},x.or=function(e){return r(e)||(e=d(e)),u(this.low|e.low,this.high|e.high,this.unsigned)},x.xor=function(e){return r(e)||(e=d(e)),u(this.low^e.low,this.high^e.high,this.unsigned)},x.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):u(0,this.low<<e-32,this.unsigned)},x.shl=x.shiftLeft,x.shiftRight=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):u(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},x.shr=x.shiftRight,x.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?u(this.low>>>e|t<<32-e,t>>>e,this.unsigned):u(32===e?t:t>>>e-32,0,this.unsigned)},x.shru=x.shiftRightUnsigned,x.shr_u=x.shiftRightUnsigned,x.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},x.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},x.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},x.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},x.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},1446:(e,t,n)=>{"use strict";var r,i,o,s=n(2100),a=s.Reader,u=s.Writer,l=s.util,c=s.roots.default||(s.roots.default={});c.onnx=((o={}).Version=(r={},(i=Object.create(r))[r[0]="_START_VERSION"]=0,i[r[1]="IR_VERSION_2017_10_10"]=1,i[r[2]="IR_VERSION_2017_10_30"]=2,i[r[3]="IR_VERSION_2017_11_3"]=3,i[r[4]="IR_VERSION_2019_1_22"]=4,i[r[5]="IR_VERSION"]=5,i),o.AttributeProto=function(){function e(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.name="",e.prototype.refAttrName="",e.prototype.docString="",e.prototype.type=0,e.prototype.f=0,e.prototype.i=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.s=l.newBuffer([]),e.prototype.t=null,e.prototype.g=null,e.prototype.floats=l.emptyArray,e.prototype.ints=l.emptyArray,e.prototype.strings=l.emptyArray,e.prototype.tensors=l.emptyArray,e.prototype.graphs=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.name&&e.hasOwnProperty("name")&&t.uint32(10).string(e.name),null!=e.f&&e.hasOwnProperty("f")&&t.uint32(21).float(e.f),null!=e.i&&e.hasOwnProperty("i")&&t.uint32(24).int64(e.i),null!=e.s&&e.hasOwnProperty("s")&&t.uint32(34).bytes(e.s),null!=e.t&&e.hasOwnProperty("t")&&c.onnx.TensorProto.encode(e.t,t.uint32(42).fork()).ldelim(),null!=e.g&&e.hasOwnProperty("g")&&c.onnx.GraphProto.encode(e.g,t.uint32(50).fork()).ldelim(),null!=e.floats&&e.floats.length){t.uint32(58).fork();for(var n=0;n<e.floats.length;++n)t.float(e.floats[n]);t.ldelim()}if(null!=e.ints&&e.ints.length){for(t.uint32(66).fork(),n=0;n<e.ints.length;++n)t.int64(e.ints[n]);t.ldelim()}if(null!=e.strings&&e.strings.length)for(n=0;n<e.strings.length;++n)t.uint32(74).bytes(e.strings[n]);if(null!=e.tensors&&e.tensors.length)for(n=0;n<e.tensors.length;++n)c.onnx.TensorProto.encode(e.tensors[n],t.uint32(82).fork()).ldelim();if(null!=e.graphs&&e.graphs.length)for(n=0;n<e.graphs.length;++n)c.onnx.GraphProto.encode(e.graphs[n],t.uint32(90).fork()).ldelim();return null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(106).string(e.docString),null!=e.type&&e.hasOwnProperty("type")&&t.uint32(160).int32(e.type),null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&t.uint32(170).string(e.refAttrName),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.AttributeProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.name=e.string();break;case 21:r.refAttrName=e.string();break;case 13:r.docString=e.string();break;case 20:r.type=e.int32();break;case 2:r.f=e.float();break;case 3:r.i=e.int64();break;case 4:r.s=e.bytes();break;case 5:r.t=c.onnx.TensorProto.decode(e,e.uint32());break;case 6:r.g=c.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&i))for(var o=e.uint32()+e.pos;e.pos<o;)r.floats.push(e.float());else r.floats.push(e.float());break;case 8:if(r.ints&&r.ints.length||(r.ints=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.ints.push(e.int64());else r.ints.push(e.int64());break;case 9:r.strings&&r.strings.length||(r.strings=[]),r.strings.push(e.bytes());break;case 10:r.tensors&&r.tensors.length||(r.tensors=[]),r.tensors.push(c.onnx.TensorProto.decode(e,e.uint32()));break;case 11:r.graphs&&r.graphs.length||(r.graphs=[]),r.graphs.push(c.onnx.GraphProto.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&!l.isString(e.refAttrName))return"refAttrName: string expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:}if(null!=e.f&&e.hasOwnProperty("f")&&"number"!=typeof e.f)return"f: number expected";if(null!=e.i&&e.hasOwnProperty("i")&&!(l.isInteger(e.i)||e.i&&l.isInteger(e.i.low)&&l.isInteger(e.i.high)))return"i: integer|Long expected";if(null!=e.s&&e.hasOwnProperty("s")&&!(e.s&&"number"==typeof e.s.length||l.isString(e.s)))return"s: buffer expected";if(null!=e.t&&e.hasOwnProperty("t")&&(n=c.onnx.TensorProto.verify(e.t)))return"t."+n;if(null!=e.g&&e.hasOwnProperty("g")&&(n=c.onnx.GraphProto.verify(e.g)))return"g."+n;if(null!=e.floats&&e.hasOwnProperty("floats")){if(!Array.isArray(e.floats))return"floats: array expected";for(var t=0;t<e.floats.length;++t)if("number"!=typeof e.floats[t])return"floats: number[] expected"}if(null!=e.ints&&e.hasOwnProperty("ints")){if(!Array.isArray(e.ints))return"ints: array expected";for(t=0;t<e.ints.length;++t)if(!(l.isInteger(e.ints[t])||e.ints[t]&&l.isInteger(e.ints[t].low)&&l.isInteger(e.ints[t].high)))return"ints: integer|Long[] expected"}if(null!=e.strings&&e.hasOwnProperty("strings")){if(!Array.isArray(e.strings))return"strings: array expected";for(t=0;t<e.strings.length;++t)if(!(e.strings[t]&&"number"==typeof e.strings[t].length||l.isString(e.strings[t])))return"strings: buffer[] expected"}if(null!=e.tensors&&e.hasOwnProperty("tensors")){if(!Array.isArray(e.tensors))return"tensors: array expected";for(t=0;t<e.tensors.length;++t)if(n=c.onnx.TensorProto.verify(e.tensors[t]))return"tensors."+n}if(null!=e.graphs&&e.hasOwnProperty("graphs")){if(!Array.isArray(e.graphs))return"graphs: array expected";for(t=0;t<e.graphs.length;++t){var n;if(n=c.onnx.GraphProto.verify(e.graphs[t]))return"graphs."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.AttributeProto)return e;var t=new c.onnx.AttributeProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.refAttrName&&(t.refAttrName=String(e.refAttrName)),null!=e.docString&&(t.docString=String(e.docString)),e.type){case"UNDEFINED":case 0:t.type=0;break;case"FLOAT":case 1:t.type=1;break;case"INT":case 2:t.type=2;break;case"STRING":case 3:t.type=3;break;case"TENSOR":case 4:t.type=4;break;case"GRAPH":case 5:t.type=5;break;case"FLOATS":case 6:t.type=6;break;case"INTS":case 7:t.type=7;break;case"STRINGS":case 8:t.type=8;break;case"TENSORS":case 9:t.type=9;break;case"GRAPHS":case 10:t.type=10}if(null!=e.f&&(t.f=Number(e.f)),null!=e.i&&(l.Long?(t.i=l.Long.fromValue(e.i)).unsigned=!1:"string"==typeof e.i?t.i=parseInt(e.i,10):"number"==typeof e.i?t.i=e.i:"object"==typeof e.i&&(t.i=new l.LongBits(e.i.low>>>0,e.i.high>>>0).toNumber())),null!=e.s&&("string"==typeof e.s?l.base64.decode(e.s,t.s=l.newBuffer(l.base64.length(e.s)),0):e.s.length&&(t.s=e.s)),null!=e.t){if("object"!=typeof e.t)throw TypeError(".onnx.AttributeProto.t: object expected");t.t=c.onnx.TensorProto.fromObject(e.t)}if(null!=e.g){if("object"!=typeof e.g)throw TypeError(".onnx.AttributeProto.g: object expected");t.g=c.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");t.floats=[];for(var n=0;n<e.floats.length;++n)t.floats[n]=Number(e.floats[n])}if(e.ints){if(!Array.isArray(e.ints))throw TypeError(".onnx.AttributeProto.ints: array expected");for(t.ints=[],n=0;n<e.ints.length;++n)l.Long?(t.ints[n]=l.Long.fromValue(e.ints[n])).unsigned=!1:"string"==typeof e.ints[n]?t.ints[n]=parseInt(e.ints[n],10):"number"==typeof e.ints[n]?t.ints[n]=e.ints[n]:"object"==typeof e.ints[n]&&(t.ints[n]=new l.LongBits(e.ints[n].low>>>0,e.ints[n].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(t.strings=[],n=0;n<e.strings.length;++n)"string"==typeof e.strings[n]?l.base64.decode(e.strings[n],t.strings[n]=l.newBuffer(l.base64.length(e.strings[n])),0):e.strings[n].length&&(t.strings[n]=e.strings[n])}if(e.tensors){if(!Array.isArray(e.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");for(t.tensors=[],n=0;n<e.tensors.length;++n){if("object"!=typeof e.tensors[n])throw TypeError(".onnx.AttributeProto.tensors: object expected");t.tensors[n]=c.onnx.TensorProto.fromObject(e.tensors[n])}}if(e.graphs){if(!Array.isArray(e.graphs))throw TypeError(".onnx.AttributeProto.graphs: array expected");for(t.graphs=[],n=0;n<e.graphs.length;++n){if("object"!=typeof e.graphs[n])throw TypeError(".onnx.AttributeProto.graphs: object expected");t.graphs[n]=c.onnx.GraphProto.fromObject(e.graphs[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.floats=[],n.ints=[],n.strings=[],n.tensors=[],n.graphs=[]),t.defaults){if(n.name="",n.f=0,l.Long){var r=new l.Long(0,0,!1);n.i=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.i=t.longs===String?"0":0;t.bytes===String?n.s="":(n.s=[],t.bytes!==Array&&(n.s=l.newBuffer(n.s))),n.t=null,n.g=null,n.docString="",n.type=t.enums===String?"UNDEFINED":0,n.refAttrName=""}if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.f&&e.hasOwnProperty("f")&&(n.f=t.json&&!isFinite(e.f)?String(e.f):e.f),null!=e.i&&e.hasOwnProperty("i")&&("number"==typeof e.i?n.i=t.longs===String?String(e.i):e.i:n.i=t.longs===String?l.Long.prototype.toString.call(e.i):t.longs===Number?new l.LongBits(e.i.low>>>0,e.i.high>>>0).toNumber():e.i),null!=e.s&&e.hasOwnProperty("s")&&(n.s=t.bytes===String?l.base64.encode(e.s,0,e.s.length):t.bytes===Array?Array.prototype.slice.call(e.s):e.s),null!=e.t&&e.hasOwnProperty("t")&&(n.t=c.onnx.TensorProto.toObject(e.t,t)),null!=e.g&&e.hasOwnProperty("g")&&(n.g=c.onnx.GraphProto.toObject(e.g,t)),e.floats&&e.floats.length){n.floats=[];for(var i=0;i<e.floats.length;++i)n.floats[i]=t.json&&!isFinite(e.floats[i])?String(e.floats[i]):e.floats[i]}if(e.ints&&e.ints.length)for(n.ints=[],i=0;i<e.ints.length;++i)"number"==typeof e.ints[i]?n.ints[i]=t.longs===String?String(e.ints[i]):e.ints[i]:n.ints[i]=t.longs===String?l.Long.prototype.toString.call(e.ints[i]):t.longs===Number?new l.LongBits(e.ints[i].low>>>0,e.ints[i].high>>>0).toNumber():e.ints[i];if(e.strings&&e.strings.length)for(n.strings=[],i=0;i<e.strings.length;++i)n.strings[i]=t.bytes===String?l.base64.encode(e.strings[i],0,e.strings[i].length):t.bytes===Array?Array.prototype.slice.call(e.strings[i]):e.strings[i];if(e.tensors&&e.tensors.length)for(n.tensors=[],i=0;i<e.tensors.length;++i)n.tensors[i]=c.onnx.TensorProto.toObject(e.tensors[i],t);if(e.graphs&&e.graphs.length)for(n.graphs=[],i=0;i<e.graphs.length;++i)n.graphs[i]=c.onnx.GraphProto.toObject(e.graphs[i],t);return null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?c.onnx.AttributeProto.AttributeType[e.type]:e.type),null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&(n.refAttrName=e.refAttrName),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.AttributeType=function(){var e={},t=Object.create(e);return t[e[0]="UNDEFINED"]=0,t[e[1]="FLOAT"]=1,t[e[2]="INT"]=2,t[e[3]="STRING"]=3,t[e[4]="TENSOR"]=4,t[e[5]="GRAPH"]=5,t[e[6]="FLOATS"]=6,t[e[7]="INTS"]=7,t[e[8]="STRINGS"]=8,t[e[9]="TENSORS"]=9,t[e[10]="GRAPHS"]=10,t}(),e}(),o.ValueInfoProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.name="",e.prototype.type=null,e.prototype.docString="",e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.name&&e.hasOwnProperty("name")&&t.uint32(10).string(e.name),null!=e.type&&e.hasOwnProperty("type")&&c.onnx.TypeProto.encode(e.type,t.uint32(18).fork()).ldelim(),null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(26).string(e.docString),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.ValueInfoProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.name=e.string();break;case 2:r.type=c.onnx.TypeProto.decode(e,e.uint32());break;case 3:r.docString=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.type&&e.hasOwnProperty("type")){var t=c.onnx.TypeProto.verify(e.type);if(t)return"type."+t}return null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString)?"docString: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.ValueInfoProto)return e;var t=new c.onnx.ValueInfoProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.type){if("object"!=typeof e.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");t.type=c.onnx.TypeProto.fromObject(e.type)}return null!=e.docString&&(t.docString=String(e.docString)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.name="",n.type=null,n.docString=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.type&&e.hasOwnProperty("type")&&(n.type=c.onnx.TypeProto.toObject(e.type,t)),null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.NodeProto=function(){function e(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.input=l.emptyArray,e.prototype.output=l.emptyArray,e.prototype.name="",e.prototype.opType="",e.prototype.domain="",e.prototype.attribute=l.emptyArray,e.prototype.docString="",e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.input&&e.input.length)for(var n=0;n<e.input.length;++n)t.uint32(10).string(e.input[n]);if(null!=e.output&&e.output.length)for(n=0;n<e.output.length;++n)t.uint32(18).string(e.output[n]);if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(26).string(e.name),null!=e.opType&&e.hasOwnProperty("opType")&&t.uint32(34).string(e.opType),null!=e.attribute&&e.attribute.length)for(n=0;n<e.attribute.length;++n)c.onnx.AttributeProto.encode(e.attribute[n],t.uint32(42).fork()).ldelim();return null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(50).string(e.docString),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(58).string(e.domain),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.NodeProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(e.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(e.string());break;case 3:r.name=e.string();break;case 4:r.opType=e.string();break;case 7:r.domain=e.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(c.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:r.docString=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.input&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var t=0;t<e.input.length;++t)if(!l.isString(e.input[t]))return"input: string[] expected"}if(null!=e.output&&e.hasOwnProperty("output")){if(!Array.isArray(e.output))return"output: array expected";for(t=0;t<e.output.length;++t)if(!l.isString(e.output[t]))return"output: string[] expected"}if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.opType&&e.hasOwnProperty("opType")&&!l.isString(e.opType))return"opType: string expected";if(null!=e.domain&&e.hasOwnProperty("domain")&&!l.isString(e.domain))return"domain: string expected";if(null!=e.attribute&&e.hasOwnProperty("attribute")){if(!Array.isArray(e.attribute))return"attribute: array expected";for(t=0;t<e.attribute.length;++t){var n=c.onnx.AttributeProto.verify(e.attribute[t]);if(n)return"attribute."+n}}return null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString)?"docString: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.NodeProto)return e;var t=new c.onnx.NodeProto;if(e.input){if(!Array.isArray(e.input))throw TypeError(".onnx.NodeProto.input: array expected");t.input=[];for(var n=0;n<e.input.length;++n)t.input[n]=String(e.input[n])}if(e.output){if(!Array.isArray(e.output))throw TypeError(".onnx.NodeProto.output: array expected");for(t.output=[],n=0;n<e.output.length;++n)t.output[n]=String(e.output[n])}if(null!=e.name&&(t.name=String(e.name)),null!=e.opType&&(t.opType=String(e.opType)),null!=e.domain&&(t.domain=String(e.domain)),e.attribute){if(!Array.isArray(e.attribute))throw TypeError(".onnx.NodeProto.attribute: array expected");for(t.attribute=[],n=0;n<e.attribute.length;++n){if("object"!=typeof e.attribute[n])throw TypeError(".onnx.NodeProto.attribute: object expected");t.attribute[n]=c.onnx.AttributeProto.fromObject(e.attribute[n])}}return null!=e.docString&&(t.docString=String(e.docString)),t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.input=[],n.output=[],n.attribute=[]),t.defaults&&(n.name="",n.opType="",n.docString="",n.domain=""),e.input&&e.input.length){n.input=[];for(var r=0;r<e.input.length;++r)n.input[r]=e.input[r]}if(e.output&&e.output.length)for(n.output=[],r=0;r<e.output.length;++r)n.output[r]=e.output[r];if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.opType&&e.hasOwnProperty("opType")&&(n.opType=e.opType),e.attribute&&e.attribute.length)for(n.attribute=[],r=0;r<e.attribute.length;++r)n.attribute[r]=c.onnx.AttributeProto.toObject(e.attribute[r],t);return null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.ModelProto=function(){function e(e){if(this.opsetImport=[],this.metadataProps=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.irVersion=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.opsetImport=l.emptyArray,e.prototype.producerName="",e.prototype.producerVersion="",e.prototype.domain="",e.prototype.modelVersion=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.docString="",e.prototype.graph=null,e.prototype.metadataProps=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.irVersion&&e.hasOwnProperty("irVersion")&&t.uint32(8).int64(e.irVersion),null!=e.producerName&&e.hasOwnProperty("producerName")&&t.uint32(18).string(e.producerName),null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&t.uint32(26).string(e.producerVersion),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(34).string(e.domain),null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&t.uint32(40).int64(e.modelVersion),null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(50).string(e.docString),null!=e.graph&&e.hasOwnProperty("graph")&&c.onnx.GraphProto.encode(e.graph,t.uint32(58).fork()).ldelim(),null!=e.opsetImport&&e.opsetImport.length)for(var n=0;n<e.opsetImport.length;++n)c.onnx.OperatorSetIdProto.encode(e.opsetImport[n],t.uint32(66).fork()).ldelim();if(null!=e.metadataProps&&e.metadataProps.length)for(n=0;n<e.metadataProps.length;++n)c.onnx.StringStringEntryProto.encode(e.metadataProps[n],t.uint32(114).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.ModelProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.irVersion=e.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(c.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:r.producerName=e.string();break;case 3:r.producerVersion=e.string();break;case 4:r.domain=e.string();break;case 5:r.modelVersion=e.int64();break;case 6:r.docString=e.string();break;case 7:r.graph=c.onnx.GraphProto.decode(e,e.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(c.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.irVersion&&e.hasOwnProperty("irVersion")&&!(l.isInteger(e.irVersion)||e.irVersion&&l.isInteger(e.irVersion.low)&&l.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(null!=e.opsetImport&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var t=0;t<e.opsetImport.length;++t)if(n=c.onnx.OperatorSetIdProto.verify(e.opsetImport[t]))return"opsetImport."+n}if(null!=e.producerName&&e.hasOwnProperty("producerName")&&!l.isString(e.producerName))return"producerName: string expected";if(null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&!l.isString(e.producerVersion))return"producerVersion: string expected";if(null!=e.domain&&e.hasOwnProperty("domain")&&!l.isString(e.domain))return"domain: string expected";if(null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&!(l.isInteger(e.modelVersion)||e.modelVersion&&l.isInteger(e.modelVersion.low)&&l.isInteger(e.modelVersion.high)))return"modelVersion: integer|Long expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.graph&&e.hasOwnProperty("graph")&&(n=c.onnx.GraphProto.verify(e.graph)))return"graph."+n;if(null!=e.metadataProps&&e.hasOwnProperty("metadataProps")){if(!Array.isArray(e.metadataProps))return"metadataProps: array expected";for(t=0;t<e.metadataProps.length;++t){var n;if(n=c.onnx.StringStringEntryProto.verify(e.metadataProps[t]))return"metadataProps."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.ModelProto)return e;var t=new c.onnx.ModelProto;if(null!=e.irVersion&&(l.Long?(t.irVersion=l.Long.fromValue(e.irVersion)).unsigned=!1:"string"==typeof e.irVersion?t.irVersion=parseInt(e.irVersion,10):"number"==typeof e.irVersion?t.irVersion=e.irVersion:"object"==typeof e.irVersion&&(t.irVersion=new l.LongBits(e.irVersion.low>>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");t.opsetImport=[];for(var n=0;n<e.opsetImport.length;++n){if("object"!=typeof e.opsetImport[n])throw TypeError(".onnx.ModelProto.opsetImport: object expected");t.opsetImport[n]=c.onnx.OperatorSetIdProto.fromObject(e.opsetImport[n])}}if(null!=e.producerName&&(t.producerName=String(e.producerName)),null!=e.producerVersion&&(t.producerVersion=String(e.producerVersion)),null!=e.domain&&(t.domain=String(e.domain)),null!=e.modelVersion&&(l.Long?(t.modelVersion=l.Long.fromValue(e.modelVersion)).unsigned=!1:"string"==typeof e.modelVersion?t.modelVersion=parseInt(e.modelVersion,10):"number"==typeof e.modelVersion?t.modelVersion=e.modelVersion:"object"==typeof e.modelVersion&&(t.modelVersion=new l.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber())),null!=e.docString&&(t.docString=String(e.docString)),null!=e.graph){if("object"!=typeof e.graph)throw TypeError(".onnx.ModelProto.graph: object expected");t.graph=c.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(t.metadataProps=[],n=0;n<e.metadataProps.length;++n){if("object"!=typeof e.metadataProps[n])throw TypeError(".onnx.ModelProto.metadataProps: object expected");t.metadataProps[n]=c.onnx.StringStringEntryProto.fromObject(e.metadataProps[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.opsetImport=[],n.metadataProps=[]),t.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.irVersion=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.irVersion=t.longs===String?"0":0;n.producerName="",n.producerVersion="",n.domain="",l.Long?(r=new l.Long(0,0,!1),n.modelVersion=t.longs===String?r.toString():t.longs===Number?r.toNumber():r):n.modelVersion=t.longs===String?"0":0,n.docString="",n.graph=null}if(null!=e.irVersion&&e.hasOwnProperty("irVersion")&&("number"==typeof e.irVersion?n.irVersion=t.longs===String?String(e.irVersion):e.irVersion:n.irVersion=t.longs===String?l.Long.prototype.toString.call(e.irVersion):t.longs===Number?new l.LongBits(e.irVersion.low>>>0,e.irVersion.high>>>0).toNumber():e.irVersion),null!=e.producerName&&e.hasOwnProperty("producerName")&&(n.producerName=e.producerName),null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&(n.producerVersion=e.producerVersion),null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&("number"==typeof e.modelVersion?n.modelVersion=t.longs===String?String(e.modelVersion):e.modelVersion:n.modelVersion=t.longs===String?l.Long.prototype.toString.call(e.modelVersion):t.longs===Number?new l.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.graph&&e.hasOwnProperty("graph")&&(n.graph=c.onnx.GraphProto.toObject(e.graph,t)),e.opsetImport&&e.opsetImport.length){n.opsetImport=[];for(var i=0;i<e.opsetImport.length;++i)n.opsetImport[i]=c.onnx.OperatorSetIdProto.toObject(e.opsetImport[i],t)}if(e.metadataProps&&e.metadataProps.length)for(n.metadataProps=[],i=0;i<e.metadataProps.length;++i)n.metadataProps[i]=c.onnx.StringStringEntryProto.toObject(e.metadataProps[i],t);return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.StringStringEntryProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.key="",e.prototype.value="",e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.key&&e.hasOwnProperty("key")&&t.uint32(10).string(e.key),null!=e.value&&e.hasOwnProperty("value")&&t.uint32(18).string(e.value),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.StringStringEntryProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.string();break;case 2:r.value=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.key&&e.hasOwnProperty("key")&&!l.isString(e.key)?"key: string expected":null!=e.value&&e.hasOwnProperty("value")&&!l.isString(e.value)?"value: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.StringStringEntryProto)return e;var t=new c.onnx.StringStringEntryProto;return null!=e.key&&(t.key=String(e.key)),null!=e.value&&(t.value=String(e.value)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.key="",n.value=""),null!=e.key&&e.hasOwnProperty("key")&&(n.key=e.key),null!=e.value&&e.hasOwnProperty("value")&&(n.value=e.value),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.TensorAnnotation=function(){function e(e){if(this.quantParameterTensorNames=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.tensorName="",e.prototype.quantParameterTensorNames=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.tensorName&&e.hasOwnProperty("tensorName")&&t.uint32(10).string(e.tensorName),null!=e.quantParameterTensorNames&&e.quantParameterTensorNames.length)for(var n=0;n<e.quantParameterTensorNames.length;++n)c.onnx.StringStringEntryProto.encode(e.quantParameterTensorNames[n],t.uint32(18).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorAnnotation;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.tensorName=e.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(c.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.tensorName&&e.hasOwnProperty("tensorName")&&!l.isString(e.tensorName))return"tensorName: string expected";if(null!=e.quantParameterTensorNames&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var t=0;t<e.quantParameterTensorNames.length;++t){var n=c.onnx.StringStringEntryProto.verify(e.quantParameterTensorNames[t]);if(n)return"quantParameterTensorNames."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.TensorAnnotation)return e;var t=new c.onnx.TensorAnnotation;if(null!=e.tensorName&&(t.tensorName=String(e.tensorName)),e.quantParameterTensorNames){if(!Array.isArray(e.quantParameterTensorNames))throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");t.quantParameterTensorNames=[];for(var n=0;n<e.quantParameterTensorNames.length;++n){if("object"!=typeof e.quantParameterTensorNames[n])throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");t.quantParameterTensorNames[n]=c.onnx.StringStringEntryProto.fromObject(e.quantParameterTensorNames[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.quantParameterTensorNames=[]),t.defaults&&(n.tensorName=""),null!=e.tensorName&&e.hasOwnProperty("tensorName")&&(n.tensorName=e.tensorName),e.quantParameterTensorNames&&e.quantParameterTensorNames.length){n.quantParameterTensorNames=[];for(var r=0;r<e.quantParameterTensorNames.length;++r)n.quantParameterTensorNames[r]=c.onnx.StringStringEntryProto.toObject(e.quantParameterTensorNames[r],t)}return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.GraphProto=function(){function e(e){if(this.node=[],this.initializer=[],this.input=[],this.output=[],this.valueInfo=[],this.quantizationAnnotation=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.node=l.emptyArray,e.prototype.name="",e.prototype.initializer=l.emptyArray,e.prototype.docString="",e.prototype.input=l.emptyArray,e.prototype.output=l.emptyArray,e.prototype.valueInfo=l.emptyArray,e.prototype.quantizationAnnotation=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.node&&e.node.length)for(var n=0;n<e.node.length;++n)c.onnx.NodeProto.encode(e.node[n],t.uint32(10).fork()).ldelim();if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(18).string(e.name),null!=e.initializer&&e.initializer.length)for(n=0;n<e.initializer.length;++n)c.onnx.TensorProto.encode(e.initializer[n],t.uint32(42).fork()).ldelim();if(null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(82).string(e.docString),null!=e.input&&e.input.length)for(n=0;n<e.input.length;++n)c.onnx.ValueInfoProto.encode(e.input[n],t.uint32(90).fork()).ldelim();if(null!=e.output&&e.output.length)for(n=0;n<e.output.length;++n)c.onnx.ValueInfoProto.encode(e.output[n],t.uint32(98).fork()).ldelim();if(null!=e.valueInfo&&e.valueInfo.length)for(n=0;n<e.valueInfo.length;++n)c.onnx.ValueInfoProto.encode(e.valueInfo[n],t.uint32(106).fork()).ldelim();if(null!=e.quantizationAnnotation&&e.quantizationAnnotation.length)for(n=0;n<e.quantizationAnnotation.length;++n)c.onnx.TensorAnnotation.encode(e.quantizationAnnotation[n],t.uint32(114).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.GraphProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(c.onnx.NodeProto.decode(e,e.uint32()));break;case 2:r.name=e.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(c.onnx.TensorProto.decode(e,e.uint32()));break;case 10:r.docString=e.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(c.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(c.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(c.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(c.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.node&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var t=0;t<e.node.length;++t)if(n=c.onnx.NodeProto.verify(e.node[t]))return"node."+n}if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.initializer&&e.hasOwnProperty("initializer")){if(!Array.isArray(e.initializer))return"initializer: array expected";for(t=0;t<e.initializer.length;++t)if(n=c.onnx.TensorProto.verify(e.initializer[t]))return"initializer."+n}if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.input&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(t=0;t<e.input.length;++t)if(n=c.onnx.ValueInfoProto.verify(e.input[t]))return"input."+n}if(null!=e.output&&e.hasOwnProperty("output")){if(!Array.isArray(e.output))return"output: array expected";for(t=0;t<e.output.length;++t)if(n=c.onnx.ValueInfoProto.verify(e.output[t]))return"output."+n}if(null!=e.valueInfo&&e.hasOwnProperty("valueInfo")){if(!Array.isArray(e.valueInfo))return"valueInfo: array expected";for(t=0;t<e.valueInfo.length;++t)if(n=c.onnx.ValueInfoProto.verify(e.valueInfo[t]))return"valueInfo."+n}if(null!=e.quantizationAnnotation&&e.hasOwnProperty("quantizationAnnotation")){if(!Array.isArray(e.quantizationAnnotation))return"quantizationAnnotation: array expected";for(t=0;t<e.quantizationAnnotation.length;++t){var n;if(n=c.onnx.TensorAnnotation.verify(e.quantizationAnnotation[t]))return"quantizationAnnotation."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.GraphProto)return e;var t=new c.onnx.GraphProto;if(e.node){if(!Array.isArray(e.node))throw TypeError(".onnx.GraphProto.node: array expected");t.node=[];for(var n=0;n<e.node.length;++n){if("object"!=typeof e.node[n])throw TypeError(".onnx.GraphProto.node: object expected");t.node[n]=c.onnx.NodeProto.fromObject(e.node[n])}}if(null!=e.name&&(t.name=String(e.name)),e.initializer){if(!Array.isArray(e.initializer))throw TypeError(".onnx.GraphProto.initializer: array expected");for(t.initializer=[],n=0;n<e.initializer.length;++n){if("object"!=typeof e.initializer[n])throw TypeError(".onnx.GraphProto.initializer: object expected");t.initializer[n]=c.onnx.TensorProto.fromObject(e.initializer[n])}}if(null!=e.docString&&(t.docString=String(e.docString)),e.input){if(!Array.isArray(e.input))throw TypeError(".onnx.GraphProto.input: array expected");for(t.input=[],n=0;n<e.input.length;++n){if("object"!=typeof e.input[n])throw TypeError(".onnx.GraphProto.input: object expected");t.input[n]=c.onnx.ValueInfoProto.fromObject(e.input[n])}}if(e.output){if(!Array.isArray(e.output))throw TypeError(".onnx.GraphProto.output: array expected");for(t.output=[],n=0;n<e.output.length;++n){if("object"!=typeof e.output[n])throw TypeError(".onnx.GraphProto.output: object expected");t.output[n]=c.onnx.ValueInfoProto.fromObject(e.output[n])}}if(e.valueInfo){if(!Array.isArray(e.valueInfo))throw TypeError(".onnx.GraphProto.valueInfo: array expected");for(t.valueInfo=[],n=0;n<e.valueInfo.length;++n){if("object"!=typeof e.valueInfo[n])throw TypeError(".onnx.GraphProto.valueInfo: object expected");t.valueInfo[n]=c.onnx.ValueInfoProto.fromObject(e.valueInfo[n])}}if(e.quantizationAnnotation){if(!Array.isArray(e.quantizationAnnotation))throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");for(t.quantizationAnnotation=[],n=0;n<e.quantizationAnnotation.length;++n){if("object"!=typeof e.quantizationAnnotation[n])throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");t.quantizationAnnotation[n]=c.onnx.TensorAnnotation.fromObject(e.quantizationAnnotation[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.node=[],n.initializer=[],n.input=[],n.output=[],n.valueInfo=[],n.quantizationAnnotation=[]),t.defaults&&(n.name="",n.docString=""),e.node&&e.node.length){n.node=[];for(var r=0;r<e.node.length;++r)n.node[r]=c.onnx.NodeProto.toObject(e.node[r],t)}if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),e.initializer&&e.initializer.length)for(n.initializer=[],r=0;r<e.initializer.length;++r)n.initializer[r]=c.onnx.TensorProto.toObject(e.initializer[r],t);if(null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),e.input&&e.input.length)for(n.input=[],r=0;r<e.input.length;++r)n.input[r]=c.onnx.ValueInfoProto.toObject(e.input[r],t);if(e.output&&e.output.length)for(n.output=[],r=0;r<e.output.length;++r)n.output[r]=c.onnx.ValueInfoProto.toObject(e.output[r],t);if(e.valueInfo&&e.valueInfo.length)for(n.valueInfo=[],r=0;r<e.valueInfo.length;++r)n.valueInfo[r]=c.onnx.ValueInfoProto.toObject(e.valueInfo[r],t);if(e.quantizationAnnotation&&e.quantizationAnnotation.length)for(n.quantizationAnnotation=[],r=0;r<e.quantizationAnnotation.length;++r)n.quantizationAnnotation[r]=c.onnx.TensorAnnotation.toObject(e.quantizationAnnotation[r],t);return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o.TensorProto=function(){function e(e){if(this.dims=[],this.floatData=[],this.int32Data=[],this.stringData=[],this.int64Data=[],this.externalData=[],this.doubleData=[],this.uint64Data=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.dims=l.emptyArray,e.prototype.dataType=0,e.prototype.segment=null,e.prototype.floatData=l.emptyArray,e.prototype.int32Data=l.emptyArray,e.prototype.stringData=l.emptyArray,e.prototype.int64Data=l.emptyArray,e.prototype.name="",e.prototype.docString="",e.prototype.rawData=l.newBuffer([]),e.prototype.externalData=l.emptyArray,e.prototype.dataLocation=0,e.prototype.doubleData=l.emptyArray,e.prototype.uint64Data=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.dims&&e.dims.length){t.uint32(10).fork();for(var n=0;n<e.dims.length;++n)t.int64(e.dims[n]);t.ldelim()}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&t.uint32(16).int32(e.dataType),null!=e.segment&&e.hasOwnProperty("segment")&&c.onnx.TensorProto.Segment.encode(e.segment,t.uint32(26).fork()).ldelim(),null!=e.floatData&&e.floatData.length){for(t.uint32(34).fork(),n=0;n<e.floatData.length;++n)t.float(e.floatData[n]);t.ldelim()}if(null!=e.int32Data&&e.int32Data.length){for(t.uint32(42).fork(),n=0;n<e.int32Data.length;++n)t.int32(e.int32Data[n]);t.ldelim()}if(null!=e.stringData&&e.stringData.length)for(n=0;n<e.stringData.length;++n)t.uint32(50).bytes(e.stringData[n]);if(null!=e.int64Data&&e.int64Data.length){for(t.uint32(58).fork(),n=0;n<e.int64Data.length;++n)t.int64(e.int64Data[n]);t.ldelim()}if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(66).string(e.name),null!=e.rawData&&e.hasOwnProperty("rawData")&&t.uint32(74).bytes(e.rawData),null!=e.doubleData&&e.doubleData.length){for(t.uint32(82).fork(),n=0;n<e.doubleData.length;++n)t.double(e.doubleData[n]);t.ldelim()}if(null!=e.uint64Data&&e.uint64Data.length){for(t.uint32(90).fork(),n=0;n<e.uint64Data.length;++n)t.uint64(e.uint64Data[n]);t.ldelim()}if(null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(98).string(e.docString),null!=e.externalData&&e.externalData.length)for(n=0;n<e.externalData.length;++n)c.onnx.StringStringEntryProto.encode(e.externalData[n],t.uint32(106).fork()).ldelim();return null!=e.dataLocation&&e.hasOwnProperty("dataLocation")&&t.uint32(112).int32(e.dataLocation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&i))for(var o=e.uint32()+e.pos;e.pos<o;)r.dims.push(e.int64());else r.dims.push(e.int64());break;case 2:r.dataType=e.int32();break;case 3:r.segment=c.onnx.TensorProto.Segment.decode(e,e.uint32());break;case 4:if(r.floatData&&r.floatData.length||(r.floatData=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.floatData.push(e.float());else r.floatData.push(e.float());break;case 5:if(r.int32Data&&r.int32Data.length||(r.int32Data=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.int32Data.push(e.int32());else r.int32Data.push(e.int32());break;case 6:r.stringData&&r.stringData.length||(r.stringData=[]),r.stringData.push(e.bytes());break;case 7:if(r.int64Data&&r.int64Data.length||(r.int64Data=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.int64Data.push(e.int64());else r.int64Data.push(e.int64());break;case 8:r.name=e.string();break;case 12:r.docString=e.string();break;case 9:r.rawData=e.bytes();break;case 13:r.externalData&&r.externalData.length||(r.externalData=[]),r.externalData.push(c.onnx.StringStringEntryProto.decode(e,e.uint32()));break;case 14:r.dataLocation=e.int32();break;case 10:if(r.doubleData&&r.doubleData.length||(r.doubleData=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.doubleData.push(e.double());else r.doubleData.push(e.double());break;case 11:if(r.uint64Data&&r.uint64Data.length||(r.uint64Data=[]),2==(7&i))for(o=e.uint32()+e.pos;e.pos<o;)r.uint64Data.push(e.uint64());else r.uint64Data.push(e.uint64());break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.dims&&e.hasOwnProperty("dims")){if(!Array.isArray(e.dims))return"dims: array expected";for(var t=0;t<e.dims.length;++t)if(!(l.isInteger(e.dims[t])||e.dims[t]&&l.isInteger(e.dims[t].low)&&l.isInteger(e.dims[t].high)))return"dims: integer|Long[] expected"}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&!l.isInteger(e.dataType))return"dataType: integer expected";if(null!=e.segment&&e.hasOwnProperty("segment")&&(n=c.onnx.TensorProto.Segment.verify(e.segment)))return"segment."+n;if(null!=e.floatData&&e.hasOwnProperty("floatData")){if(!Array.isArray(e.floatData))return"floatData: array expected";for(t=0;t<e.floatData.length;++t)if("number"!=typeof e.floatData[t])return"floatData: number[] expected"}if(null!=e.int32Data&&e.hasOwnProperty("int32Data")){if(!Array.isArray(e.int32Data))return"int32Data: array expected";for(t=0;t<e.int32Data.length;++t)if(!l.isInteger(e.int32Data[t]))return"int32Data: integer[] expected"}if(null!=e.stringData&&e.hasOwnProperty("stringData")){if(!Array.isArray(e.stringData))return"stringData: array expected";for(t=0;t<e.stringData.length;++t)if(!(e.stringData[t]&&"number"==typeof e.stringData[t].length||l.isString(e.stringData[t])))return"stringData: buffer[] expected"}if(null!=e.int64Data&&e.hasOwnProperty("int64Data")){if(!Array.isArray(e.int64Data))return"int64Data: array expected";for(t=0;t<e.int64Data.length;++t)if(!(l.isInteger(e.int64Data[t])||e.int64Data[t]&&l.isInteger(e.int64Data[t].low)&&l.isInteger(e.int64Data[t].high)))return"int64Data: integer|Long[] expected"}if(null!=e.name&&e.hasOwnProperty("name")&&!l.isString(e.name))return"name: string expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!l.isString(e.docString))return"docString: string expected";if(null!=e.rawData&&e.hasOwnProperty("rawData")&&!(e.rawData&&"number"==typeof e.rawData.length||l.isString(e.rawData)))return"rawData: buffer expected";if(null!=e.externalData&&e.hasOwnProperty("externalData")){if(!Array.isArray(e.externalData))return"externalData: array expected";for(t=0;t<e.externalData.length;++t){var n;if(n=c.onnx.StringStringEntryProto.verify(e.externalData[t]))return"externalData."+n}}if(null!=e.dataLocation&&e.hasOwnProperty("dataLocation"))switch(e.dataLocation){default:return"dataLocation: enum value expected";case 0:case 1:}if(null!=e.doubleData&&e.hasOwnProperty("doubleData")){if(!Array.isArray(e.doubleData))return"doubleData: array expected";for(t=0;t<e.doubleData.length;++t)if("number"!=typeof e.doubleData[t])return"doubleData: number[] expected"}if(null!=e.uint64Data&&e.hasOwnProperty("uint64Data")){if(!Array.isArray(e.uint64Data))return"uint64Data: array expected";for(t=0;t<e.uint64Data.length;++t)if(!(l.isInteger(e.uint64Data[t])||e.uint64Data[t]&&l.isInteger(e.uint64Data[t].low)&&l.isInteger(e.uint64Data[t].high)))return"uint64Data: integer|Long[] expected"}return null},e.fromObject=function(e){if(e instanceof c.onnx.TensorProto)return e;var t=new c.onnx.TensorProto;if(e.dims){if(!Array.isArray(e.dims))throw TypeError(".onnx.TensorProto.dims: array expected");t.dims=[];for(var n=0;n<e.dims.length;++n)l.Long?(t.dims[n]=l.Long.fromValue(e.dims[n])).unsigned=!1:"string"==typeof e.dims[n]?t.dims[n]=parseInt(e.dims[n],10):"number"==typeof e.dims[n]?t.dims[n]=e.dims[n]:"object"==typeof e.dims[n]&&(t.dims[n]=new l.LongBits(e.dims[n].low>>>0,e.dims[n].high>>>0).toNumber())}if(null!=e.dataType&&(t.dataType=0|e.dataType),null!=e.segment){if("object"!=typeof e.segment)throw TypeError(".onnx.TensorProto.segment: object expected");t.segment=c.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(t.floatData=[],n=0;n<e.floatData.length;++n)t.floatData[n]=Number(e.floatData[n])}if(e.int32Data){if(!Array.isArray(e.int32Data))throw TypeError(".onnx.TensorProto.int32Data: array expected");for(t.int32Data=[],n=0;n<e.int32Data.length;++n)t.int32Data[n]=0|e.int32Data[n]}if(e.stringData){if(!Array.isArray(e.stringData))throw TypeError(".onnx.TensorProto.stringData: array expected");for(t.stringData=[],n=0;n<e.stringData.length;++n)"string"==typeof e.stringData[n]?l.base64.decode(e.stringData[n],t.stringData[n]=l.newBuffer(l.base64.length(e.stringData[n])),0):e.stringData[n].length&&(t.stringData[n]=e.stringData[n])}if(e.int64Data){if(!Array.isArray(e.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");for(t.int64Data=[],n=0;n<e.int64Data.length;++n)l.Long?(t.int64Data[n]=l.Long.fromValue(e.int64Data[n])).unsigned=!1:"string"==typeof e.int64Data[n]?t.int64Data[n]=parseInt(e.int64Data[n],10):"number"==typeof e.int64Data[n]?t.int64Data[n]=e.int64Data[n]:"object"==typeof e.int64Data[n]&&(t.int64Data[n]=new l.LongBits(e.int64Data[n].low>>>0,e.int64Data[n].high>>>0).toNumber())}if(null!=e.name&&(t.name=String(e.name)),null!=e.docString&&(t.docString=String(e.docString)),null!=e.rawData&&("string"==typeof e.rawData?l.base64.decode(e.rawData,t.rawData=l.newBuffer(l.base64.length(e.rawData)),0):e.rawData.length&&(t.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(t.externalData=[],n=0;n<e.externalData.length;++n){if("object"!=typeof e.externalData[n])throw TypeError(".onnx.TensorProto.externalData: object expected");t.externalData[n]=c.onnx.StringStringEntryProto.fromObject(e.externalData[n])}}switch(e.dataLocation){case"DEFAULT":case 0:t.dataLocation=0;break;case"EXTERNAL":case 1:t.dataLocation=1}if(e.doubleData){if(!Array.isArray(e.doubleData))throw TypeError(".onnx.TensorProto.doubleData: array expected");for(t.doubleData=[],n=0;n<e.doubleData.length;++n)t.doubleData[n]=Number(e.doubleData[n])}if(e.uint64Data){if(!Array.isArray(e.uint64Data))throw TypeError(".onnx.TensorProto.uint64Data: array expected");for(t.uint64Data=[],n=0;n<e.uint64Data.length;++n)l.Long?(t.uint64Data[n]=l.Long.fromValue(e.uint64Data[n])).unsigned=!0:"string"==typeof e.uint64Data[n]?t.uint64Data[n]=parseInt(e.uint64Data[n],10):"number"==typeof e.uint64Data[n]?t.uint64Data[n]=e.uint64Data[n]:"object"==typeof e.uint64Data[n]&&(t.uint64Data[n]=new l.LongBits(e.uint64Data[n].low>>>0,e.uint64Data[n].high>>>0).toNumber(!0))}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),t.defaults&&(n.dataType=0,n.segment=null,n.name="",t.bytes===String?n.rawData="":(n.rawData=[],t.bytes!==Array&&(n.rawData=l.newBuffer(n.rawData))),n.docString="",n.dataLocation=t.enums===String?"DEFAULT":0),e.dims&&e.dims.length){n.dims=[];for(var r=0;r<e.dims.length;++r)"number"==typeof e.dims[r]?n.dims[r]=t.longs===String?String(e.dims[r]):e.dims[r]:n.dims[r]=t.longs===String?l.Long.prototype.toString.call(e.dims[r]):t.longs===Number?new l.LongBits(e.dims[r].low>>>0,e.dims[r].high>>>0).toNumber():e.dims[r]}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&(n.dataType=e.dataType),null!=e.segment&&e.hasOwnProperty("segment")&&(n.segment=c.onnx.TensorProto.Segment.toObject(e.segment,t)),e.floatData&&e.floatData.length)for(n.floatData=[],r=0;r<e.floatData.length;++r)n.floatData[r]=t.json&&!isFinite(e.floatData[r])?String(e.floatData[r]):e.floatData[r];if(e.int32Data&&e.int32Data.length)for(n.int32Data=[],r=0;r<e.int32Data.length;++r)n.int32Data[r]=e.int32Data[r];if(e.stringData&&e.stringData.length)for(n.stringData=[],r=0;r<e.stringData.length;++r)n.stringData[r]=t.bytes===String?l.base64.encode(e.stringData[r],0,e.stringData[r].length):t.bytes===Array?Array.prototype.slice.call(e.stringData[r]):e.stringData[r];if(e.int64Data&&e.int64Data.length)for(n.int64Data=[],r=0;r<e.int64Data.length;++r)"number"==typeof e.int64Data[r]?n.int64Data[r]=t.longs===String?String(e.int64Data[r]):e.int64Data[r]:n.int64Data[r]=t.longs===String?l.Long.prototype.toString.call(e.int64Data[r]):t.longs===Number?new l.LongBits(e.int64Data[r].low>>>0,e.int64Data[r].high>>>0).toNumber():e.int64Data[r];if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.rawData&&e.hasOwnProperty("rawData")&&(n.rawData=t.bytes===String?l.base64.encode(e.rawData,0,e.rawData.length):t.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(n.doubleData=[],r=0;r<e.doubleData.length;++r)n.doubleData[r]=t.json&&!isFinite(e.doubleData[r])?String(e.doubleData[r]):e.doubleData[r];if(e.uint64Data&&e.uint64Data.length)for(n.uint64Data=[],r=0;r<e.uint64Data.length;++r)"number"==typeof e.uint64Data[r]?n.uint64Data[r]=t.longs===String?String(e.uint64Data[r]):e.uint64Data[r]:n.uint64Data[r]=t.longs===String?l.Long.prototype.toString.call(e.uint64Data[r]):t.longs===Number?new l.LongBits(e.uint64Data[r].low>>>0,e.uint64Data[r].high>>>0).toNumber(!0):e.uint64Data[r];if(null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),e.externalData&&e.externalData.length)for(n.externalData=[],r=0;r<e.externalData.length;++r)n.externalData[r]=c.onnx.StringStringEntryProto.toObject(e.externalData[r],t);return null!=e.dataLocation&&e.hasOwnProperty("dataLocation")&&(n.dataLocation=t.enums===String?c.onnx.TensorProto.DataLocation[e.dataLocation]:e.dataLocation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.DataType=function(){var e={},t=Object.create(e);return t[e[0]="UNDEFINED"]=0,t[e[1]="FLOAT"]=1,t[e[2]="UINT8"]=2,t[e[3]="INT8"]=3,t[e[4]="UINT16"]=4,t[e[5]="INT16"]=5,t[e[6]="INT32"]=6,t[e[7]="INT64"]=7,t[e[8]="STRING"]=8,t[e[9]="BOOL"]=9,t[e[10]="FLOAT16"]=10,t[e[11]="DOUBLE"]=11,t[e[12]="UINT32"]=12,t[e[13]="UINT64"]=13,t[e[14]="COMPLEX64"]=14,t[e[15]="COMPLEX128"]=15,t[e[16]="BFLOAT16"]=16,t}(),e.Segment=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.begin=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.end=l.Long?l.Long.fromBits(0,0,!1):0,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.begin&&e.hasOwnProperty("begin")&&t.uint32(8).int64(e.begin),null!=e.end&&e.hasOwnProperty("end")&&t.uint32(16).int64(e.end),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorProto.Segment;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.begin=e.int64();break;case 2:r.end=e.int64();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.begin&&e.hasOwnProperty("begin")&&!(l.isInteger(e.begin)||e.begin&&l.isInteger(e.begin.low)&&l.isInteger(e.begin.high))?"begin: integer|Long expected":null!=e.end&&e.hasOwnProperty("end")&&!(l.isInteger(e.end)||e.end&&l.isInteger(e.end.low)&&l.isInteger(e.end.high))?"end: integer|Long expected":null},e.fromObject=function(e){if(e instanceof c.onnx.TensorProto.Segment)return e;var t=new c.onnx.TensorProto.Segment;return null!=e.begin&&(l.Long?(t.begin=l.Long.fromValue(e.begin)).unsigned=!1:"string"==typeof e.begin?t.begin=parseInt(e.begin,10):"number"==typeof e.begin?t.begin=e.begin:"object"==typeof e.begin&&(t.begin=new l.LongBits(e.begin.low>>>0,e.begin.high>>>0).toNumber())),null!=e.end&&(l.Long?(t.end=l.Long.fromValue(e.end)).unsigned=!1:"string"==typeof e.end?t.end=parseInt(e.end,10):"number"==typeof e.end?t.end=e.end:"object"==typeof e.end&&(t.end=new l.LongBits(e.end.low>>>0,e.end.high>>>0).toNumber())),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.begin=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.begin=t.longs===String?"0":0;l.Long?(r=new l.Long(0,0,!1),n.end=t.longs===String?r.toString():t.longs===Number?r.toNumber():r):n.end=t.longs===String?"0":0}return null!=e.begin&&e.hasOwnProperty("begin")&&("number"==typeof e.begin?n.begin=t.longs===String?String(e.begin):e.begin:n.begin=t.longs===String?l.Long.prototype.toString.call(e.begin):t.longs===Number?new l.LongBits(e.begin.low>>>0,e.begin.high>>>0).toNumber():e.begin),null!=e.end&&e.hasOwnProperty("end")&&("number"==typeof e.end?n.end=t.longs===String?String(e.end):e.end:n.end=t.longs===String?l.Long.prototype.toString.call(e.end):t.longs===Number?new l.LongBits(e.end.low>>>0,e.end.high>>>0).toNumber():e.end),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e.DataLocation=function(){var e={},t=Object.create(e);return t[e[0]="DEFAULT"]=0,t[e[1]="EXTERNAL"]=1,t}(),e}(),o.TensorShapeProto=function(){function e(e){if(this.dim=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.dim=l.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=u.create()),null!=e.dim&&e.dim.length)for(var n=0;n<e.dim.length;++n)c.onnx.TensorShapeProto.Dimension.encode(e.dim[n],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorShapeProto;e.pos<n;){var i=e.uint32();i>>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(c.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&i)}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.dim&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var t=0;t<e.dim.length;++t){var n=c.onnx.TensorShapeProto.Dimension.verify(e.dim[t]);if(n)return"dim."+n}}return null},e.fromObject=function(e){if(e instanceof c.onnx.TensorShapeProto)return e;var t=new c.onnx.TensorShapeProto;if(e.dim){if(!Array.isArray(e.dim))throw TypeError(".onnx.TensorShapeProto.dim: array expected");t.dim=[];for(var n=0;n<e.dim.length;++n){if("object"!=typeof e.dim[n])throw TypeError(".onnx.TensorShapeProto.dim: object expected");t.dim[n]=c.onnx.TensorShapeProto.Dimension.fromObject(e.dim[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.dim=[]),e.dim&&e.dim.length){n.dim=[];for(var r=0;r<e.dim.length;++r)n.dim[r]=c.onnx.TensorShapeProto.Dimension.toObject(e.dim[r],t)}return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.Dimension=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t;return e.prototype.dimValue=l.Long?l.Long.fromBits(0,0,!1):0,e.prototype.dimParam="",e.prototype.denotation="",Object.defineProperty(e.prototype,"value",{get:l.oneOfGetter(t=["dimValue","dimParam"]),set:l.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.dimValue&&e.hasOwnProperty("dimValue")&&t.uint32(8).int64(e.dimValue),null!=e.dimParam&&e.hasOwnProperty("dimParam")&&t.uint32(18).string(e.dimParam),null!=e.denotation&&e.hasOwnProperty("denotation")&&t.uint32(26).string(e.denotation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TensorShapeProto.Dimension;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.dimValue=e.int64();break;case 2:r.dimParam=e.string();break;case 3:r.denotation=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.dimValue&&e.hasOwnProperty("dimValue")&&(t.value=1,!(l.isInteger(e.dimValue)||e.dimValue&&l.isInteger(e.dimValue.low)&&l.isInteger(e.dimValue.high))))return"dimValue: integer|Long expected";if(null!=e.dimParam&&e.hasOwnProperty("dimParam")){if(1===t.value)return"value: multiple values";if(t.value=1,!l.isString(e.dimParam))return"dimParam: string expected"}return null!=e.denotation&&e.hasOwnProperty("denotation")&&!l.isString(e.denotation)?"denotation: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.TensorShapeProto.Dimension)return e;var t=new c.onnx.TensorShapeProto.Dimension;return null!=e.dimValue&&(l.Long?(t.dimValue=l.Long.fromValue(e.dimValue)).unsigned=!1:"string"==typeof e.dimValue?t.dimValue=parseInt(e.dimValue,10):"number"==typeof e.dimValue?t.dimValue=e.dimValue:"object"==typeof e.dimValue&&(t.dimValue=new l.LongBits(e.dimValue.low>>>0,e.dimValue.high>>>0).toNumber())),null!=e.dimParam&&(t.dimParam=String(e.dimParam)),null!=e.denotation&&(t.denotation=String(e.denotation)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.denotation=""),null!=e.dimValue&&e.hasOwnProperty("dimValue")&&("number"==typeof e.dimValue?n.dimValue=t.longs===String?String(e.dimValue):e.dimValue:n.dimValue=t.longs===String?l.Long.prototype.toString.call(e.dimValue):t.longs===Number?new l.LongBits(e.dimValue.low>>>0,e.dimValue.high>>>0).toNumber():e.dimValue,t.oneofs&&(n.value="dimValue")),null!=e.dimParam&&e.hasOwnProperty("dimParam")&&(n.dimParam=e.dimParam,t.oneofs&&(n.value="dimParam")),null!=e.denotation&&e.hasOwnProperty("denotation")&&(n.denotation=e.denotation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e}(),o.TypeProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t;return e.prototype.tensorType=null,e.prototype.denotation="",Object.defineProperty(e.prototype,"value",{get:l.oneOfGetter(t=["tensorType"]),set:l.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.tensorType&&e.hasOwnProperty("tensorType")&&c.onnx.TypeProto.Tensor.encode(e.tensorType,t.uint32(10).fork()).ldelim(),null!=e.denotation&&e.hasOwnProperty("denotation")&&t.uint32(50).string(e.denotation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TypeProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.tensorType=c.onnx.TypeProto.Tensor.decode(e,e.uint32());break;case 6:r.denotation=e.string();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.tensorType&&e.hasOwnProperty("tensorType")){var t=c.onnx.TypeProto.Tensor.verify(e.tensorType);if(t)return"tensorType."+t}return null!=e.denotation&&e.hasOwnProperty("denotation")&&!l.isString(e.denotation)?"denotation: string expected":null},e.fromObject=function(e){if(e instanceof c.onnx.TypeProto)return e;var t=new c.onnx.TypeProto;if(null!=e.tensorType){if("object"!=typeof e.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");t.tensorType=c.onnx.TypeProto.Tensor.fromObject(e.tensorType)}return null!=e.denotation&&(t.denotation=String(e.denotation)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.denotation=""),null!=e.tensorType&&e.hasOwnProperty("tensorType")&&(n.tensorType=c.onnx.TypeProto.Tensor.toObject(e.tensorType,t),t.oneofs&&(n.value="tensorType")),null!=e.denotation&&e.hasOwnProperty("denotation")&&(n.denotation=e.denotation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.Tensor=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.elemType=0,e.prototype.shape=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.elemType&&e.hasOwnProperty("elemType")&&t.uint32(8).int32(e.elemType),null!=e.shape&&e.hasOwnProperty("shape")&&c.onnx.TensorShapeProto.encode(e.shape,t.uint32(18).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.TypeProto.Tensor;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.elemType=e.int32();break;case 2:r.shape=c.onnx.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.elemType&&e.hasOwnProperty("elemType")&&!l.isInteger(e.elemType))return"elemType: integer expected";if(null!=e.shape&&e.hasOwnProperty("shape")){var t=c.onnx.TensorShapeProto.verify(e.shape);if(t)return"shape."+t}return null},e.fromObject=function(e){if(e instanceof c.onnx.TypeProto.Tensor)return e;var t=new c.onnx.TypeProto.Tensor;if(null!=e.elemType&&(t.elemType=0|e.elemType),null!=e.shape){if("object"!=typeof e.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");t.shape=c.onnx.TensorShapeProto.fromObject(e.shape)}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.elemType=0,n.shape=null),null!=e.elemType&&e.hasOwnProperty("elemType")&&(n.elemType=e.elemType),null!=e.shape&&e.hasOwnProperty("shape")&&(n.shape=c.onnx.TensorShapeProto.toObject(e.shape,t)),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e}(),o.OperatorSetIdProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.domain="",e.prototype.version=l.Long?l.Long.fromBits(0,0,!1):0,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=u.create()),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(10).string(e.domain),null!=e.version&&e.hasOwnProperty("version")&&t.uint32(16).int64(e.version),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new c.onnx.OperatorSetIdProto;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.domain=e.string();break;case 2:r.version=e.int64();break;default:e.skipType(7&i)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.domain&&e.hasOwnProperty("domain")&&!l.isString(e.domain)?"domain: string expected":null!=e.version&&e.hasOwnProperty("version")&&!(l.isInteger(e.version)||e.version&&l.isInteger(e.version.low)&&l.isInteger(e.version.high))?"version: integer|Long expected":null},e.fromObject=function(e){if(e instanceof c.onnx.OperatorSetIdProto)return e;var t=new c.onnx.OperatorSetIdProto;return null!=e.domain&&(t.domain=String(e.domain)),null!=e.version&&(l.Long?(t.version=l.Long.fromValue(e.version)).unsigned=!1:"string"==typeof e.version?t.version=parseInt(e.version,10):"number"==typeof e.version?t.version=e.version:"object"==typeof e.version&&(t.version=new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults)if(n.domain="",l.Long){var r=new l.Long(0,0,!1);n.version=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.version=t.longs===String?"0":0;return null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),null!=e.version&&e.hasOwnProperty("version")&&("number"==typeof e.version?n.version=t.longs===String?String(e.version):e.version:n.version=t.longs===String?l.Long.prototype.toString.call(e.version):t.longs===Number?new l.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),o),e.exports=c},2100:(e,t,n)=>{"use strict";e.exports=n(9482)},9482:(e,t,n)=>{"use strict";var r=t;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=i,i()},1408:(e,t,n)=>{"use strict";e.exports=u;var r,i=n(9693),o=i.LongBits,s=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function u(e){this.buf=e,this.pos=0,this.len=e.length}var l,c="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new u(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new u(e);throw Error("illegal buffer")},d=function(){return i.Buffer?function(e){return(u.create=function(e){return i.Buffer.isBuffer(e)?new r(e):c(e)})(e)}:c};function h(){var e=new o(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}u.create=d(),u.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,u.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},u.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},u.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)},u.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},u.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},u._configure=function(e){r=e,u.create=d(),r._configure();var t=i.Long?"toLong":"toNumber";i.merge(u.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},593:(e,t,n)=>{"use strict";e.exports=o;var r=n(1408);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(e){r.call(this,e)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o._configure()},5054:e=>{"use strict";e.exports={}},5994:(e,t,n)=>{"use strict";t.Service=n(7948)},7948:(e,t,n)=>{"use strict";e.exports=i;var r=n(9693);function i(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function e(t,n,i,o,s){if(!o)throw TypeError("request must be specified");var a=this;if(!s)return r.asPromise(e,a,t,n,i,o);if(a.rpcImpl)try{return a.rpcImpl(t,n[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(e,n){if(e)return a.emit("error",e,t),s(e);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return a.emit("error",e,t),s(e)}return a.emit("data",n,t),s(null,n)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){s(e)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(e,t,n)=>{"use strict";e.exports=i;var r=n(9693);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return o;var t=e<0;t&&(e=-e);var n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(e){if("number"==typeof e)return i.fromNumber(e);if(r.isString(e)){if(!r.Long)return i.fromNumber(parseInt(e,10));e=r.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):o},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===s?o:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},9693:function(e,t,n){"use strict";var r=t;function i(e,t,n){for(var r=Object.keys(t),i=0;i<r.length;++i)void 0!==e[r[i]]&&n||(e[r[i]]=t[r[i]]);return e}function o(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&i(this,n)}return(t.prototype=Object.create(Error.prototype)).constructor=t,Object.defineProperty(t.prototype,"name",{get:function(){return e}}),t.prototype.toString=function(){return this.name+": "+this.message},t}r.asPromise=n(4537),r.base64=n(7419),r.EventEmitter=n(9211),r.float=n(945),r.inquire=n(7199),r.utf8=n(4997),r.pool=n(6662),r.LongBits=n(1945),r.isNode=Boolean(void 0!==n.g&&n.g&&n.g.process&&n.g.process.versions&&n.g.process.versions.node),r.global=r.isNode&&n.g||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},r.isString=function(e){return"string"==typeof e||e instanceof String},r.isObject=function(e){return e&&"object"==typeof e},r.isset=r.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},r.merge=i,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=o,r.ProtocolError=o("ProtocolError"),r.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},r.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var e=r.Buffer;e?(r._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},r._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):r._Buffer_from=r._Buffer_allocUnsafe=null}},1173:(e,t,n)=>{"use strict";e.exports=d;var r,i=n(9693),o=i.LongBits,s=i.base64,a=i.utf8;function u(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function l(){}function c(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function d(){this.len=0,this.head=new u(l,0,0),this.tail=this.head,this.states=null}var h=function(){return i.Buffer?function(){return(d.create=function(){return new r})()}:function(){return new d}};function p(e,t,n){t[n]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function m(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}d.create=h(),d.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.prototype._push=function(e,t,n){return this.tail=this.tail.next=new u(e,t,n),this.len+=t,this},f.prototype=Object.create(u.prototype),f.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},d.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},d.prototype.int32=function(e){return e<0?this._push(g,10,o.fromNumber(e)):this.uint32(e)},d.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},d.prototype.uint64=function(e){var t=o.from(e);return this._push(g,t.length(),t)},d.prototype.int64=d.prototype.uint64,d.prototype.sint64=function(e){var t=o.from(e).zzEncode();return this._push(g,t.length(),t)},d.prototype.bool=function(e){return this._push(p,1,e?1:0)},d.prototype.fixed32=function(e){return this._push(m,4,e>>>0)},d.prototype.sfixed32=d.prototype.fixed32,d.prototype.fixed64=function(e){var t=o.from(e);return this._push(m,4,t.lo)._push(m,4,t.hi)},d.prototype.sfixed64=d.prototype.fixed64,d.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},d.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var b=i.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var r=0;r<e.length;++r)t[n+r]=e[r]};d.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(p,1,0);if(i.isString(e)){var n=d.alloc(t=s.length(e));s.decode(e,n,0),e=n}return this.uint32(t)._push(b,t,e)},d.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},d.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new u(l,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(l,0,0),this.len=0),this},d.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},d.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},d._configure=function(e){r=e,d.create=h(),r._configure()}},3155:(e,t,n)=>{"use strict";e.exports=o;var r=n(1173);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(){r.call(this)}function s(e,t,n){e.length<40?i.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var r=0;r<e.length;)t[n++]=e[r++]}},o.prototype.bytes=function(e){i.isString(e)&&(e=i._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(s,t,e),this},o._configure()},4154:e=>{"use strict";e.exports='"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'},7067:()=>{},1296:()=>{},760:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(e,t,n)=>{"use strict";n.r(t),n.d(t,{flatbuffers:()=>r});var r={};r.Offset,r.Table,r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(e,t){this.low=0|e,this.high=0|t},r.Long.create=function(e,t){return 0==e&&0==t?r.Long.ZERO:new r.Long(e,t)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(e){return this.low==e.low&&this.high==e.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(e){if(e)t=e;else var t=1024;this.bb=r.ByteBuffer.allocate(t),this.space=t,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.forceDefaults=function(e){this.force_defaults=e},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(e,t){e>this.minalign&&(this.minalign=e);for(var n=1+~(this.bb.capacity()-this.space+t)&e-1;this.space<n+e+t;){var i=this.bb.capacity();this.bb=r.Builder.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)},r.Builder.prototype.pad=function(e){for(var t=0;t<e;t++)this.bb.writeInt8(--this.space,0)},r.Builder.prototype.writeInt8=function(e){this.bb.writeInt8(this.space-=1,e)},r.Builder.prototype.writeInt16=function(e){this.bb.writeInt16(this.space-=2,e)},r.Builder.prototype.writeInt32=function(e){this.bb.writeInt32(this.space-=4,e)},r.Builder.prototype.writeInt64=function(e){this.bb.writeInt64(this.space-=8,e)},r.Builder.prototype.writeFloat32=function(e){this.bb.writeFloat32(this.space-=4,e)},r.Builder.prototype.writeFloat64=function(e){this.bb.writeFloat64(this.space-=8,e)},r.Builder.prototype.addInt8=function(e){this.prep(1,0),this.writeInt8(e)},r.Builder.prototype.addInt16=function(e){this.prep(2,0),this.writeInt16(e)},r.Builder.prototype.addInt32=function(e){this.prep(4,0),this.writeInt32(e)},r.Builder.prototype.addInt64=function(e){this.prep(8,0),this.writeInt64(e)},r.Builder.prototype.addFloat32=function(e){this.prep(4,0),this.writeFloat32(e)},r.Builder.prototype.addFloat64=function(e){this.prep(8,0),this.writeFloat64(e)},r.Builder.prototype.addFieldInt8=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))},r.Builder.prototype.addFieldInt16=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))},r.Builder.prototype.addFieldInt32=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))},r.Builder.prototype.addFieldInt64=function(e,t,n){!this.force_defaults&&t.equals(n)||(this.addInt64(t),this.slot(e))},r.Builder.prototype.addFieldFloat32=function(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))},r.Builder.prototype.addFieldFloat64=function(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))},r.Builder.prototype.addFieldOffset=function(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))},r.Builder.prototype.addFieldStruct=function(e,t,n){t!=n&&(this.nested(t),this.slot(e))},r.Builder.prototype.nested=function(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")},r.Builder.prototype.notNested=function(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")},r.Builder.prototype.slot=function(e){this.vtable[e]=this.offset()},r.Builder.prototype.offset=function(){return this.bb.capacity()-this.space},r.Builder.growByteBuffer=function(e){var t=e.capacity();if(3221225472&t)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");var n=t<<1,i=r.ByteBuffer.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i},r.Builder.prototype.addOffset=function(e){this.prep(r.SIZEOF_INT,0),this.writeInt32(this.offset()-e+r.SIZEOF_INT)},r.Builder.prototype.startObject=function(e){this.notNested(),null==this.vtable&&(this.vtable=[]),this.vtable_in_use=e;for(var t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()},r.Builder.prototype.endObject=function(){if(null==this.vtable||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);for(var e=this.offset(),t=this.vtable_in_use-1;t>=0&&0==this.vtable[t];t--);for(var n=t+1;t>=0;t--)this.addInt16(0!=this.vtable[t]?e-this.vtable[t]:0);this.addInt16(e-this.object_start);var i=(n+2)*r.SIZEOF_SHORT;this.addInt16(i);var o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){var a=this.bb.capacity()-this.vtables[t];if(i==this.bb.readInt16(a)){for(var u=r.SIZEOF_SHORT;u<i;u+=r.SIZEOF_SHORT)if(this.bb.readInt16(s+u)!=this.bb.readInt16(a+u))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e},r.Builder.prototype.finish=function(e,t,n){var i=n?r.SIZE_PREFIX_LENGTH:0;if(t){var o=t;if(this.prep(this.minalign,r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH+i),o.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var s=r.FILE_IDENTIFIER_LENGTH-1;s>=0;s--)this.writeInt8(o.charCodeAt(s))}this.prep(this.minalign,r.SIZEOF_INT+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(e,t){this.finish(e,t,!0)},r.Builder.prototype.requiredField=function(e,t){var n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+t))throw new Error("FlatBuffers: field "+t+" must be set")},r.Builder.prototype.startVector=function(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(r.SIZEOF_INT,e*t),this.prep(n,e*t)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(e){if(e instanceof Uint8Array)var t=e;else{t=[];for(var n=0;n<e.length;){var r,i=e.charCodeAt(n++);(r=i<55296||i>=56320?i:(i<<10)+e.charCodeAt(n++)+-56613888)<128?t.push(r):(r<2048?t.push(r>>6&31|192):(r<65536?t.push(r>>12&15|224):t.push(r>>18&7|240,r>>12&63|128),t.push(r>>6&63|128)),t.push(63&r|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length),n=0;for(var o=this.space,s=this.bb.bytes();n<t.length;n++)s[o++]=t[n];return this.endVector()},r.Builder.prototype.createLong=function(e,t){return r.Long.create(e,t)},r.ByteBuffer=function(e){this.bytes_=e,this.position_=0},r.ByteBuffer.allocate=function(e){return new r.ByteBuffer(new Uint8Array(e))},r.ByteBuffer.prototype.clear=function(){this.position_=0},r.ByteBuffer.prototype.bytes=function(){return this.bytes_},r.ByteBuffer.prototype.position=function(){return this.position_},r.ByteBuffer.prototype.setPosition=function(e){this.position_=e},r.ByteBuffer.prototype.capacity=function(){return this.bytes_.length},r.ByteBuffer.prototype.readInt8=function(e){return this.readUint8(e)<<24>>24},r.ByteBuffer.prototype.readUint8=function(e){return this.bytes_[e]},r.ByteBuffer.prototype.readInt16=function(e){return this.readUint16(e)<<16>>16},r.ByteBuffer.prototype.readUint16=function(e){return this.bytes_[e]|this.bytes_[e+1]<<8},r.ByteBuffer.prototype.readInt32=function(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24},r.ByteBuffer.prototype.readUint32=function(e){return this.readInt32(e)>>>0},r.ByteBuffer.prototype.readInt64=function(e){return new r.Long(this.readInt32(e),this.readInt32(e+4))},r.ByteBuffer.prototype.readUint64=function(e){return new r.Long(this.readUint32(e),this.readUint32(e+4))},r.ByteBuffer.prototype.readFloat32=function(e){return r.int32[0]=this.readInt32(e),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(e){return r.int32[r.isLittleEndian?0:1]=this.readInt32(e),r.int32[r.isLittleEndian?1:0]=this.readInt32(e+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(e,t){this.bytes_[e]=t},r.ByteBuffer.prototype.writeUint8=function(e,t){this.bytes_[e]=t},r.ByteBuffer.prototype.writeInt16=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8},r.ByteBuffer.prototype.writeUint16=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8},r.ByteBuffer.prototype.writeInt32=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24},r.ByteBuffer.prototype.writeUint32=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24},r.ByteBuffer.prototype.writeInt64=function(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)},r.ByteBuffer.prototype.writeUint64=function(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)},r.ByteBuffer.prototype.writeFloat32=function(e,t){r.float32[0]=t,this.writeInt32(e,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(e,t){r.float64[0]=t,this.writeInt32(e,r.int32[r.isLittleEndian?0:1]),this.writeInt32(e+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length<this.position_+r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");for(var e="",t=0;t<r.FILE_IDENTIFIER_LENGTH;t++)e+=String.fromCharCode(this.readInt8(this.position_+r.SIZEOF_INT+t));return e},r.ByteBuffer.prototype.__offset=function(e,t){var n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0},r.ByteBuffer.prototype.__union=function(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e},r.ByteBuffer.prototype.__string=function(e,t){e+=this.readInt32(e);var n=this.readInt32(e),i="",o=0;if(e+=r.SIZEOF_INT,t===r.Encoding.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;o<n;){var s,a=this.readUint8(e+o++);if(a<192)s=a;else{var u=this.readUint8(e+o++);if(a<224)s=(31&a)<<6|63&u;else{var l=this.readUint8(e+o++);s=a<240?(15&a)<<12|(63&u)<<6|63&l:(7&a)<<18|(63&u)<<12|(63&l)<<6|63&this.readUint8(e+o++)}}s<65536?i+=String.fromCharCode(s):(s-=65536,i+=String.fromCharCode(55296+(s>>10),56320+(1023&s)))}return i},r.ByteBuffer.prototype.__indirect=function(e){return e+this.readInt32(e)},r.ByteBuffer.prototype.__vector=function(e){return e+this.readInt32(e)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(e){return this.readInt32(e+this.readInt32(e))},r.ByteBuffer.prototype.__has_identifier=function(e){if(e.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var t=0;t<r.FILE_IDENTIFIER_LENGTH;t++)if(e.charCodeAt(t)!=this.readInt8(this.position_+r.SIZEOF_INT+t))return!1;return!0},r.ByteBuffer.prototype.createLong=function(e,t){return r.Long.create(e,t)}}},__webpack_module_cache__={};function __nested_webpack_require_606622__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__nested_webpack_require_606622__),n.exports}__nested_webpack_require_606622__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __nested_webpack_require_606622__.d(t,{a:t}),t},__nested_webpack_require_606622__.d=(e,t)=>{for(var n in t)__nested_webpack_require_606622__.o(t,n)&&!__nested_webpack_require_606622__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__nested_webpack_require_606622__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__nested_webpack_require_606622__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__nested_webpack_require_606622__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __nested_webpack_exports__=__nested_webpack_require_606622__(1057);return __nested_webpack_exports__})(),module.exports=t()},793:e=>{"use strict";function t(e){try{return JSON.stringify(e)}catch(e){return'"[Circular]"'}}e.exports=function(e,n,r){var i=r&&r.stringify||t;if("object"==typeof e&&null!==e){var o=n.length+1;if(1===o)return e;var s=new Array(o);s[0]=i(e);for(var a=1;a<o;a++)s[a]=i(n[a]);return s.join(" ")}if("string"!=typeof e)return e;var u=n.length;if(0===u)return e;for(var l="",c=0,d=-1,h=e&&e.length||0,p=0;p<h;){if(37===e.charCodeAt(p)&&p+1<h){switch(d=d>-1?d:0,e.charCodeAt(p+1)){case 100:case 102:if(c>=u)break;if(null==n[c])break;d<p&&(l+=e.slice(d,p)),l+=Number(n[c]),d=p+2,p++;break;case 105:if(c>=u)break;if(null==n[c])break;d<p&&(l+=e.slice(d,p)),l+=Math.floor(Number(n[c])),d=p+2,p++;break;case 79:case 111:case 106:if(c>=u)break;if(void 0===n[c])break;d<p&&(l+=e.slice(d,p));var f=typeof n[c];if("string"===f){l+="'"+n[c]+"'",d=p+2,p++;break}if("function"===f){l+=n[c].name||"<anonymous>",d=p+2,p++;break}l+=i(n[c]),d=p+2,p++;break;case 115:if(c>=u)break;d<p&&(l+=e.slice(d,p)),l+=String(n[c]),d=p+2,p++;break;case 37:d<p&&(l+=e.slice(d,p)),l+="%",d=p+2,p++,c--}++c}++p}return-1===d?e:(d<h&&(l+=e.slice(d)),l)}},955:function(e){var t;t=()=>(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{RingBuffer:()=>n});class n{static fromArray(e,t=0){const r=new n(t);return r.fromArray(e,0===t),r}constructor(e){if(this.buffer=[],this.pos=0,e<0)throw new RangeError("Invalid size.");this.size=e}getSize(){return this.size}getPos(){return this.pos}getBufferLength(){return this.buffer.length}add(...e){e.forEach((e=>{this.buffer[this.pos]=e,this.pos=(this.pos+1)%this.size}))}get(e){if(e<0&&(e+=this.buffer.length),!(e<0||e>this.buffer.length))return this.buffer.length<this.size?this.buffer[e]:this.buffer[(this.pos+e)%this.size]}getFirst(){return this.get(0)}getLast(){return this.get(-1)}getFirstN(e){return 0===e?[]:e<0?this.getLastN(-e):this.toArray().slice(0,e)}getLastN(e){return 0===e?[]:e<0?this.getFirstN(-e):this.toArray().slice(-e)}remove(e,t=1){if(e<0&&(e+=this.buffer.length),e<0||e>this.buffer.length)return[];const n=this.toArray(),r=n.splice(e,t);return this.fromArray(n),r}removeFirst(){return this.remove(0)[0]}removeLast(){return this.remove(-1)[0]}toArray(){return this.buffer.slice(this.pos).concat(this.buffer.slice(0,this.pos))}fromArray(e,t=!1){if(!Array.isArray(e))throw new TypeError("Input value is not an array.");t&&this.resize(e.length),0!==this.size&&(this.buffer=e.slice(-this.size),this.pos=this.buffer.length%this.size)}clear(){this.buffer=[],this.pos=0}resize(e){if(e<0)throw new RangeError("The size does not allow negative values.");if(0===e)this.clear();else if(e!==this.size){const t=this.toArray();this.fromArray(t.slice(-e)),this.pos=this.buffer.length%e}this.size=e}isFull(){return this.buffer.length===this.size}isEmpty(){return 0===this.buffer.length}}return t})(),e.exports=t()},963:e=>{"use strict";const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const r=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++)n=r[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+n+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(n.attribute=e.substring(t+1,r),n.value=e.substring(r+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const r=t.matchPrefix(e+n,"a=ice-ufrag:")[0],i=t.matchPrefix(e+n,"a=ice-pwd:")[0];return r&&i?{usernameFragment:r.substring(12),password:i.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");n.profile=r[2];for(let i=3;i<r.length;i++){const o=r[i],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const r=t.parseRtpMap(s),i=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(r.parameters=i.length?t.parseFmtp(i[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{i.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let r="";r+="m="+e+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let i=0;return n.codecs.forEach((e=>{e.maxptime>i&&(i=e.maxptime)})),i>0&&(r+="a=maxptime:"+i+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const n=[],r=t.parseRtpParameters(e),i=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let u;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(u=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&u&&(t.rtx={ssrc:u}),n.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.push({ssrc:a});let c=t.matchPrefix(e,"b=");return c.length&&(c=0===c[0].indexOf("b=TIAS:")?parseInt(c[0].substring(7),10):0===c[0].indexOf("b=AS:")?1e3*parseInt(c[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=c}))),n},t.parseRtcpParameters=function(e){const n={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=i.length>0,n.compound=0===i.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};const i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0?(n=i[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let i;r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,r){let i;const o=void 0!==n?n:2;return i=e||t.generateSessionId(),"v=0\r\no="+(r||"thisisadapterortc")+" "+i+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t},874:(e,t,n)=>{"use strict";const r=n(793);e.exports=d;const i=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},o={mapHttpRequest:b,mapHttpResponse:b,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:b,res:b,err:g,errWithCause:g};function s(e,t){return"silent"===e?1/0:t.levels.values[e]}const a=Symbol("pino.logFuncs"),u=Symbol("pino.hierarchy"),l={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function c(e,t){const n={logger:t,parent:e[u]};t[u]=n}function d(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const n=e.browser.write||i;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},o=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,r);let u=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(u=!1);const g=Object.keys(e.customLevels||{}),b=["error","fatal","warn","info","debug","trace"].concat(g);"function"==typeof n&&b.forEach((function(e){n[e]=n})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const y=e.level||"info",w=Object.create(n);w.log||(w.log=v),function(e,t,n){const r={};t.forEach((e=>{r[e]=n[e]?n[e]:i[e]||i[l[e]||"log"]||v})),e[a]=r}(w,b,n),c({},w),Object.defineProperty(w,"levelVal",{get:function(){return s(this.level,this)}}),Object.defineProperty(w,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,h(this,S,w,"error"),h(this,S,w,"fatal"),h(this,S,w,"warn"),h(this,S,w,"info"),h(this,S,w,"debug"),h(this,S,w,"trace"),g.forEach((e=>{h(this,S,w,e)}))}});const S={transmit:t,serialize:o,asObject:e.browser.asObject,formatters:e.browser.formatters,levels:b,timestamp:m(e)};return w.levels=function(e){const t=e.customLevels||{};return{values:Object.assign({},d.levels.values,t),labels:Object.assign({},d.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(n){t[e[n]]=n})),t}(t))}}(e),w.level=y,w.setMaxListeners=w.getMaxListeners=w.emit=w.addListener=w.on=w.prependListener=w.once=w.prependOnceListener=w.removeListener=w.removeAllListeners=w.listeners=w.listenerCount=w.eventNames=w.write=w.flush=v,w.serializers=r,w._serialize=o,w._stdErrSerialize=u,w.child=function(n,i){if(!n)throw new Error("missing bindings for child Pino");i=i||{},o&&n.serializers&&(i.serializers=n.serializers);const s=i.serializers;if(o&&s){var a=Object.assign({},r,s),u=!0===e.browser.serialize?Object.keys(a):o;delete n.serializers,p([n],u,a,this._stdErrSerialize)}function l(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,a&&(this.serializers=a,this._serialize=u),t&&(this._logEvent=f([].concat(e._logEvent.bindings,n)))}l.prototype=this;const d=new l(this);return c(this,d),d.level=this.level,d},t&&(w._logEvent=f()),w}function h(e,t,n,o){if(Object.defineProperty(e,o,{value:s(e.level,n)>s(o,n)?v:n[a][o],writable:!0,enumerable:!0,configurable:!0}),!t.transmit&&e[o]===v)return;e[o]=function(e,t,n,o){return u=e[a][o],function(){const a=t.timestamp(),l=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===i?i:this;for(var d=0;d<l.length;d++)l[d]=arguments[d];if(t.serialize&&!t.asObject&&p(l,this._serialize,this.serializers,this._stdErrSerialize),t.asObject||t.formatters?u.call(c,function(e,t,n,i,o={}){const{level:s=(()=>e.levels.values[t]),log:a=(e=>e)}=o;e._serialize&&p(n,e._serialize,e.serializers,e._stdErrSerialize);const u=n.slice();let l=u[0];const c={};i&&(c.time=i),c.level=s(t,e.levels.values[t]);let d=1+(0|e._childLevel);if(d<1&&(d=1),null!==l&&"object"==typeof l){for(;d--&&"object"==typeof u[0];)Object.assign(c,u.shift());l=u.length?r(u.shift(),u):void 0}else"string"==typeof l&&(l=r(u.shift(),u));return void 0!==l&&(c.msg=l),a(c)}(this,o,l,a,t.formatters)):u.apply(c,l),t.transmit){const r=t.transmit.level||e._level,i=n.levels.values[r],u=n.levels.values[o];if(u<i)return;!function(e,t,n){const r=t.send,i=t.ts,o=t.methodLevel,s=t.methodValue,a=t.val,u=e._logEvent.bindings;p(n,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=i,e._logEvent.messages=n.filter((function(e){return-1===u.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=s,r(o,e._logEvent,a),e._logEvent=f(u)}(this,{ts:a,methodLevel:o,methodValue:u,transmitLevel:r,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:s(e._level,n)},l)}};var u}(e,t,n,o);const l=function(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[u];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}(e);0!==l.length&&(e[o]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(l,e[o]))}function p(e,t,n,r){for(const i in e)if(r&&e[i]instanceof Error)e[i]=d.stdSerializers.err(e[i]);else if("object"==typeof e[i]&&!Array.isArray(e[i]))for(const r in e[i])t&&t.indexOf(r)>-1&&r in n&&(e[i][r]=n[r](e[i][r]))}function f(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function g(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)void 0===t[n]&&(t[n]=e[n]);return t}function m(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?w:S}function b(){return{}}function y(e){return e}function v(){}function w(){return!1}function S(){return Date.now()}d.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},d.stdSerializers=o,d.stdTimeFunctions=Object.assign({},{nullTime:w,epochTime:S,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),e.exports.default=d,e.exports.pino=d}},__webpack_module_cache__={},leafPrototypes,getProto,inProgress,dataWebpackPrefix;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.m=__webpack_modules__,__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var n=Object.create(null);__webpack_require__.r(n);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var i=2&t&&e;"object"==typeof i&&!~leafPrototypes.indexOf(i);i=getProto(i))Object.getOwnPropertyNames(i).forEach((t=>r[t]=()=>e[t]));return r.default=()=>e,__webpack_require__.d(n,r),n},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce(((t,n)=>(__webpack_require__.f[n](e,t),t)),[])),__webpack_require__.u=e=>e+".index.js",__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),inProgress={},dataWebpackPrefix="Uneeq:",__webpack_require__.l=(e,t,n,r)=>{if(inProgress[e])inProgress[e].push(t);else{var i,o;if(void 0!==n)for(var s=document.getElementsByTagName("script"),a=0;a<s.length;a++){var u=s[a];if(u.getAttribute("src")==e||u.getAttribute("data-webpack")==dataWebpackPrefix+n){i=u;break}}i||(o=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,__webpack_require__.nc&&i.setAttribute("nonce",__webpack_require__.nc),i.setAttribute("data-webpack",dataWebpackPrefix+n),i.src=e),inProgress[e]=[t];var l=(t,n)=>{i.onerror=i.onload=null,clearTimeout(c);var r=inProgress[e];if(delete inProgress[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach((e=>e(n))),t)return t(n)},c=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),o&&document.head.appendChild(i)}},__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var r=n.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=n[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})(),(()=>{var e={792:0};__webpack_require__.f.j=(t,n)=>{var r=__webpack_require__.o(e,t)?e[t]:void 0;if(0!==r)if(r)n.push(r[2]);else{var i=new Promise(((n,i)=>r=e[t]=[n,i]));n.push(r[2]=i);var o=__webpack_require__.p+__webpack_require__.u(t),s=new Error;__webpack_require__.l(o,(n=>{if(__webpack_require__.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var i=n&&("load"===n.type?"missing":n.type),o=n&&n.target&&n.target.src;s.message="Loading chunk "+t+" failed.\n("+i+": "+o+")",s.name="ChunkLoadError",s.type=i,s.request=o,r[1](s)}}),"chunk-"+t,t)}};var t=(t,n)=>{var r,i,[o,s,a]=n,u=0;if(o.some((t=>0!==e[t]))){for(r in s)__webpack_require__.o(s,r)&&(__webpack_require__.m[r]=s[r]);a&&a(__webpack_require__)}for(t&&t(n);u<o.length;u++)i=o[u],__webpack_require__.o(e,i)&&e[i]&&e[i][0](),e[i]=0},n=Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})();var __webpack_exports__={};return(()=>{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{AvatarAnswerMessage:()=>In,AvatarStartedSpeakingMessage:()=>Ln,AvatarStoppedSpeakingMessage:()=>Fn,CameraAnchorDistance:()=>Ji,CameraAnchorHorizontal:()=>Qi,CustomMetadataUpdated:()=>Xn,DeviceErrorMessage:()=>kn,DigitalHumanMuted:()=>qn,DigitalHumanPlayedInMutedModeSuccess:()=>Hn,DigitalHumanUnmuted:()=>Wn,EnableMicrophoneUpdatedMessage:()=>Kn,LogLevel:()=>e,PromptRequestMessage:()=>Jn,PromptResultMessage:()=>Qn,SceneReadyMessage:()=>Yn,SessionBackendErrorMessage:()=>zn,SessionConnectingMessage:()=>Zn,SessionDisconnectedMessage:()=>er,SessionEndedMessage:()=>Gn,SessionErrorMessage:()=>Bn,SessionLiveMessage:()=>Un,SessionReconnectingFinishedMessage:()=>nr,SessionReconnectingMessage:()=>tr,SoftSwitchStartingMessage:()=>rr,SoftSwitchStoppingMessage:()=>ir,SpeechEventMessage:()=>Vn,SpeechRecognitionProvider:()=>ur,SpeechTranscriptionMessage:()=>Mn,Uneeq:()=>so,UneeqMessageType:()=>wn,UserStartedSpeakingMessage:()=>Dn,UserStoppedSpeakingMessage:()=>$n,VadInterruptionAllowedMessage:()=>Rn,VideoLayoutConfiguringMessage:()=>or,WaitingInQueueMessage:()=>Nn,WebRtcStatsMessage:()=>jn});var e,t=__webpack_require__(874),n=__webpack_require__.n(t);!function(e){e.Fatal="fatal",e.Error="error",e.Warn="warn",e.Info="info",e.Debug="debug",e.Trace="trace"}(e||(e={}));class r{static formatLogMessage(e,t){return"UneeQ SDK: "+e+" | "+JSON.stringify(t)}static fatal(e,...t){r.getLogger().fatal(r.formatLogMessage(e,t))}static error(e,...t){r.getLogger().error(r.formatLogMessage(e,t))}static warn(e,...t){r.getLogger().warn(r.formatLogMessage(e,t))}static info(e,...t){r.getLogger().info(r.formatLogMessage(e,t))}static debug(e,...t){r.getLogger().debug(r.formatLogMessage(e,t))}static trace(e,...t){r.getLogger().trace(r.formatLogMessage(e,t))}static getLogger(){return this.instance||(this.instance=n()({level:e.Info})),this.instance}static setLevel(t){Object.values(e).includes(t)?this.instance=n()({level:t}):this.instance=n()({level:e.Info})}static serialiseError(e){return JSON.stringify(e,Object.getOwnPropertyNames(e))}}var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)};function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function s(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function u(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function l(e){return"function"==typeof e}function c(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var d=c((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function h(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var p=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var c=s(o),h=c.next();!h.done;h=c.next())h.value.remove(this)}catch(t){e={error:t}}finally{try{h&&!h.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else o.remove(this);var p=this.initialTeardown;if(l(p))try{p()}catch(e){i=e instanceof d?e.errors:[e]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var g=s(f),b=g.next();!b.done;b=g.next()){var y=b.value;try{m(y)}catch(e){i=null!=i?i:[],e instanceof d?i=u(u([],a(i)),a(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{b&&!b.done&&(r=g.return)&&r.call(g)}finally{if(n)throw n.error}}}if(i)throw new d(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)m(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&h(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&h(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),f=p.EMPTY;function g(e){return e instanceof p||e&&"closed"in e&&l(e.remove)&&l(e.add)&&l(e.unsubscribe)}function m(e){l(e)?e():e.unsubscribe()}var b=null,y=null,v=void 0,w=!1,S=!1,_={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=_.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,u([e,t],a(n))):setTimeout.apply(void 0,u([e,t],a(n)))},clearTimeout:function(e){var t=_.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function T(){}var x=E("C",void 0,void 0);function E(e,t,n){return{kind:e,value:t,error:n}}var C=null;function P(e){if(w){var t=!C;if(t&&(C={errorThrown:!1,error:null}),e(),t){var n=C,r=n.errorThrown,i=n.error;if(C=null,r)throw i}}else e()}var O=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,g(t)&&t.add(n)):n.destination=$,n}return o(t,e),t.create=function(e,t,n){return new M(e,t,n)},t.prototype.next=function(e){this.isStopped?D(function(e){return E("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?D(E("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?D(x,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(p),A=Function.prototype.bind;function k(e,t){return A.call(e,t)}var I=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){R(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){R(e)}else R(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){R(e)}},e}(),M=function(e){function t(t,n,r){var i,o,s=e.call(this)||this;return l(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:s&&S?((o=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&k(t.next,o),error:t.error&&k(t.error,o),complete:t.complete&&k(t.complete,o)}):i=t,s.destination=new I(i),s}return o(t,e),t}(O);function R(e){var t;w?(t=e,w&&C&&(C.errorThrown=!0,C.error=t)):function(e){_.setTimeout((function(){if(!b)throw e;b(e)}))}(e)}function D(e,t){var n=y;n&&_.setTimeout((function(){return n(e,t)}))}var $={closed:!0,next:T,error:function(e){throw e},complete:T},L="function"==typeof Symbol&&Symbol.observable||"@@observable";function F(e){return e}var U=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,i=this,o=(r=e)&&r instanceof O||function(e){return e&&l(e.next)&&l(e.error)&&l(e.complete)}(r)&&g(r)?e:new M(e,t,n);return P((function(){var e=i,t=e.operator,n=e.source;o.add(t?t.call(o,n):n?i._subscribe(o):i._trySubscribe(o))})),o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=N(t))((function(t,r){var i=new M({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[L]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===(n=e).length?F:1===n.length?n[0]:function(e){return n.reduce((function(e,t){return t(e)}),e)})(this);var n},e.prototype.toPromise=function(e){var t=this;return new(e=N(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function N(e){var t;return null!==(t=null!=e?e:v)&&void 0!==t?t:Promise}var j,B,z,V=c((function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),G=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return o(t,e),t.prototype.lift=function(e){var t=new H(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new V},t.prototype.next=function(e){var t=this;P((function(){var n,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=s(t.currentObservers),o=i.next();!o.done;o=i.next())o.value.next(e)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}}))},t.prototype.error=function(e){var t=this;P((function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}}))},t.prototype.complete=function(){var e=this;P((function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}}))},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,i=n.isStopped,o=n.observers;return r||i?f:(this.currentObservers=null,o.push(e),new p((function(){t.currentObservers=null,h(o,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,i=t.isStopped;n?e.error(r):i&&e.complete()},t.prototype.asObservable=function(){var e=new U;return e.source=this,e},t.create=function(e,t){return new H(e,t)},t}(U),H=function(e){function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return o(t,e),t.prototype.next=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===n||n.call(t,e)},t.prototype.error=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===n||n.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,n;return null!==(n=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==n?n:f},t}(G),W={now:function(){return(W.delegate||Date).now()},delegate:void 0},q=function(e){function t(t,n,r){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===r&&(r=W);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return o(t,e),t.prototype.next=function(t){var n=this,r=n.isStopped,i=n._buffer,o=n._infiniteTimeWindow,s=n._timestampProvider,a=n._windowTime;r||(i.push(t),!o&&i.push(s.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this._infiniteTimeWindow,r=this._buffer.slice(),i=0;i<r.length&&!e.closed;i+=n?1:2)e.next(r[i]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,n=e._timestampProvider,r=e._buffer,i=e._infiniteTimeWindow,o=(i?1:2)*t;if(t<1/0&&o<r.length&&r.splice(0,r.length-o),!i){for(var s=n.now(),a=0,u=1;u<r.length&&r[u]<=s;u+=2)a=u;a&&r.splice(0,a+1)}},t}(G),K=__webpack_require__(963),X={d:(e,t)=>{for(var n in t)X.o(t,n)&&!X.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},J={};X.d(J,{Dz:()=>ft,g$:()=>Te,Lt:()=>we,Q9:()=>_e,qf:()=>Se,hV:()=>Tt,z$:()=>bn,J0:()=>vt,De:()=>ht,$C:()=>pt,al:()=>Me,_W:()=>Re,Gv:()=>Ke,m:()=>Xe,tz:()=>Ie,Nu:()=>yt,zg:()=>Dt,vp:()=>rt,vU:()=>it,wF:()=>Ve,rv:()=>mt,Nh:()=>bt,ss:()=>Mt,qW:()=>Je,QL:()=>qe,cf:()=>Lt,eM:()=>ze,Yd:()=>Q,Tk:()=>At,iM:()=>ue,qy:()=>Y,ce:()=>le,sK:()=>st,Ok:()=>ct,q5:()=>wt,g:()=>mn,xl:()=>Ne,I:()=>je,bx:()=>Be,dD:()=>tt,Ib:()=>ge,Az:()=>me,Iw:()=>be,qY:()=>ve,db:()=>ye,mR:()=>Qe,Tn:()=>ce,rV:()=>Ge,gh:()=>$e,Mi:()=>Le,j:()=>Fe,YB:()=>Ue,Yt:()=>We,i5:()=>He,x_:()=>ut,Am:()=>un,eR:()=>xe,r8:()=>De,u3:()=>$t,vd:()=>Ce,iV:()=>Oe,jZ:()=>Pe,SW:()=>ke,ZH:()=>Ae,Ni:()=>cn,lh:()=>Ee,ZP:()=>nt,bq:()=>de,$f:()=>hn,eu:()=>et,Ax:()=>Ze,Mc:()=>Ye});class Q{static GetStackTrace(){const e=new Error;let t="No Stack Available for this browser";return e.stack&&(t=e.stack.toString().replace(/Error/g,"")),t}static SetLoggerVerbosity(e){null!=this.verboseLogLevel&&(this.verboseLogLevel=e)}static Log(e,t,n){if(n>this.verboseLogLevel)return;const r=`Level: Log\nMsg: ${t}\nCaller: ${e}`;console.log(r)}static Info(e,t,n){if(n>this.verboseLogLevel)return;const r=`Level: Info\nMsg: ${t}`;console.info(r)}static Error(e,t){const n=`Level: Error\nMsg: ${t}\nCaller: ${e}`;console.error(n)}static Warning(e,t){const n=`Level: Warning\nCaller: ${e}\nMsg: ${t}`;console.warn(n)}}Q.verboseLogLevel=5,(z=j||(j={})).LIST_STREAMERS="listStreamers",z.SUBSCRIBE="subscribe",z.UNSUBSCRIBE="unsubscribe",z.ICE_CANDIDATE="iceCandidate",z.OFFER="offer",z.ANSWER="answer",z.DATACHANNELREQUEST="dataChannelRequest",z.SFURECVDATACHANNELREADY="peerDataChannelsReady",z.PONG="pong";class Y{sendFilter(e,t){return t}payload(){return Q.Log(Q.GetStackTrace(),"Sending => \n"+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class Z extends Y{constructor(){super(),this.type=j.LIST_STREAMERS}}class ee extends Y{constructor(e){super(),this.type=j.SUBSCRIBE,this.streamerId=e}}class te extends Y{constructor(){super(),this.type=j.UNSUBSCRIBE}}class ne extends Y{constructor(e){super(),this.type=j.PONG,this.time=e}}class re extends Y{constructor(e,t){super(),this.type=j.OFFER,this.minBitrate=0,this.maxBitrate=0,e&&(this.type=e.type,this.sdp=e.sdp,this.minBitrate=t.minBitrateBps,this.maxBitrate=t.maxBitrateBps)}sendFilter(e,t){if("minBitrate"!=e&&"maxBitrate"!=e||!(t<=0))return t}}class ie extends Y{constructor(e,t){super(),this.type=j.ANSWER,this.minBitrate=0,this.maxBitrate=0,e&&(this.type=e.type,this.sdp=e.sdp,this.minBitrate=t.minBitrateBps,this.maxBitrate=t.maxBitrateBps)}sendFilter(e,t){if("minBitrate"!=e&&"maxBitrate"!=e||!(t<=0))return t}}class oe extends Y{constructor(){super(),this.type=j.DATACHANNELREQUEST}}class se extends Y{constructor(){super(),this.type=j.SFURECVDATACHANNELREADY}}class ae{constructor(e){this.type=j.ICE_CANDIDATE,this.candidate=e}payload(){return Q.Log(Q.GetStackTrace(),"Sending => \n"+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}!function(e){e.CONFIG="config",e.STREAMER_LIST="streamerList",e.STREAMER_ID_CHANGED="streamerIDChanged",e.PLAYER_COUNT="playerCount",e.OFFER="offer",e.ANSWER="answer",e.ICE_CANDIDATE="iceCandidate",e.PEER_DATA_CHANNELS="peerDataChannels",e.PING="ping",e.WARNING="warning"}(B||(B={}));class ue{}class le extends ue{}class ce{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(e,t){this.FromUEMessageHandlers.set(e,t)}handleMessage(e,t){this.FromUEMessageHandlers.has(e)?this.FromUEMessageHandlers.get(e)(t):Q.Error(Q.GetStackTrace(),`Message type of ${e} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(e){e.signallingProtocol.addMessageHandler(B.PING,(t=>{const n=new ne((new Date).getTime()).payload();Q.Log(Q.GetStackTrace(),B.PING+": "+t,6),e.webSocket.send(n)})),e.signallingProtocol.addMessageHandler(B.CONFIG,(t=>{Q.Log(Q.GetStackTrace(),B.CONFIG,6);const n=JSON.parse(t);e.onConfig(n)})),e.signallingProtocol.addMessageHandler(B.STREAMER_LIST,(t=>{Q.Log(Q.GetStackTrace(),B.STREAMER_LIST,6);const n=JSON.parse(t);e.onStreamerList(n)})),e.signallingProtocol.addMessageHandler(B.STREAMER_ID_CHANGED,(t=>{Q.Log(Q.GetStackTrace(),B.STREAMER_ID_CHANGED,6);const n=JSON.parse(t);e.onStreamerIDChanged(n)})),e.signallingProtocol.addMessageHandler(B.PLAYER_COUNT,(t=>{Q.Log(Q.GetStackTrace(),B.PLAYER_COUNT,6);const n=JSON.parse(t);Q.Log(Q.GetStackTrace(),"Player Count: "+n.count,6),e.onPlayerCount(n)})),e.signallingProtocol.addMessageHandler(B.ANSWER,(t=>{Q.Log(Q.GetStackTrace(),B.ANSWER,6);const n=JSON.parse(t);e.onWebRtcAnswer(n)})),e.signallingProtocol.addMessageHandler(B.OFFER,(t=>{Q.Log(Q.GetStackTrace(),B.OFFER,6);const n=JSON.parse(t);e.onWebRtcOffer(n)})),e.signallingProtocol.addMessageHandler(B.ICE_CANDIDATE,(t=>{Q.Log(Q.GetStackTrace(),B.ICE_CANDIDATE,6);const n=JSON.parse(t);e.onIceCandidate(n.candidate)})),e.signallingProtocol.addMessageHandler(B.WARNING,(e=>{Q.Warning(Q.GetStackTrace(),`Warning received: ${e}`)})),e.signallingProtocol.addMessageHandler(B.PEER_DATA_CHANNELS,(t=>{Q.Log(Q.GetStackTrace(),B.PEER_DATA_CHANNELS,6);const n=JSON.parse(t);e.onWebRtcPeerDataChannels(n)}))}}class de{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new ce,ce.setupDefaultHandlers(this)}connect(e){Q.Log(Q.GetStackTrace(),e,6);try{return this.webSocket=new WebSocket(e),this.webSocket.onopen=e=>this.handleOnOpen(e),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=e=>this.handleOnClose(e),this.webSocket.onmessage=e=>this.handleOnMessage(e),this.webSocket.onmessagebinary=e=>this.handleOnMessageBinary(e),!0}catch(e){return Q.Error(e,e),!1}}handleOnMessageBinary(e){e&&e.data&&e.data.text().then((e=>{const t=new MessageEvent("messageFromBinary",{data:e});this.handleOnMessage(t)})).catch((e=>{Q.Error(Q.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${e}`)}))}handleOnMessage(e){if(e.data&&e.data instanceof Blob)return void this.handleOnMessageBinary(e);const t=JSON.parse(e.data);Q.Log(Q.GetStackTrace(),"received => \n"+JSON.stringify(JSON.parse(e.data),void 0,4),6),this.signallingProtocol.handleMessage(t.type,e.data)}handleOnOpen(e){Q.Log(Q.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){Q.Error(Q.GetStackTrace(),"WebSocket error")}handleOnClose(e){Q.Log(Q.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:e}))}requestStreamerList(){const e=new Z;this.webSocket.send(e.payload())}sendSubscribe(e){const t=new ee(e);this.webSocket.send(t.payload())}sendUnsubscribe(){const e=new te;this.webSocket.send(e.payload())}sendWebRtcOffer(e,t){const n=new re(e,t);this.webSocket.send(n.payload())}sendWebRtcAnswer(e,t){const n=new ie(e,t);this.webSocket.send(n.payload())}sendWebRtcDatachannelRequest(){const e=new oe;this.webSocket.send(e.payload())}sendSFURecvDataChannelReady(){const e=new se;this.webSocket.send(e.payload())}sendIceCandidate(e){if(Q.Log(Q.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const t=new ae(e);this.webSocket.send(t.payload())}}close(){var e;null===(e=this.webSocket)||void 0===e||e.close()}onConfig(e){}onStreamerList(e){}onStreamerIDChanged(e){}onIceCandidate(e){}onWebRtcAnswer(e){}onWebRtcOffer(e){}onWebRtcPeerDataChannels(e){}onPlayerCount(e){}}class he{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(Q.Log(Q.GetStackTrace(),"handleOnTrack "+JSON.stringify(e.streams),6),"probator"==e.track.id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&Q.Log(Q.GetStackTrace(),"Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState,6),"audio"!=e.track.kind)return"video"==e.track.kind&&t.srcObject!==e.streams[0]?(t.srcObject=e.streams[0],void Q.Log(Q.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(e.streams[0])}CreateAudioTrack(e){const t=this.videoElementProvider.getVideoElement();t.srcObject!=e&&t.srcObject&&t.srcObject!==e&&(this.audioElement.srcObject=e,Q.Log(Q.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class pe{constructor(e){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=e,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(e){const t=btoa(e.reduce(((e,t)=>e+String.fromCharCode(t)),""));this.imageElement.src="data:image/jpeg;base64,"+t}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(0!==this.freezeFrameWidth&&0!==this.freezeFrameHeight){let e=0,t=0,n=0,r=0;const i=this.rootDiv.clientWidth/this.rootDiv.clientHeight,o=this.freezeFrameWidth/this.freezeFrameHeight;i<o?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/o),n=Math.floor(.5*(this.rootDiv.clientHeight-t)),r=0):(e=Math.floor(this.rootDiv.clientHeight*o),t=this.rootDiv.clientHeight,n=0,r=Math.floor(.5*(this.rootDiv.clientWidth-e))),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=e+"px",this.imageElement.style.height=t+"px",this.imageElement.style.left=r+"px",this.imageElement.style.top=n+"px"}}}class fe{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new pe(e)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(e,t){this.freezeFrame.updateImageElementSource(e),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),t()}}processFreezeFrameMessage(e,t){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(e.slice(1,5).buffer).getInt32(0,!0);const n=e.slice(5);if(this.jpeg){const e=new Uint8Array(this.jpeg.length+n.length);e.set(this.jpeg,0),e.set(n,this.jpeg.length),this.jpeg=e}else this.jpeg=n,this.receiving=!0,Q.Log(Q.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,Q.Log(Q.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(Q.Error(Q.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class ge{constructor(e,t,n,r,i=(()=>{})){this.onChange=i,this.onChangeEmit=()=>{},this.id=e,this.description=n,this.label=t,this.value=r}set label(e){this._label=e,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(e){this._value=e,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class me extends ge{constructor(e,t,n,r,i,o=(()=>{})){super(e,t,n,r,o);const s=new URLSearchParams(window.location.search);if(i&&s.has(this.id)){const e=this.getUrlParamFlag();this.flag=e}else this.flag=r;this.useUrlParams=i}getUrlParamFlag(){const e=new URLSearchParams(window.location.search);return!!e.has(this.id)&&"false"!==e.get(this.id)&&"False"!==e.get(this.id)}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);!0===this.flag?e.set(this.id,"true"):e.set(this.id,"false"),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}}class be extends ge{constructor(e,t,n,r,i,o,s,a=(()=>{})){super(e,t,n,o,a),this._min=r,this._max=i;const u=new URLSearchParams(window.location.search);if(s&&u.has(this.id)){const e=Number.parseFloat(u.get(this.id));this.number=Number.isNaN(e)?o:e}else this.number=o;this.useUrlParams=s}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.number.toString()),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}set number(e){this.value=this.clamp(e)}get number(){return this.value}clamp(e){return null==this._min&&null==this._max?e:null==this._min?Math.min(this._max,e):null==this._max?Math.max(this._min,e):Math.max(Math.min(this._max,e),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(e){this.onChange=e}}class ye extends ge{constructor(e,t,n,r,i,o=(()=>{})){super(e,t,n,r,o);const s=new URLSearchParams(window.location.search);if(i&&s.has(this.id)){const e=this.getUrlParamText();this.text=e}else this.text=r;this.useUrlParams=i}getUrlParamText(){var e;const t=new URLSearchParams(window.location.search);return t.has(this.id)&&null!==(e=t.get(this.id))&&void 0!==e?e:""}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.text),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}get text(){return this.value}set text(e){this.value=e}}class ve extends ge{constructor(e,t,n,r,i,o,s=(()=>{})){super(e,t,n,r,s),this.options=i;const a=new URLSearchParams(window.location.search),u=o&&a.has(this.id)?this.getUrlParamText():r;this.selected=u,this.useUrlParams=o}getUrlParamText(){var e;const t=new URLSearchParams(window.location.search);return t.has(this.id)&&null!==(e=t.get(this.id))&&void 0!==e?e:""}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.selected),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}addOnChangedListener(e){this.onChange=e}get options(){return this._options}set options(e){this._options=e,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(e){let t=this.options.filter((t=>-1!==t.indexOf(e)));t.length?this.value=t[0]:(t=this.options.filter((t=>-1!==t.indexOf(e.split(" ")[0]))),t.length&&(this.value=t[0]))}}class we extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class Se extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class _e extends Event{constructor(){super("afkWarningDeactivate")}}class Te extends Event{constructor(){super("afkTimedOut")}}class xe extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class Ee extends Event{constructor(){super("webRtcSdp")}}class Ce extends Event{constructor(){super("webRtcAutoConnect")}}class Pe extends Event{constructor(){super("webRtcConnecting")}}class Oe extends Event{constructor(){super("webRtcConnected")}}class Ae extends Event{constructor(){super("webRtcFailed")}}class ke extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class Ie extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class Me extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class Re extends Event{constructor(e){super("dataChannelError"),this.data=e}}class De extends Event{constructor(){super("videoInitialized")}}class $e extends Event{constructor(){super("streamLoading")}}class Le extends Event{constructor(){super("streamConnect")}}class Fe extends Event{constructor(){super("streamDisconnect")}}class Ue extends Event{constructor(){super("streamReconnect")}}class Ne extends Event{constructor(e){super("playStreamError"),this.data=e}}class je extends Event{constructor(){super("playStream")}}class Be extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class ze extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class Ve extends Event{constructor(){super("hideFreezeFrame")}}class Ge extends Event{constructor(e){super("statsReceived"),this.data=e}}class He extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class We extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class qe extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class Ke extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class Xe extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class Je extends Event{constructor(e){super("initialSettings"),this.data=e}}class Qe extends Event{constructor(e){super("settingsChanged"),this.data=e}}class Ye extends Event{constructor(){super("xrSessionStarted")}}class Ze extends Event{constructor(){super("xrSessionEnded")}}class et extends Event{constructor(e){super("xrFrame"),this.data=e}}class tt extends Event{constructor(e){super("playerCount"),this.data=e}}class nt extends Event{constructor(){super("webRtcTCPRelayDetected")}}class rt extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class it{}it.AutoConnect="AutoConnect",it.AutoPlayVideo="AutoPlayVideo",it.AFKDetection="TimeoutIfIdle",it.BrowserSendOffer="OfferToReceive",it.HoveringMouseMode="HoveringMouse",it.ForceMonoAudio="ForceMonoAudio",it.ForceTURN="ForceTURN",it.FakeMouseWithTouches="FakeMouseWithTouches",it.IsQualityController="ControlsQuality",it.MatchViewportResolution="MatchViewportRes",it.StartVideoMuted="StartVideoMuted",it.SuppressBrowserKeys="SuppressBrowserKeys",it.UseMic="UseMic",it.KeyboardInput="KeyboardInput",it.MouseInput="MouseInput",it.TouchInput="TouchInput",it.GamepadInput="GamepadInput",it.XRControllerInput="XRControllerInput",it.WaitForStreamer="WaitForStreamer",it.HideUI="HideUI";const ot=e=>Object.getOwnPropertyNames(it).some((t=>it[t]===e));class st{}st.AFKTimeoutSecs="AFKTimeout",st.AFKCountdownSecs="AFKCountdown",st.MinQP="MinQP",st.MaxQP="MaxQP",st.WebRTCFPS="WebRTCFPS",st.WebRTCMinBitrate="WebRTCMinBitrate",st.WebRTCMaxBitrate="WebRTCMaxBitrate",st.MaxReconnectAttempts="MaxReconnectAttempts",st.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const at=e=>Object.getOwnPropertyNames(st).some((t=>st[t]===e));class ut{}ut.SignallingServerUrl="ss";const lt=e=>Object.getOwnPropertyNames(ut).some((t=>ut[t]===e));class ct{}ct.PreferredCodec="PreferredCodec",ct.StreamerId="StreamerId";const dt=e=>Object.getOwnPropertyNames(ct).some((t=>ct[t]===e));class ht{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:t,useUrlParams:n}=e;this._useUrlParams=!!n,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(e,t){this.textParameters.set(ut.SignallingServerUrl,new ye(ut.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&t.hasOwnProperty(ut.SignallingServerUrl)?t[ut.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(ct.StreamerId,new ve(ct.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&t.hasOwnProperty(ct.StreamerId)?t[ct.StreamerId]:"",[],e)),this.optionParameters.set(ct.PreferredCodec,new ve(ct.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",t&&t.hasOwnProperty(ct.PreferredCodec)?[t[ct.PreferredCodec]]:function(){const e=[];if(!RTCRtpReceiver.getCapabilities)return e.push("Only available on Chrome"),e;const t=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((n=>{const r=n.mimeType.split("/")[1]+" "+(n.sdpFmtpLine||"");null!==t.exec(r)&&e.push(r)})),e}(),e)),this.flags.set(it.AutoConnect,new me(it.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!t||!t.hasOwnProperty(it.AutoConnect))&&t[it.AutoConnect],e)),this.flags.set(it.AutoPlayVideo,new me(it.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!t||!t.hasOwnProperty(it.AutoPlayVideo)||t[it.AutoPlayVideo],e)),this.flags.set(it.BrowserSendOffer,new me(it.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!t||!t.hasOwnProperty(it.BrowserSendOffer))&&t[it.BrowserSendOffer],e)),this.flags.set(it.UseMic,new me(it.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!t.hasOwnProperty(it.UseMic))&&t[it.UseMic],e)),this.flags.set(it.StartVideoMuted,new me(it.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!t.hasOwnProperty(it.StartVideoMuted))&&t[it.StartVideoMuted],e)),this.flags.set(it.SuppressBrowserKeys,new me(it.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!t||!t.hasOwnProperty(it.SuppressBrowserKeys)||t[it.SuppressBrowserKeys],e)),this.flags.set(it.IsQualityController,new me(it.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!t.hasOwnProperty(it.IsQualityController)||t[it.IsQualityController],e)),this.flags.set(it.ForceMonoAudio,new me(it.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!t.hasOwnProperty(it.ForceMonoAudio))&&t[it.ForceMonoAudio],e)),this.flags.set(it.ForceTURN,new me(it.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!t.hasOwnProperty(it.ForceTURN))&&t[it.ForceTURN],e)),this.flags.set(it.AFKDetection,new me(it.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!t.hasOwnProperty(it.AFKDetection))&&t[it.AFKDetection],e)),this.flags.set(it.MatchViewportResolution,new me(it.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!t||!t.hasOwnProperty(it.MatchViewportResolution))&&t[it.MatchViewportResolution],e)),this.flags.set(it.HoveringMouseMode,new me(it.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!t||!t.hasOwnProperty(it.HoveringMouseMode))&&t[it.HoveringMouseMode],e,((e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`}))),this.flags.set(it.FakeMouseWithTouches,new me(it.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!t||!t.hasOwnProperty(it.FakeMouseWithTouches))&&t[it.FakeMouseWithTouches],e)),this.flags.set(it.KeyboardInput,new me(it.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!t.hasOwnProperty(it.KeyboardInput)||t[it.KeyboardInput],e)),this.flags.set(it.MouseInput,new me(it.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!t.hasOwnProperty(it.MouseInput)||t[it.MouseInput],e)),this.flags.set(it.TouchInput,new me(it.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!t.hasOwnProperty(it.TouchInput)||t[it.TouchInput],e)),this.flags.set(it.GamepadInput,new me(it.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!t.hasOwnProperty(it.GamepadInput)||t[it.GamepadInput],e)),this.flags.set(it.XRControllerInput,new me(it.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!t.hasOwnProperty(it.XRControllerInput)||t[it.XRControllerInput],e)),this.flags.set(it.WaitForStreamer,new me(it.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!t.hasOwnProperty(it.WaitForStreamer)||t[it.WaitForStreamer],e)),this.flags.set(it.HideUI,new me(it.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!t.hasOwnProperty(it.HideUI))&&t[it.HideUI],e)),this.numericParameters.set(st.AFKTimeoutSecs,new be(st.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,t&&t.hasOwnProperty(st.AFKTimeoutSecs)?t[st.AFKTimeoutSecs]:120,e)),this.numericParameters.set(st.AFKCountdownSecs,new be(st.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,e)),this.numericParameters.set(st.MaxReconnectAttempts,new be(st.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&t.hasOwnProperty(st.MaxReconnectAttempts)?t[st.MaxReconnectAttempts]:3,e)),this.numericParameters.set(st.MinQP,new be(st.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&t.hasOwnProperty(st.MinQP)?t[st.MinQP]:0,e)),this.numericParameters.set(st.MaxQP,new be(st.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&t.hasOwnProperty(st.MaxQP)?t[st.MaxQP]:51,e)),this.numericParameters.set(st.WebRTCFPS,new be(st.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&t.hasOwnProperty(st.WebRTCFPS)?t[st.WebRTCFPS]:60,e)),this.numericParameters.set(st.WebRTCMinBitrate,new be(st.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&t.hasOwnProperty(st.WebRTCMinBitrate)?t[st.WebRTCMinBitrate]:0,e)),this.numericParameters.set(st.WebRTCMaxBitrate,new be(st.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&t.hasOwnProperty(st.WebRTCMaxBitrate)?t[st.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(st.StreamerAutoJoinInterval,new be(st.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&t.hasOwnProperty(st.StreamerAutoJoinInterval)?t[st.StreamerAutoJoinInterval]:3e3,e))}_addOnNumericSettingChangedListener(e,t){this.numericParameters.has(e)&&this.numericParameters.get(e).addOnChangedListener(t)}_addOnOptionSettingChangedListener(e,t){this.optionParameters.has(e)&&this.optionParameters.get(e).addOnChangedListener(t)}getNumericSettingValue(e){if(this.numericParameters.has(e))return this.numericParameters.get(e).number;throw new Error(`There is no numeric setting with the id of ${e}`)}getTextSettingValue(e){if(this.textParameters.has(e))return this.textParameters.get(e).value;throw new Error(`There is no numeric setting with the id of ${e}`)}setNumericSetting(e,t){if(!this.numericParameters.has(e))throw new Error(`There is no numeric setting with the id of ${e}`);this.numericParameters.get(e).number=t}_addOnSettingChangedListener(e,t){this.flags.has(e)&&(this.flags.get(e).onChange=t)}_addOnTextSettingChangedListener(e,t){this.textParameters.has(e)&&(this.textParameters.get(e).onChange=t)}getSettingOption(e){return this.optionParameters.get(e)}isFlagEnabled(e){return this.flags.get(e).flag}setFlagEnabled(e,t){this.flags.has(e)?this.flags.get(e).flag=t:Q.Warning(Q.GetStackTrace(),`Cannot toggle flag called ${e} - it does not exist in the Config.flags map.`)}setTextSetting(e,t){this.textParameters.has(e)?this.textParameters.get(e).text=t:Q.Warning(Q.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(e,t){this.optionParameters.has(e)?this.optionParameters.get(e).options=t:Q.Warning(Q.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(this.optionParameters.has(e)){const n=this.optionParameters.get(e),r=n.options;r.includes(t)||(r.push(t),n.options=r),n.selected=t}else Q.Warning(Q.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(e,t){this.flags.has(e)?this.flags.get(e).label=t:Q.Warning(Q.GetStackTrace(),`Cannot set label for flag called ${e} - it does not exist in the Config.flags map.`)}setSettings(e){for(const t of Object.keys(e))ot(t)?this.setFlagEnabled(t,e[t]):at(t)?this.setNumericSetting(t,e[t]):lt(t)?this.setTextSetting(t,e[t]):dt(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){const e={};for(const[t,n]of this.flags.entries())e[t]=n.flag;for(const[t,n]of this.numericParameters.entries())e[t]=n.number;for(const[t,n]of this.textParameters.entries())e[t]=n.text;for(const[t,n]of this.optionParameters.entries())e[t]=n.selected;return e}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(e){for(const t of this.flags.keys()){const n=this.flags.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"flag",value:t,target:n})))}for(const t of this.numericParameters.keys()){const n=this.numericParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"number",value:t,target:n})))}for(const t of this.textParameters.keys()){const n=this.textParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"text",value:t,target:n})))}for(const t of this.optionParameters.keys()){const n=this.optionParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Qe({id:n.id,type:"option",value:t,target:n})))}}}var pt;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(pt||(pt={}));class ft{constructor(e,t,n){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=e,this.pixelStreaming=t,this.onDismissAfk=n,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new _e))}startAfkWarningTimer(){this.config.getNumericSettingValue(st.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(it.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(it.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(st.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new we({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(st.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new Se({countDown:this.countDown})),this.config.isFlagEnabled(it.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,0==this.countDown?(this.pixelStreaming.dispatchEvent(new Te),this.onAFKTimedOutCallback(),Q.Log(Q.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new Se({countDown:this.countDown}))}),1e3)}}class gt{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,n){this.peerConnection=e,this.label=t,this.datachannelOptions=n,null==n&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=e=>this.handleOnOpen(e),this.dataChannel.onclose=e=>this.handleOnClose(e),this.dataChannel.onmessage=e=>this.handleOnMessage(e),this.dataChannel.onerror=e=>this.handleOnError(e)}handleOnOpen(e){var t;Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) message: ${e}`,8)}handleOnError(e){var t;Q.Log(Q.GetStackTrace(),`Data Channel (${this.label}) error: ${e}`,7),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class mt{}class bt{}class yt{}class vt{}class wt{}class St{}class _t{}class Tt{constructor(){this.inboundVideoStats=new bt,this.inboundAudioStats=new mt,this.DataChannelStats=new yt,this.outBoundVideoStats=new wt,this.sessionStats=new St,this.streamStats=new _t,this.codecs=new Map}processStats(e){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,e.forEach((e=>{switch(e.type){case"candidate-pair":this.handleCandidatePair(e);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(e);break;case"data-channel":this.handleDataChannel(e);break;case"inbound-rtp":this.handleInBoundRTP(e);break;case"local-candidate":this.handleLocalCandidate(e);break;case"remote-candidate":this.handleRemoteCandidate(e);break;case"remote-outbound-rtp":this.handleRemoteOutBound(e);break;case"track":this.handleTrack(e);break;case"transport":this.handleTransport(e);break;case"stream":this.handleStream(e);break;default:Q.Error(Q.GetStackTrace(),"unhandled Stat Type"),Q.Log(Q.GetStackTrace(),e)}}))}handleStream(e){this.streamStats=e}handleCandidatePair(e){this.candidatePairs.push(e)}handleDataChannel(e){this.DataChannelStats.bytesReceived=e.bytesReceived,this.DataChannelStats.bytesSent=e.bytesSent,this.DataChannelStats.dataChannelIdentifier=e.dataChannelIdentifier,this.DataChannelStats.id=e.id,this.DataChannelStats.label=e.label,this.DataChannelStats.messagesReceived=e.messagesReceived,this.DataChannelStats.messagesSent=e.messagesSent,this.DataChannelStats.protocol=e.protocol,this.DataChannelStats.state=e.state,this.DataChannelStats.timestamp=e.timestamp}handleLocalCandidate(e){const t=new vt;t.label="local-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.candidateType=e.candidateType,t.id=e.id,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.localCandidates.push(t)}handleRemoteCandidate(e){const t=new vt;t.label="remote-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.id=e.id,t.candidateType=e.candidateType,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.remoteCandidates.push(t)}handleInBoundRTP(e){switch(e.kind){case"video":this.inboundVideoStats=e,null!=this.lastVideoStats&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=e,null!=this.lastAudioStats&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:Q.Log(Q.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(e){"video"===e.kind&&(this.outBoundVideoStats.bytesSent=e.bytesSent,this.outBoundVideoStats.id=e.id,this.outBoundVideoStats.localId=e.localId,this.outBoundVideoStats.packetsSent=e.packetsSent,this.outBoundVideoStats.remoteTimestamp=e.remoteTimestamp,this.outBoundVideoStats.timestamp=e.timestamp)}handleTrack(e){"track"!==e.type||"video_label"!==e.trackIdentifier&&"video"!==e.kind||(this.inboundVideoStats.framesDropped=e.framesDropped,this.inboundVideoStats.framesReceived=e.framesReceived,this.inboundVideoStats.frameHeight=e.frameHeight,this.inboundVideoStats.frameWidth=e.frameWidth)}handleTransport(e){this.transportStats=e}handleCodec(e){const t=e.id,n=`${e.mimeType.replace("video/","").replace("audio/","")}${e.sdpFmtpLine?` ${e.sdpFmtpLine}`:""}`;this.codecs.set(t,n)}handleSessionStatistics(e,t,n){const r=Date.now()-e;this.sessionStats.runTime=new Date(r).toISOString().substr(11,8).toString();const i=null===t?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=i,this.sessionStats.videoEncoderAvgQP=n}isNumber(e){return"number"==typeof e&&isFinite(e)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((e=>e.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((e=>e.selected),null)}}const xt=(Et={parseRtpParameters:()=>K.parseRtpParameters,splitSections:()=>K.splitSections},Ct={},X.d(Ct,Et),Ct);var Et,Ct;class Pt{static isVideoTransciever(e){return this.canTransceiverReceiveVideo(e)||this.canTransceiverSendVideo(e)}static canTransceiverReceiveVideo(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind}static canTransceiverSendVideo(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"video"===e.sender.track.kind}static isAudioTransciever(e){return this.canTransceiverReceiveAudio(e)||this.canTransceiverSendAudio(e)}static canTransceiverReceiveAudio(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind}static canTransceiverSendAudio(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"audio"===e.sender.track.kind}}var Ot,At,kt=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class It{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n)}createPeerConnection(e,t){this.config.isFlagEnabled(it.ForceTURN)&&(e.iceTransportPolicy="relay",Q.Log(Q.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(e),this.peerConnection.onsignalingstatechange=e=>this.handleSignalStateChange(e),this.peerConnection.oniceconnectionstatechange=e=>this.handleIceConnectionStateChange(e),this.peerConnection.onicegatheringstatechange=e=>this.handleIceGatheringStateChange(e),this.peerConnection.ontrack=e=>this.handleOnTrack(e),this.peerConnection.onicecandidate=e=>this.handleIceCandidate(e),this.peerConnection.ondatachannel=e=>this.handleDataChannel(e),this.aggregatedStats=new Tt,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return kt(this,void 0,void 0,(function*(){Q.Log(Q.GetStackTrace(),"Create Offer",6);const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,r="https:"===location.protocol;let i=t.isFlagEnabled(it.UseMic);!i||n||r||(i=!1,Q.Error(Q.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),Q.Error(Q.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(i).finally((()=>{var t;null===(t=this.peerConnection)||void 0===t||t.createOffer(e).then((e=>{var t;this.showTextOverlayConnecting(),e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t||t.setLocalDescription(e),this.onSendWebRTCOffer(e)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(e,t){var n;return kt(this,void 0,void 0,(function*(){Q.Log(Q.GetStackTrace(),"Receive Offer",6),null===(n=this.peerConnection)||void 0===n||n.setRemoteDescription(e).then((()=>{const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,r="https:"===location.protocol;let i=t.isFlagEnabled(it.UseMic);!i||n||r||(i=!1,Q.Error(Q.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),Q.Error(Q.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(ct.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(i).finally((()=>{var e;null===(e=this.peerConnection)||void 0===e||e.createAnswer().then((e=>{var t;return e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t?void 0:t.setLocalDescription(e)})).then((()=>{var e;this.onSendWebRTCAnswer(null===(e=this.peerConnection)||void 0===e?void 0:e.currentLocalDescription)})).catch((()=>{Q.Error(Q.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(ct.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){var e;null===(e=this.peerConnection)||void 0===e||e.getStats(null).then((e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(ct.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(e,t){let n=e.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,"$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r\n"),r="maxaveragebitrate=510000;";return t&&(r+="sprop-maxcapturerate=48000;"),r+=this.config.isFlagEnabled(it.ForceMonoAudio)?"stereo=0;":"stereo=1;",r+="useinbandfec=1",n=n.replace("useinbandfec=1",r),n}handleOnIce(e){var t;Q.Log(Q.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(it.ForceTURN)&&e.candidate.indexOf("relay")<0?Q.Info(Q.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${e.type} | Protocol= ${e.protocol} | Address=${e.address} | Port=${e.port} |`,6):null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}handleSignalStateChange(e){Q.Log(Q.GetStackTrace(),"signaling state change: "+e,6)}handleIceConnectionStateChange(e){Q.Log(Q.GetStackTrace(),"ice connection state change: "+e,6),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){Q.Log(Q.GetStackTrace(),"ice gathering state change: "+JSON.stringify(e),6)}handleOnTrack(e){this.onTrack(e)}handleIceCandidate(e){this.onPeerIceCandidate(e)}handleDataChannel(e){this.onDataChannel(e)}onTrack(e){}onIceConnectionStateChange(e){}onPeerIceCandidate(e){}onDataChannel(e){}fuzzyIntersectUEAndBrowserCodecs(e){const t=new Array,n=this.parseAvailableCodecs(e),r=this.config.getSettingOption(ct.PreferredCodec).options;for(const e of n)if(r.includes(e))t.push(e);else{const n=e.split(" ")[0];for(const e of r)if(e.includes(n)){t.push(e);break}}return t}setupTransceiversAsync(e){var t,n,r,i,o,s,a,u,l,c,d,h;return kt(this,void 0,void 0,(function*(){let p=!1;for(const e of null!==(n=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==n?n:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind){p=!0;break}if(p||null===(r=this.peerConnection)||void 0===r||r.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&""!=this.preferredCodec)for(const e of null!==(o=null===(i=this.peerConnection)||void 0===i?void 0:i.getTransceivers())&&void 0!==o?o:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind&&e.setCodecPreferences){const t=this.preferredCodec.split(" "),n={mimeType:"video/"+t[0],clockRate:9e4,sdpFmtpLine:t[1]?t[1]:""},r=[n];RTCRtpReceiver.getCapabilities("video").codecs.forEach((e=>{(e.mimeType!=n.mimeType||(null==e?void 0:e.sdpFmtpLine)!=(null==n?void 0:n.sdpFmtpLine))&&r.push(e)}));for(const e of r)void 0!==(null==e?void 0:e.sdpFmtpLine)&&""!==e.sdpFmtpLine||delete e.sdpFmtpLine;e.setCodecPreferences(r)}let f=!1;for(const e of null!==(a=null===(s=this.peerConnection)||void 0===s?void 0:s.getTransceivers())&&void 0!==a?a:[])if(e&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind){f=!0;break}if(e){const e={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},t=yield navigator.mediaDevices.getUserMedia(e);if(t)if(f){for(const e of null!==(c=null===(l=this.peerConnection)||void 0===l?void 0:l.getTransceivers())&&void 0!==c?c:[])if(Pt.canTransceiverReceiveAudio(e))for(const n of t.getTracks())n.kind&&"audio"==n.kind&&(e.sender.replaceTrack(n),e.direction="sendrecv")}else for(const e of t.getTracks())e.kind&&"audio"==e.kind&&(null===(d=this.peerConnection)||void 0===d||d.addTransceiver(e,{direction:"sendrecv"}));else f||null===(h=this.peerConnection)||void 0===h||h.addTransceiver("audio",{direction:"recvonly"})}else f||null===(u=this.peerConnection)||void 0===u||u.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(e){}onSendWebRTCOffer(e){}onSendWebRTCAnswer(e){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(e){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const t=[],n=(0,xt.splitSections)(e.sdp);return n.shift(),n.forEach((e=>{const{codecs:n}=(0,xt.parseRtpParameters)(e),r=/(VP\d|H26\d|AV1).*/;n.forEach((e=>{const n=e.name+" "+Object.keys(e.parameters||{}).map((t=>t+"="+e.parameters[t])).join(";");if(null!==r.exec(n)){"VP9"==e.name&&(e.parameters={"profile-id":"0"});const n=e.name+" "+Object.keys(e.parameters||{}).map((t=>t+"="+e.parameters[t])).join(";");t.push(n)}}))})),t}}class Mt{constructor(){this.PixelStreamingSettings=new Rt,this.EncoderSettings=new Dt,this.WebRTCSettings=new $t}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Rt{}class Dt{}class $t{}class Lt{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(e){0==this.frameDisplayDeltaTimeMs&&(this.frameDisplayDeltaTimeMs=Math.round(e))}processFields(){null!=this.EncodeMs||null==this.PreEncodeTimeMs&&null==this.PostEncodeTimeMs||(Q.Log(Q.GetStackTrace(),`Setting Encode Ms \n ${this.PostEncodeTimeMs} \n ${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),null!=this.CaptureToSendMs||null==this.PreCaptureTimeMs&&null==this.PostCaptureTimeMs||(Q.Log(Q.GetStackTrace(),`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class Ft{static setExtensionFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.size=0,t.data=[],t.timestampStart=(new Date).getTime(),Q.Log(Q.GetStackTrace(),"Received first chunk of file",6));const n=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),n,6),t.extension=n}static setMimeTypeFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.size=0,t.data=[],t.timestampStart=(new Date).getTime(),Q.Log(Q.GetStackTrace(),"Received first chunk of file",6));const n=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),n,6),t.mimetype=n}static setContentsFromBytes(e,t){if(!t.receiving)return;t.size=Math.ceil(new DataView(e.slice(1,5).buffer).getInt32(0,!0)/16379);const n=e.slice(5);if(t.data.push(n),Q.Log(Q.GetStackTrace(),`Received file chunk: ${t.data.length}/${t.size}`,6),t.data.length===t.size){t.receiving=!1,t.valid=!0,Q.Log(Q.GetStackTrace(),"Received complete file",6);const e=(new Date).getTime()-t.timestampStart,n=Math.round(16*t.size*1024/e);Q.Log(Q.GetStackTrace(),`Average transfer bitrate: ${n}kb/s over ${e/1e3} seconds`,6);const r=new Blob(t.data,{type:t.mimetype}),i=document.createElement("a");i.setAttribute("href",URL.createObjectURL(r)),i.setAttribute("download",`transfer.${t.extension}`),document.body.append(i),i.remove()}else t.data.length>t.size&&(t.receiving=!1,Q.Error(Q.GetStackTrace(),`Received bigger file than advertised: ${t.data.length}/${t.size}`))}}class Ut{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.size=0,this.data=[],this.valid=!1}}class Nt{}Nt.mainButton=0,Nt.auxiliaryButton=1,Nt.secondaryButton=2,Nt.fourthButton=3,Nt.fifthButton=4;class jt{}jt.primaryButton=1,jt.secondaryButton=2,jt.auxiliaryButton=4,jt.fourthButton=8,jt.fifthButton=16;class Bt{constructor(){this.unregisterCallbacks=[]}addUnregisterCallback(e){this.unregisterCallbacks.push(e)}unregisterAll(){for(const e of this.unregisterCallbacks)e();this.unregisterCallbacks=[]}}class zt{constructor(e,t,n){this.touchEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n;const r=e=>this.onTouchStart(e),i=e=>this.onTouchEnd(e),o=e=>this.onTouchMove(e);document.addEventListener("touchstart",r,{passive:!1}),document.addEventListener("touchend",i,{passive:!1}),document.addEventListener("touchmove",o,{passive:!1}),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchstart",r))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchend",i))),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",o)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}setVideoElementParentClientRect(e){this.videoElementParentClientRect=e}onTouchStart(e){if(this.videoElementProvider.isVideoReady()&&e.target===this.videoElementProvider.getVideoElement()){if(null==this.fakeTouchFinger){const t=e.changedTouches[0];this.fakeTouchFinger=new Vt(t.identifier,t.clientX-this.videoElementParentClientRect.left,t.clientY-this.videoElementParentClientRect.top);const n=this.videoElementProvider.getVideoParentElement(),r=new MouseEvent("mouseenter",t);n.dispatchEvent(r);const i=this.coordinateConverter.normalizeAndQuantizeUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([Nt.mainButton,i.x,i.y])}e.preventDefault()}}onTouchEnd(e){if(!this.videoElementProvider.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.videoElementProvider.getVideoParentElement(),n=this.toStreamerMessagesProvider.toStreamerHandlers;for(let r=0;r<e.changedTouches.length;r++){const i=e.changedTouches[r];if(i.identifier===this.fakeTouchFinger.id){const e=i.clientX-this.videoElementParentClientRect.left,r=i.clientY-this.videoElementParentClientRect.top,o=this.coordinateConverter.normalizeAndQuantizeUnsigned(e,r);n.get("MouseUp")([Nt.mainButton,o.x,o.y]);const s=new MouseEvent("mouseleave",i);t.dispatchEvent(s),this.fakeTouchFinger=null;break}}e.preventDefault()}onTouchMove(e){if(!this.videoElementProvider.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.toStreamerMessagesProvider.toStreamerHandlers;for(let n=0;n<e.touches.length;n++){const r=e.touches[n];if(r.identifier===this.fakeTouchFinger.id){const e=r.clientX-this.videoElementParentClientRect.left,n=r.clientY-this.videoElementParentClientRect.top,i=this.coordinateConverter.normalizeAndQuantizeUnsigned(e,n),o=this.coordinateConverter.normalizeAndQuantizeSigned(e-this.fakeTouchFinger.x,n-this.fakeTouchFinger.y);t.get("MouseMove")([i.x,i.y,o.x,o.y]),this.fakeTouchFinger.x=e,this.fakeTouchFinger.y=n;break}}e.preventDefault()}}class Vt{constructor(e,t,n){this.id=e,this.x=t,this.y=n}}class Gt{}Gt.backSpace=8,Gt.shift=16,Gt.control=17,Gt.alt=18,Gt.rightShift=253,Gt.rightControl=254,Gt.rightAlt=255;class Ht{constructor(e,t,n){this.keyboardEventListenerTracker=new Bt,this.CodeToKeyCode={Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93},this.toStreamerMessagesProvider=e,this.config=t,this.activeKeysProvider=n}registerKeyBoardEvents(){const e=e=>this.handleOnCompositionEnd(e),t=e=>this.handleOnKeyDown(e),n=e=>this.handleOnKeyUp(e),r=e=>this.handleOnKeyPress(e);document.addEventListener("compositionend",e),document.addEventListener("keydown",t),document.addEventListener("keyup",n),document.addEventListener("keypress",r),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("compositionend",e))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keydown",t))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keyup",n))),this.keyboardEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("keypress",r)))}unregisterKeyBoardEvents(){this.keyboardEventListenerTracker.unregisterAll()}handleOnKeyDown(e){const t=this.getKeycode(e);t&&229!==t&&(Q.Log(Q.GetStackTrace(),`key down ${t}, repeat = ${e.repeat}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyDown")([this.getKeycode(e),e.repeat?1:0]),this.activeKeysProvider.getActiveKeys().push(t),t===Gt.backSpace&&document.dispatchEvent(new KeyboardEvent("keypress",{charCode:Gt.backSpace})),this.config.isFlagEnabled(it.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(t)&&e.preventDefault())}handleOnKeyUp(e){const t=this.getKeycode(e);t&&(Q.Log(Q.GetStackTrace(),`key up ${t}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyUp")([t]),this.config.isFlagEnabled(it.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(t)&&e.preventDefault())}handleOnKeyPress(e){if(!("charCode"in e))return void Q.Warning(Q.GetStackTrace(),"KeyboardEvent.charCode is deprecated in this browser, cannot send key press.");const t=e.charCode;Q.Log(Q.GetStackTrace(),`key press ${t}`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("KeyPress")([t])}handleOnCompositionEnd(e){e.data&&e.data.length&&e.data.split("").forEach((e=>{this.handleOnKeyDown(new KeyboardEvent("keydown",{keyCode:e.toUpperCase().charCodeAt(0),charCode:e.charCodeAt(0)})),this.handleOnKeyPress(new KeyboardEvent("keypress",{keyCode:e.toUpperCase().charCodeAt(0),charCode:e.charCodeAt(0)})),this.handleOnKeyUp(new KeyboardEvent("keyup",{keyCode:e.toUpperCase().charCodeAt(0),charCode:e.charCodeAt(0)}))}))}getKeycode(e){if(!("keyCode"in e)){const t=e;return t.code in this.CodeToKeyCode?this.CodeToKeyCode[t.code]:(Q.Warning(Q.GetStackTrace(),`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===Gt.shift&&"ShiftRight"===e.code?Gt.rightShift:e.keyCode===Gt.control&&"ControlRight"===e.code?Gt.rightControl:e.keyCode===Gt.alt&&"AltRight"===e.code?Gt.rightAlt:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||9===e}}class Wt{constructor(e,t,n){this.x=0,this.y=0,this.updateMouseMovePositionEvent=e=>{this.updateMouseMovePosition(e)},this.mouseEventListenerTracker=new Bt,this.videoElementProvider=e,this.mouseController=t,this.activeKeysProvider=n;const r=this.videoElementProvider.getVideoParentElement();this.x=r.getBoundingClientRect().width/2,this.y=r.getBoundingClientRect().height/2,this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y)}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}lockStateChange(){const e=this.videoElementProvider.getVideoParentElement(),t=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers;if(document.pointerLockElement===e||document.mozPointerLockElement===e)Q.Log(Q.GetStackTrace(),"Pointer locked",6),document.addEventListener("mousemove",this.updateMouseMovePositionEvent,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1)));else{Q.Log(Q.GetStackTrace(),"The pointer lock status is now unlocked",6),document.removeEventListener("mousemove",this.updateMouseMovePositionEvent,!1);let e=this.activeKeysProvider.getActiveKeys();const n=new Set(e),r=[];n.forEach((e=>{r[e]})),r.forEach((e=>{t.get("KeyUp")([e])})),e=[]}}updateMouseMovePosition(e){if(!this.videoElementProvider.isVideoReady())return;const t=this.mouseController.toStreamerMessagesProvider.toStreamerHandlers,n=this.videoElementProvider.getVideoParentElement().clientWidth,r=this.videoElementProvider.getVideoParentElement().clientHeight;this.x+=e.movementX,this.y+=e.movementY,this.x>n&&(this.x-=n),this.y>r&&(this.y-=r),this.x<0&&(this.x=n+this.x),this.y<0&&(this.y=r-this.y),this.coord=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(this.x,this.y);const i=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(e.movementX,e.movementY);t.get("MouseMove")([this.coord.x,this.coord.y,i.x,i.y])}handleMouseDown(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([e.button,this.coord.x,this.coord.y])}handleMouseUp(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([e.button,this.coord.x,this.coord.y])}handleMouseWheel(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,this.coord.x,this.coord.y])}handleMouseDouble(e){this.videoElementProvider.isVideoReady()&&this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([e.button,this.coord.x,this.coord.y])}handlePressMouseButtons(e){this.videoElementProvider.isVideoReady()&&this.mouseController.pressMouseButtons(e.buttons,this.x,this.y)}handleReleaseMouseButtons(e){this.videoElementProvider.isVideoReady()&&this.mouseController.releaseMouseButtons(e.buttons,this.x,this.y)}}class qt{constructor(e){this.mouseController=e}unregisterMouseEvents(){}updateMouseMovePosition(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),"MouseMove",6);const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY),n=this.mouseController.coordinateConverter.normalizeAndQuantizeSigned(e.movementX,e.movementY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseMove")([t.x,t.y,n.x,n.y]),e.preventDefault()}handleMouseDown(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),"onMouse Down",6);const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([e.button,t.x,t.y]),e.preventDefault()}handleMouseUp(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),"onMouse Up",6);const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y]),e.preventDefault()}handleContextMenu(e){this.mouseController.videoElementProvider.isVideoReady()&&e.preventDefault()}handleMouseWheel(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,t.x,t.y]),e.preventDefault()}handleMouseDouble(e){if(!this.mouseController.videoElementProvider.isVideoReady())return;const t=this.mouseController.coordinateConverter.normalizeAndQuantizeUnsigned(e.offsetX,e.offsetY);this.mouseController.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDouble")([e.button,t.x,t.y])}handlePressMouseButtons(e){this.mouseController.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"onMouse press",6),this.mouseController.pressMouseButtons(e.buttons,e.offsetX,e.offsetY))}handleReleaseMouseButtons(e){this.mouseController.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"onMouse release",6),this.mouseController.releaseMouseButtons(e.buttons,e.offsetX,e.offsetY))}}class Kt{constructor(e,t,n,r){this.mouseEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.coordinateConverter=n,this.videoElementProvider=t,this.activeKeysProvider=r,this.registerMouseEnterAndLeaveEvents()}unregisterMouseEvents(){this.mouseEventListenerTracker.unregisterAll()}registerLockedMouseEvents(e){const t=this.videoElementProvider.getVideoParentElement(),n=new Wt(this.videoElementProvider,e,this.activeKeysProvider);if(t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,t.requestPointerLock){const e=()=>{t.requestPointerLock()};t.addEventListener("click",e),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("click",e)))}const r=()=>n.lockStateChange();document.addEventListener("pointerlockchange",r,!1),document.addEventListener("mozpointerlockchange",r,!1),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("pointerlockchange",r,!1))),this.mouseEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("mozpointerlockchange",r,!1)));const i=e=>n.handleMouseDown(e),o=e=>n.handleMouseUp(e),s=e=>n.handleMouseWheel(e),a=e=>n.handleMouseDouble(e);t.addEventListener("mousedown",i),t.addEventListener("mouseup",o),t.addEventListener("wheel",s),t.addEventListener("dblclick",a),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mousedown",i))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mouseup",o))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("wheel",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("dblclick",a))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.unregisterMouseEvents())),this.mouseEventListenerTracker.addUnregisterCallback((()=>{!document.exitPointerLock||document.pointerLockElement!==t&&document.mozPointerLockElement!==t||document.exitPointerLock()}))}registerHoveringMouseEvents(e){const t=this.videoElementProvider.getVideoParentElement(),n=new qt(e),r=e=>n.updateMouseMovePosition(e),i=e=>n.handleMouseDown(e),o=e=>n.handleMouseUp(e),s=e=>n.handleContextMenu(e),a=e=>n.handleMouseWheel(e),u=e=>n.handleMouseDouble(e);t.addEventListener("mousemove",r),t.addEventListener("mousedown",i),t.addEventListener("mouseup",o),t.addEventListener("contextmenu",s),t.addEventListener("wheel",a),t.addEventListener("dblclick",u),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mousemove",r))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mousedown",i))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("mouseup",o))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("contextmenu",s))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("wheel",a))),this.mouseEventListenerTracker.addUnregisterCallback((()=>t.removeEventListener("dblclick",u))),this.mouseEventListenerTracker.addUnregisterCallback((()=>n.unregisterMouseEvents()))}registerMouseEnterAndLeaveEvents(){const e=this.videoElementProvider.getVideoParentElement(),t=e=>{this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"Mouse Entered",6),this.sendMouseEnter(),this.pressMouseButtons(e.buttons,e.x,e.y))},n=e=>{this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"Mouse Left",6),this.sendMouseLeave(),this.releaseMouseButtons(e.buttons,e.x,e.y))};e.addEventListener("mouseenter",t),e.addEventListener("mouseleave",n),this.mouseEventListenerTracker.addUnregisterCallback((()=>e.removeEventListener("mouseenter",t))),this.mouseEventListenerTracker.addUnregisterCallback((()=>e.removeEventListener("mouseleave",n)))}releaseMouseButtons(e,t,n){const r=this.coordinateConverter.normalizeAndQuantizeUnsigned(t,n);e&jt.primaryButton&&this.sendMouseUp(Nt.mainButton,r.x,r.y),e&jt.secondaryButton&&this.sendMouseUp(Nt.secondaryButton,r.x,r.y),e&jt.auxiliaryButton&&this.sendMouseUp(Nt.auxiliaryButton,r.x,r.y),e&jt.fourthButton&&this.sendMouseUp(Nt.fourthButton,r.x,r.y),e&jt.fifthButton&&this.sendMouseUp(Nt.fifthButton,r.x,r.y)}pressMouseButtons(e,t,n){if(!this.videoElementProvider.isVideoReady())return;const r=this.coordinateConverter.normalizeAndQuantizeUnsigned(t,n);e&jt.primaryButton&&this.sendMouseDown(Nt.mainButton,r.x,r.y),e&jt.secondaryButton&&this.sendMouseDown(Nt.secondaryButton,r.x,r.y),e&jt.auxiliaryButton&&this.sendMouseDown(Nt.auxiliaryButton,r.x,r.y),e&jt.fourthButton&&this.sendMouseDown(Nt.fourthButton,r.x,r.y),e&jt.fifthButton&&this.sendMouseDown(Nt.fifthButton,r.x,r.y)}sendMouseEnter(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseEnter")()}sendMouseLeave(){this.videoElementProvider.isVideoReady()&&this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseLeave")()}sendMouseDown(e,t,n){this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),`mouse button ${e} down at (${t}, ${n})`,6),this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseDown")([e,t,n]))}sendMouseUp(e,t,n){if(!this.videoElementProvider.isVideoReady())return;Q.Log(Q.GetStackTrace(),`mouse button ${e} up at (${t}, ${n})`,6);const r=this.coordinateConverter.normalizeAndQuantizeUnsigned(t,n);this.toStreamerMessagesProvider.toStreamerHandlers.get("MouseUp")([e,r.x,r.y])}}class Xt{constructor(e,t,n){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.touchEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n,this.videoElementParent=t.getVideoElement();const r=e=>this.onTouchStart(e),i=e=>this.onTouchEnd(e),o=e=>this.onTouchMove(e);this.videoElementParent.addEventListener("touchstart",r),this.videoElementParent.addEventListener("touchend",i),this.videoElementParent.addEventListener("touchmove",o),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchstart",r))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchend",i))),this.touchEventListenerTracker.addUnregisterCallback((()=>this.videoElementParent.removeEventListener("touchmove",o))),Q.Log(Q.GetStackTrace(),"Touch Events Registered",6);const s=e=>{e.preventDefault()};document.addEventListener("touchmove",s),this.touchEventListenerTracker.addUnregisterCallback((()=>document.removeEventListener("touchmove",s)))}unregisterTouchEvents(){this.touchEventListenerTracker.unregisterAll()}rememberTouch(e){const t=this.fingers.pop();void 0===t&&Q.Log(Q.GetStackTrace(),"exhausted touch identifiers",6),this.fingerIds.set(e.identifier,t)}forgetTouch(e){this.fingers.push(this.fingerIds.get(e.identifier)),this.fingers.sort((function(e,t){return t-e})),this.fingerIds.delete(e.identifier)}onTouchStart(e){if(this.videoElementProvider.isVideoReady()){for(let t=0;t<e.changedTouches.length;t++)this.rememberTouch(e.changedTouches[t]);Q.Log(Q.GetStackTrace(),"touch start",6),this.emitTouchData("TouchStart",e.changedTouches),e.preventDefault()}}onTouchEnd(e){if(this.videoElementProvider.isVideoReady()){Q.Log(Q.GetStackTrace(),"touch end",6),this.emitTouchData("TouchEnd",e.changedTouches);for(let t=0;t<e.changedTouches.length;t++)this.forgetTouch(e.changedTouches[t]);e.preventDefault()}}onTouchMove(e){this.videoElementProvider.isVideoReady()&&(Q.Log(Q.GetStackTrace(),"touch move",6),this.emitTouchData("TouchMove",e.touches),e.preventDefault())}emitTouchData(e,t){if(!this.videoElementProvider.isVideoReady())return;const n=this.videoElementProvider.getVideoParentElement().getBoundingClientRect(),r=this.toStreamerMessagesProvider.toStreamerHandlers;for(let i=0;i<t.length;i++){const o=1,s=t[i],a=s.clientX-n.left,u=s.clientY-n.top;Q.Log(Q.GetStackTrace(),`F${this.fingerIds.get(s.identifier)}=(${a}, ${u})`,6);const l=this.coordinateConverter.normalizeAndQuantizeUnsigned(a,u);switch(e){case"TouchStart":r.get("TouchStart")([o,l.x,l.y,this.fingerIds.get(s.identifier),this.maxByteValue*(s.force>0?s.force:1),l.inRange?1:0]);break;case"TouchEnd":r.get("TouchEnd")([o,l.x,l.y,this.fingerIds.get(s.identifier),this.maxByteValue*s.force,l.inRange?1:0]);break;case"TouchMove":r.get("TouchMove")([o,l.x,l.y,this.fingerIds.get(s.identifier),this.maxByteValue*(s.force>0?s.force:1),l.inRange?1:0])}}}}class Jt{constructor(e){this.gamePadEventListenerTracker=new Bt,this.toStreamerMessagesProvider=e,this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window);const t=window;if(window.addEventListener("beforeunload",(e=>this.onBeforeUnload(e))),"GamepadEvent"in t){const e=e=>this.gamePadConnectHandler(e),t=e=>this.gamePadDisconnectHandler(e);window.addEventListener("gamepadconnected",e),window.addEventListener("gamepaddisconnected",t),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepadconnected",e))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("gamepaddisconnected",t)))}else if("WebKitGamepadEvent"in t){const e=e=>this.gamePadConnectHandler(e),t=e=>this.gamePadDisconnectHandler(e);window.addEventListener("webkitgamepadconnected",e),window.addEventListener("webkitgamepaddisconnected",t),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepadconnected",e))),this.gamePadEventListenerTracker.addUnregisterCallback((()=>window.removeEventListener("webkitgamepaddisconnected",t)))}if(this.controllers=[],navigator.getGamepads)for(const e of navigator.getGamepads())e&&this.gamePadConnectHandler(new GamepadEvent("gamepadconnected",{gamepad:e}))}unregisterGamePadEvents(){this.gamePadEventListenerTracker.unregisterAll();for(const e of this.controllers)void 0!==e.id&&this.onGamepadDisconnected(e.id);this.controllers=[],this.onGamepadConnected=()=>{},this.onGamepadDisconnected=()=>{}}gamePadConnectHandler(e){Q.Log(Q.GetStackTrace(),"Gamepad connect handler",6);const t=e.gamepad,n={currentState:t,prevState:t,id:void 0};this.controllers.push(n),this.controllers[t.index].currentState=t,this.controllers[t.index].prevState=t,Q.Log(Q.GetStackTrace(),"gamepad: "+t.id+" connected",6),window.requestAnimationFrame((()=>this.updateStatus())),this.onGamepadConnected()}gamePadDisconnectHandler(e){Q.Log(Q.GetStackTrace(),"Gamepad disconnect handler",6),Q.Log(Q.GetStackTrace(),"gamepad: "+e.gamepad.id+" disconnected",6);const t=this.controllers[e.gamepad.index];delete this.controllers[e.gamepad.index],this.controllers=this.controllers.filter((e=>void 0!==e)),this.onGamepadDisconnected(t.id)}scanGamePads(){const e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let t=0;t<e.length;t++)e[t]&&e[t].index in this.controllers&&(this.controllers[e[t].index].currentState=e[t])}updateStatus(){this.scanGamePads();const e=this.toStreamerMessagesProvider.toStreamerHandlers;for(const t of this.controllers){const n=void 0===t.id?this.controllers.indexOf(t):t.id,r=t.currentState;for(let r=0;r<t.currentState.buttons.length;r++){const i=t.currentState.buttons[r],o=t.prevState.buttons[r];i.pressed?r==Ot.LeftTrigger?e.get("GamepadAnalog")([n,5,i.value]):r==Ot.RightTrigger?e.get("GamepadAnalog")([n,6,i.value]):e.get("GamepadButtonPressed")([n,r,o.pressed?1:0]):!i.pressed&&o.pressed&&(r==Ot.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):r==Ot.RightTrigger?e.get("GamepadAnalog")([n,6,0]):e.get("GamepadButtonReleased")([n,r,0]))}for(let t=0;t<r.axes.length;t+=2){const i=parseFloat(r.axes[t].toFixed(4)),o=-parseFloat(r.axes[t+1].toFixed(4));e.get("GamepadAnalog")([n,t+1,i]),e.get("GamepadAnalog")([n,t+2,o])}this.controllers[n].prevState=r}this.controllers.length>0&&this.requestAnimationFrame((()=>this.updateStatus()))}onGamepadResponseReceived(e){for(const t of this.controllers)if(void 0===t.id){t.id=e;break}}onGamepadConnected(){}onGamepadDisconnected(e){}onBeforeUnload(e){for(const e of this.controllers)this.onGamepadDisconnected(e.id)}}!function(e){e[e.RightClusterBottomButton=0]="RightClusterBottomButton",e[e.RightClusterRightButton=1]="RightClusterRightButton",e[e.RightClusterLeftButton=2]="RightClusterLeftButton",e[e.RightClusterTopButton=3]="RightClusterTopButton",e[e.LeftShoulder=4]="LeftShoulder",e[e.RightShoulder=5]="RightShoulder",e[e.LeftTrigger=6]="LeftTrigger",e[e.RightTrigger=7]="RightTrigger",e[e.SelectOrBack=8]="SelectOrBack",e[e.StartOrForward=9]="StartOrForward",e[e.LeftAnalogPress=10]="LeftAnalogPress",e[e.RightAnalogPress=11]="RightAnalogPress",e[e.LeftClusterTopButton=12]="LeftClusterTopButton",e[e.LeftClusterBottomButton=13]="LeftClusterBottomButton",e[e.LeftClusterLeftButton=14]="LeftClusterLeftButton",e[e.LeftClusterRightButton=15]="LeftClusterRightButton",e[e.CentreButton=16]="CentreButton",e[e.LeftStickHorizontal=0]="LeftStickHorizontal",e[e.LeftStickVertical=1]="LeftStickVertical",e[e.RightStickHorizontal=2]="RightStickHorizontal",e[e.RightStickVertical=3]="RightStickVertical"}(Ot||(Ot={}));class Qt{constructor(e,t,n){this.activeKeys=new Yt,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){Q.Log(Q.GetStackTrace(),"Register Keyboard Events",7);const t=new Ht(this.toStreamerMessagesProvider,e,this.activeKeys);return t.registerKeyBoardEvents(),t}registerMouse(e){Q.Log(Q.GetStackTrace(),"Register Mouse Events",7);const t=new Kt(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys);switch(e){case pt.LockedMouse:t.registerLockedMouseEvents(t);break;case pt.HoveringMouse:t.registerHoveringMouseEvents(t);break;default:Q.Info(Q.GetStackTrace(),"unknown Control Scheme Type Defaulting to Locked Mouse Events"),t.registerLockedMouseEvents(t)}return t}registerTouch(e,t){if(Q.Log(Q.GetStackTrace(),"Registering Touch",6),e){const e=new zt(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter);return e.setVideoElementParentClientRect(t),e}return new Xt(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter)}registerGamePad(){return Q.Log(Q.GetStackTrace(),"Register Game Pad",7),new Jt(this.toStreamerMessagesProvider)}}class Yt{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Zt{constructor(e,t){this.lastTimeResized=(new Date).getTime(),this.videoElement=document.createElement("video"),this.config=t,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",e.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{null!=this.audioElement&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",(()=>this.resizePlayerStyle()),!0),window.addEventListener("orientationchange",(()=>this.onOrientationChange()))}setAudioElement(e){this.audioElement=e}play(){return this.videoElement.muted=this.config.isFlagEnabled(it.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(it.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return void 0!==this.videoElement.readyState&&this.videoElement.readyState>0}hasVideoSource(){return void 0!==this.videoElement.srcObject&&null!==this.videoElement.srcObject}getVideoElement(){return this.videoElement}getVideoParentElement(){return this.videoElement.parentElement}setVideoEnabled(e){this.videoElement.srcObject.getTracks().forEach((t=>t.enabled=e))}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout((()=>{this.resizePlayerStyle()}),500)}resizePlayerStyle(){const e=this.getVideoParentElement();e&&(this.updateVideoStreamSize(),e.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(it.MatchViewportResolution))if((new Date).getTime()-this.lastTimeResized>300){const e=this.getVideoParentElement();if(!e)return;this.onMatchViewportResolutionCallback(e.clientWidth,e.clientHeight),this.lastTimeResized=(new Date).getTime()}else Q.Log(Q.GetStackTrace(),"Resizing too often - skipping",6),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout((()=>this.updateVideoStreamSize()),100)}}class en{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(e,t,n){switch(e){case At.ToStreamer:this.toStreamerHandlers.set(t,n);break;case At.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:Q.Log(Q.GetStackTrace(),`Unknown message direction ${e}`)}}}!function(e){e[e.ToStreamer=0]="ToStreamer",e[e.FromStreamer=1]="FromStreamer"}(At||(At={}));class tn{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.Response",6);const t=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),t,6),this.responseEventListeners.forEach((e=>{e(t)}))}}class nn{constructor(e,t){this.dataChannelSender=e,this.toStreamerMessagesMapProvider=t}sendMessageToStreamer(e,t){void 0===t&&(t=[]);const n=this.toStreamerMessagesMapProvider.toStreamerMessages.get(e);if(void 0===n)return void Q.Error(Q.GetStackTrace(),`Attempted to send a message to the streamer with message type: ${e}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);if(n.structure&&t&&n.structure.length!==t.length)return void Q.Error(Q.GetStackTrace(),`Provided message data doesn't match expected layout. Expected [ ${n.structure.map((e=>{switch(e){case"uint8":case"uint16":case"int16":case"float":case"double":return"number";case"string":return"string"}})).toString()} ] but received [ ${t.map((e=>typeof e)).toString()} ]`);let r=0;const i=new TextEncoder;t.forEach(((e,t)=>{switch(n.structure[t]){case"uint8":r+=1;break;case"uint16":case"int16":r+=2;break;case"float":r+=4;break;case"double":r+=8;break;case"string":r+=2,r+=2*i.encode(e).length}}));const o=new DataView(new ArrayBuffer(r+1));o.setUint8(0,n.id);let s=1;t.forEach(((e,t)=>{switch(n.structure[t]){case"uint8":o.setUint8(s,e),s+=1;break;case"uint16":o.setUint16(s,e,!0),s+=2;break;case"int16":o.setInt16(s,e,!0),s+=2;break;case"float":o.setFloat32(s,e,!0),s+=4;break;case"double":o.setFloat64(s,e,!0),s+=8;break;case"string":o.setUint16(s,e.length,!0),s+=2;for(let t=0;t<e.length;t++)o.setUint16(s,e.charCodeAt(t),!0),s+=2}})),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(o.buffer):Q.Info(Q.GetStackTrace(),`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(o.buffer)}`)}}class rn{constructor(e){this.sendMessageController=e}SendRequestQualityControl(){this.sendMessageController.sendMessageToStreamer("RequestQualityControl")}SendMaxFpsRequest(){this.sendMessageController.sendMessageToStreamer("FpsRequest")}SendAverageBitrateRequest(){this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")}SendStartStreaming(){this.sendMessageController.sendMessageToStreamer("StartStreaming")}SendStopStreaming(){this.sendMessageController.sendMessageToStreamer("StopStreaming")}SendRequestInitialSettings(){this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")}}class on{constructor(e){this.dataChannelProvider=e}canSend(){return void 0!==this.dataChannelProvider.getDataChannelInstance().dataChannel&&"open"==this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState}sendData(e){const t=this.dataChannelProvider.getDataChannelInstance();"open"==t.dataChannel.readyState?(t.dataChannel.send(e),Q.Log(Q.GetStackTrace(),`Message Sent: ${new Uint8Array(e)}`,6),this.resetAfkWarningTimerOnDataSend()):Q.Error(Q.GetStackTrace(),`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}}class sn{constructor(e){this.videoElementProvider=e,this.normalizeAndQuantizeUnsignedFunc=()=>{throw new Error("Normalize and quantize unsigned, method not implemented.")},this.normalizeAndQuantizeSignedFunc=()=>{throw new Error("Normalize and unquantize signed, method not implemented.")},this.denormalizeAndUnquantizeUnsignedFunc=()=>{throw new Error("Denormalize and unquantize unsigned, method not implemented.")}}normalizeAndQuantizeUnsigned(e,t){return this.normalizeAndQuantizeUnsignedFunc(e,t)}unquantizeAndDenormalizeUnsigned(e,t){return this.denormalizeAndUnquantizeUnsignedFunc(e,t)}normalizeAndQuantizeSigned(e,t){return this.normalizeAndQuantizeSignedFunc(e,t)}setupNormalizeAndQuantize(){if(this.videoElementParent=this.videoElementProvider.getVideoParentElement(),this.videoElement=this.videoElementProvider.getVideoElement(),this.videoElementParent&&this.videoElement){const e=this.videoElementParent.clientWidth||1,t=this.videoElementParent.clientHeight||1,n=this.videoElement.videoWidth||1,r=t/e,i=(this.videoElement.videoHeight||1)/n;r>i?(Q.Log(Q.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio > videoAspectRatio",6),this.ratio=r/i,this.normalizeAndQuantizeUnsignedFunc=(e,t)=>this.normalizeAndQuantizeUnsignedPlayerBigger(e,t),this.normalizeAndQuantizeSignedFunc=(e,t)=>this.normalizeAndQuantizeSignedPlayerBigger(e,t),this.denormalizeAndUnquantizeUnsignedFunc=(e,t)=>this.denormalizeAndUnquantizeUnsignedPlayerBigger(e,t)):(Q.Log(Q.GetStackTrace(),"Setup Normalize and Quantize for playerAspectRatio <= videoAspectRatio",6),this.ratio=i/r,this.normalizeAndQuantizeUnsignedFunc=(e,t)=>this.normalizeAndQuantizeUnsignedPlayerSmaller(e,t),this.normalizeAndQuantizeSignedFunc=(e,t)=>this.normalizeAndQuantizeSignedPlayerSmaller(e,t),this.denormalizeAndUnquantizeUnsignedFunc=(e,t)=>this.denormalizeAndUnquantizeUnsignedPlayerSmaller(e,t))}}normalizeAndQuantizeUnsignedPlayerBigger(e,t){const n=e/this.videoElementParent.clientWidth,r=this.ratio*(t/this.videoElementParent.clientHeight-.5)+.5;return n<0||n>1||r<0||r>1?new an(!1,65535,65535):new an(!0,65536*n,65536*r)}denormalizeAndUnquantizeUnsignedPlayerBigger(e,t){const n=e/65536,r=(t/65536-.5)/this.ratio+.5;return new un(n*this.videoElementParent.clientWidth,r*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerBigger(e,t){const n=e/(.5*this.videoElementParent.clientWidth),r=this.ratio*t/(.5*this.videoElementParent.clientHeight);return new ln(32767*n,32767*r)}normalizeAndQuantizeUnsignedPlayerSmaller(e,t){const n=this.ratio*(e/this.videoElementParent.clientWidth-.5)+.5,r=t/this.videoElementParent.clientHeight;return n<0||n>1||r<0||r>1?new an(!1,65535,65535):new an(!0,65536*n,65536*r)}denormalizeAndUnquantizeUnsignedPlayerSmaller(e,t){const n=(e/65536-.5)/this.ratio+.5,r=t/65536;return new un(n*this.videoElementParent.clientWidth,r*this.videoElementParent.clientHeight)}normalizeAndQuantizeSignedPlayerSmaller(e,t){const n=this.ratio*e/(.5*this.videoElementParent.clientWidth),r=t/(.5*this.videoElementParent.clientHeight);return new ln(32767*n,32767*r)}}class an{constructor(e,t,n){this.inRange=e,this.x=t,this.y=n}}class un{constructor(e,t){this.x=e,this.y=t}}class ln{constructor(e,t){this.x=e,this.y=t}}class cn{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new tn,this.file=new Ut,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new ft(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity")},this.freezeFrameController=new fe(this.pixelStreaming.videoElementParent),this.videoPlayer=new Zt(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(e,t)=>{const n={"Resolution.Width":e,"Resolution.Height":t};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(n)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new he(this.videoPlayer),this.coordinateConverter=new sn(this.videoPlayer),this.sendrecvDataChannelController=new gt,this.recvDataChannelController=new gt,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new on(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new en,this.webSocketController=new de,this.webSocketController.onConfig=e=>this.handleOnConfigMessage(e),this.webSocketController.onStreamerList=e=>this.handleStreamerListMessage(e),this.webSocketController.onStreamerIDChanged=e=>this.handleStreamerIDChangedMessage(e),this.webSocketController.onPlayerCount=e=>{this.pixelStreaming._onPlayerCount(e.count)},this.webSocketController.onOpen.addEventListener("open",(()=>{this.config.isFlagEnabled(it.BrowserSendOffer)||this.webSocketController.requestStreamerList()})),this.webSocketController.onClose.addEventListener("close",(e=>{const t=this.shouldReconnect&&1001!=e.detail.code&&this.config.getNumericSettingValue(st.MaxReconnectAttempts)>0,n=this.disconnectMessage?this.disconnectMessage:e.detail.reason;this.pixelStreaming._onDisconnect(n,!t&&!this.isReconnecting),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&void 0!==this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),t&&setTimeout((()=>{this.isReconnecting=!0,this.reconnectAttempt++,this.tryReconnect(e.detail.reason)}),2e3)})),this.sendMessageController=new nn(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new rn(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new Qt(this.streamMessageController,this.videoPlayer,this.coordinateConverter),this.isUsingSFU=!1,this.isQualityController=!1,this.preferredCodec="",this.shouldReconnect=!0,this.isReconnecting=!1,this.reconnectAttempt=0,this.config._addOnOptionSettingChangedListener(ct.StreamerId,(e=>{""!==e&&(this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=e,this.webSocketController.sendSubscribe(e))})),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>{let e=this.config.getTextSettingValue(ut.SignallingServerUrl);return this.config.isFlagEnabled(it.BrowserSendOffer)&&(e+="?"+it.BrowserSendOffer+"=true"),e}}requestUnquantizedAndDenormalizeUnsigned(e,t){return this.coordinateConverter.unquantizeAndDenormalizeUnsigned(e,t)}handleOnMessage(e){const t=new Uint8Array(e.data);Q.Log(Q.GetStackTrace(),"Message incoming:"+t,6);const n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(At.FromStreamer,"QualityControlOwnership",(e=>this.onQualityControlOwnership(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"Response",(e=>this.responseController.onResponse(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"Command",(e=>{this.onCommand(e)})),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FreezeFrame",(e=>this.onFreezeFrameMessage(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"UnfreezeFrame",(()=>this.invalidateFreezeFrameAndEnableVideo())),this.streamMessageController.registerMessageHandler(At.FromStreamer,"VideoEncoderAvgQP",(e=>this.handleVideoEncoderAvgQP(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"LatencyTest",(e=>this.handleLatencyTestResult(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"DataChannelLatencyTest",(e=>this.handleDataChannelLatencyTestResponse(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"InitialSettings",(e=>this.handleInitialSettings(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FileExtension",(e=>this.onFileExtension(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FileMimeType",(e=>this.onFileMimeType(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"FileContents",(e=>this.onFileContents(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(At.FromStreamer,"InputControlOwnership",(e=>this.onInputControlOwnership(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"GamepadResponse",(e=>this.onGamepadResponse(e))),this.streamMessageController.registerMessageHandler(At.FromStreamer,"Protocol",(e=>this.onProtocolMessage(e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"IFrameRequest",(()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"RequestQualityControl",(()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"FpsRequest",(()=>this.sendMessageController.sendMessageToStreamer("FpsRequest"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"AverageBitrateRequest",(()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"StartStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StartStreaming"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"StopStreaming",(()=>this.sendMessageController.sendMessageToStreamer("StopStreaming"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"LatencyTest",(e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"RequestInitialSettings",(()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TestEcho",(()=>{})),this.streamMessageController.registerMessageHandler(At.ToStreamer,"UIInteraction",(e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"Command",(e=>this.sendMessageController.sendMessageToStreamer("Command",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TextboxEntry",(e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"KeyDown",(e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"KeyUp",(e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"KeyPress",(e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseEnter",(e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseLeave",(e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseDown",(e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseUp",(e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseMove",(e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseWheel",(e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"MouseDouble",(e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TouchStart",(e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TouchEnd",(e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"TouchMove",(e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadConnected",(()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected"))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadButtonPressed",(e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadButtonReleased",(e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadAnalog",(e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"GamepadDisconnected",(e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XREyeViews",(e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRHMDTransform",(e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRControllerTransform",(e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRSystem",(e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonTouched",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonTouchReleased",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonPressed",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRButtonReleased",(e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e))),this.streamMessageController.registerMessageHandler(At.ToStreamer,"XRAnalog",(e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)))}onCommand(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.Command",6);const t=new TextDecoder("utf-16").decode(e.slice(1));Q.Log(Q.GetStackTrace(),"Data Channel Command: "+t,6);const n=JSON.parse(t);"onScreenKeyboard"===n.command&&this.pixelStreaming._activateOnScreenKeyboard(n)}onProtocolMessage(e){try{const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||Q.Error(Q.GetStackTrace(),"Malformed protocol received. Ensure the protocol message contains a direction");const r=n.Direction;delete n.Direction,Q.Log(Q.GetStackTrace(),`Received new ${r==At.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach((e=>{const t=n[e];switch(r){case At.ToStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Q.Error(Q.GetStackTrace(),`ToStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);if("UIInteraction"===e||"Command"===e||"LatencyTest"===e)return;this.streamMessageController.toStreamerHandlers.get(e)?this.streamMessageController.toStreamerMessages.set(e,t):Q.Error(Q.GetStackTrace(),`There was no registered handler for "${e}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${e}", myHandler)`);break;case At.FromStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Q.Error(Q.GetStackTrace(),`FromStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(e)?this.streamMessageController.fromStreamerMessages.set(t.id,e):Q.Error(Q.GetStackTrace(),`There was no registered handler for "${t}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${e}", myHandler)`);break;default:Q.Error(Q.GetStackTrace(),`Unknown direction: ${r}`)}})),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(e){Q.Log(Q.GetStackTrace(),e)}}onInputControlOwnership(e){const t=new Uint8Array(e);Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.InputControlOwnership",6);const n=new Boolean(t[1]).valueOf();Q.Log(Q.GetStackTrace(),`Received input controller message - will your input control the stream: ${n}`),this.pixelStreaming._onInputControlOwnership(n)}onGamepadResponse(e){const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.gamePadController.onGamepadResponseReceived(n.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(e){e?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(e){this.webSocketController?(this.isReconnecting=!0,this.webSocketController.webSocket&&this.webSocketController.webSocket.readyState!=WebSocket.CLOSED?(this.closeSignalingServer(`${e} Restarting stream...`),setTimeout((()=>{this.tryReconnect(e)}),3e3)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):Q.Log(Q.GetStackTrace(),"The Web Socket Controller does not exist so this will not work right now.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new ze({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),!0===this.shouldShowPlayOverlay?(Q.Log(Q.GetStackTrace(),"showing play overlay"),this.resizePlayerStyle()):(Q.Log(Q.GetStackTrace(),"showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout((()=>{this.videoPlayer.setVideoEnabled(!1)}),this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6);const t=new Uint8Array(e);this.freezeFrameController.processFreezeFrameMessage(t,(()=>this.loadFreezeFrameOrShowPlayOverlay()))}invalidateFreezeFrameAndEnableVideo(){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.FreezeFrame",6),setTimeout((()=>{this.pixelStreaming.dispatchEvent(new Ve),this.freezeFrameController.hideFreezeFrame()}),this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(e){const t=new Uint8Array(e);Ft.setExtensionFromBytes(t,this.file)}onFileMimeType(e){const t=new Uint8Array(e);Ft.setMimeTypeFromBytes(t,this.file)}onFileContents(e){const t=new Uint8Array(e);Ft.setContentsFromBytes(t,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const e="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Ne({message:e})),Q.Error(Q.GetStackTrace(),e),void this.closeSignalingServer("Stream not initialized correctly")}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(it.TouchInput)),this.pixelStreaming.dispatchEvent(new je),this.streamController.audioElement.srcObject){const e=this.config.isFlagEnabled(it.StartVideoMuted);this.streamController.audioElement.muted=e,e?this.playVideo():this.streamController.audioElement.play().then((()=>{this.playVideo()})).catch((e=>{Q.Log(Q.GetStackTrace(),e),Q.Log(Q.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Be({reason:e}))}))}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else Q.Warning(Q.GetStackTrace(),"Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch((e=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),Q.Log(Q.GetStackTrace(),e),Q.Log(Q.GetStackTrace(),"Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Be({reason:e}))}))}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(it.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.shouldReconnect=!0,this.disconnectMessage=null;const e=this.signallingUrlBuilder();this.webSocketController.connect(e)}startSession(e){if(this.peerConfig=e,this.config.isFlagEnabled(it.ForceTURN)&&!this.checkTurnServerAvailability(e))return Q.Info(Q.GetStackTrace(),"No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.");this.peerConnectionController=new It(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=e=>this.handleVideoStats(e),this.peerConnectionController.onSendWebRTCOffer=e=>this.handleSendWebRTCOffer(e),this.peerConnectionController.onSendWebRTCAnswer=e=>this.handleSendWebRTCAnswer(e),this.peerConnectionController.onPeerIceCandidate=e=>this.handleSendIceCandidate(e),this.peerConnectionController.onDataChannel=e=>this.handleDataChannel(e),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let t=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!t&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),t=!0)},this.peerConnectionController.onTrack=e=>this.streamController.handleOnTrack(e),this.config.isFlagEnabled(it.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(e){if(!e.iceServers)return Q.Info(Q.GetStackTrace(),"A turn sever was not found"),!1;for(const t of e.iceServers)for(const e of t.urls)if(e.includes("turn"))return Q.Log(Q.GetStackTrace(),`A turn sever was found at ${e}`),!0;return Q.Info(Q.GetStackTrace(),"A turn sever was not found"),!1}handleOnConfigMessage(e){this.resizePlayerStyle(),this.startSession(e.peerConnectionOptions),this.webSocketController.onWebRtcAnswer=e=>this.handleWebRtcAnswer(e),this.webSocketController.onWebRtcOffer=e=>this.handleWebRtcOffer(e),this.webSocketController.onWebRtcPeerDataChannels=e=>this.handleWebRtcSFUPeerDatachannels(e),this.webSocketController.onIceCandidate=e=>this.handleIceCandidate(e)}handleStreamerListMessage(e){Q.Log(Q.GetStackTrace(),`Got streamer list ${e.ids}`,6);let t=null;var n=this.config.getSettingOption(ct.StreamerId);n.selected.toString().trim()&&(t=n.selected);const r=[...e.ids];r.unshift(""),this.config.setOptionSettingOptions(ct.StreamerId,r);let i=null;const o=this.config.isFlagEnabled(it.WaitForStreamer),s=this.config.getNumericSettingValue(st.MaxReconnectAttempts),a=this.config.getNumericSettingValue(st.StreamerAutoJoinInterval),u=this.config.useUrlParams,l=new URLSearchParams(window.location.search);u&&l.has(ct.StreamerId)?t=l.get(ct.StreamerId):this.subscribedStream&&(t=this.subscribedStream),t&&e.ids.includes(t)?i=t:t&&o||1!=e.ids.length||(i=e.ids[0]),i?(this.isReconnecting=!1,this.reconnectAttempt=0,this.config.setOptionSettingValue(ct.StreamerId,i)):o&&(this.reconnectAttempt<s?(this.isReconnecting=!0,this.reconnectAttempt++,setTimeout((()=>{this.webSocketController.requestStreamerList()}),a)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.shouldReconnect=!1)),this.pixelStreaming.dispatchEvent(new He({messageStreamerList:e,autoSelectedStreamerId:i,wantedStreamerId:t}))}handleStreamerIDChangedMessage(e){const t=e.newID;var n=this.config.getSettingOption(ct.StreamerId),r=n.onChange;n.onChange=()=>{};for(var i=n.options,o=0;o<i.length;++o)if(i[o]==this.subscribedStream){i[o]=t;break}n.options=i,n.selected=t,n.onChange=r,this.subscribedStream=e.newID,this.pixelStreaming.dispatchEvent(new We({newID:t}))}handleWebRtcAnswer(e){Q.Log(Q.GetStackTrace(),`Got answer sdp ${e.sdp}`,6);const t={sdp:e.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(t),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(e){Q.Log(Q.GetStackTrace(),`Got offer sdp ${e.sdp}`,6),this.isUsingSFU=!!e.sfu&&e.sfu,this.isUsingSFU&&(this.peerConnectionController.preferredCodec="");const t={sdp:e.sdp,type:"offer"};this.peerConnectionController.receiveOffer(t,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(e){const t={ordered:!0,negotiated:!0,id:e.sendStreamId},n=e.sendStreamId!=e.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,n?"send-datachannel":"datachannel",t),n){const t={ordered:!0,negotiated:!0,id:e.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",t),this.recvDataChannelController.handleOnOpen=()=>this.webSocketController.sendSFURecvDataChannelReady(),this.recvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}else this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&void 0!==this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval((()=>this.getStats()),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(it.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(it.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(it.GamepadInput))}handleIceCandidate(e){Q.Log(Q.GetStackTrace(),"Web RTC Controller: onWebRtcIce",6);const t=new RTCIceCandidate(e);this.peerConnectionController.handleOnIce(t)}handleSendIceCandidate(e){Q.Log(Q.GetStackTrace(),"OnIceCandidate",6),e.candidate&&e.candidate.candidate&&this.webSocketController.sendIceCandidate(e.candidate)}handleDataChannel(e){Q.Log(Q.GetStackTrace(),"Data channel created for us by browser as we are a receiving peer.",6),this.sendrecvDataChannelController.dataChannel=e.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handleSendWebRTCOffer(e){Q.Log(Q.GetStackTrace(),"Sending the offer to the Server",6);const t={minBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcOffer(e,t)}handleSendWebRTCAnswer(e){Q.Log(Q.GetStackTrace(),"Sending the answer to the Server",6);const t={minBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(st.WebRTCMaxBitrate)};this.webSocketController.sendWebRtcAnswer(e,t),this.isUsingSFU&&this.webSocketController.sendWebRtcDatachannelRequest()}setUpMouseAndFreezeFrame(){this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),this.coordinateConverter.setupNormalizeAndQuantize(),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(e){var t;this.locallyClosed=!0,this.shouldReconnect=!1,this.disconnectMessage=e,null===(t=this.webSocketController)||void 0===t||t.close()}closePeerConnection(){var e;null===(e=this.peerConnectionController)||void 0===e||e.close()}close(){this.closeSignalingServer(""),this.closePeerConnection()}getStats(){this.peerConnectionController.generateStats()}sendLatencyTest(){this.latencyStartTime=Date.now(),this.streamMessageController.toStreamerHandlers.get("LatencyTest")([JSON.stringify({StartTime:this.latencyStartTime})])}sendDataChannelLatencyTest(e){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(e)])}sendEncoderMinQP(e){Q.Log(Q.GetStackTrace(),`MinQP=${e}\n`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":e})])}sendEncoderMaxQP(e){Q.Log(Q.GetStackTrace(),`MaxQP=${e}\n`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":e})])}sendWebRTCMinBitrate(e){Q.Log(Q.GetStackTrace(),`WebRTC Min Bitrate=${e}`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":e})])}sendWebRTCMaxBitrate(e){Q.Log(Q.GetStackTrace(),`WebRTC Max Bitrate=${e}`,6),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":e})])}sendWebRTCFps(e){Q.Log(Q.GetStackTrace(),`WebRTC FPS=${e}`,6),null!=e&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":e})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":e})]))}sendShowFps(){Q.Log(Q.GetStackTrace(),"---- Sending show stat to UE ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){Q.Log(Q.GetStackTrace(),"---- Sending Request for an IFrame ----",6),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(e){Q.Log(Q.GetStackTrace(),"---- Sending custom UIInteraction message ----",6),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(e)])}emitCommand(e){Q.Log(Q.GetStackTrace(),"---- Sending custom Command message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(e)])}emitConsoleCommand(e){Q.Log(Q.GetStackTrace(),"---- Sending custom Command:ConsoleCommand message ----",6),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:e})])}sendRequestQualityControlOwnership(){Q.Log(Q.GetStackTrace(),"---- Sending Request to Control Quality ----",6),this.toStreamerMessagesController.SendRequestQualityControl()}handleLatencyTestResult(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.latencyTest",6);const t=new TextDecoder("utf-16").decode(e.slice(1)),n=new Lt;Object.assign(n,JSON.parse(t)),n.processFields(),n.testStartTimeMs=this.latencyStartTime,n.browserReceiptTimeMs=Date.now(),n.latencyExcludingDecode=~~(n.browserReceiptTimeMs-n.testStartTimeMs),n.testDuration=~~(n.TransmissionTimeMs-n.ReceiptTimeMs),n.networkLatency=~~(n.latencyExcludingDecode-n.testDuration),n.frameDisplayDeltaTimeMs&&n.browserReceiptTimeMs&&(n.endToEndLatency=(n.frameDisplayDeltaTimeMs,n.networkLatency,~~+n.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(n)}handleDataChannelLatencyTestResponse(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.dataChannelLatencyResponse",6);const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.pixelStreaming._onDataChannelLatencyTestResponse(n)}handleInitialSettings(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.InitialSettings",6);const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t),r=new Mt;n.Encoder&&(r.EncoderSettings=n.Encoder),n.WebRTC&&(r.WebRTCSettings=n.WebRTC),n.PixelStreaming&&(r.PixelStreamingSettings=n.PixelStreaming),n.ConfigOptions&&void 0!==n.ConfigOptions.DefaultToHover&&this.config.setFlagEnabled(it.HoveringMouseMode,!!n.ConfigOptions.DefaultToHover),r.ueCompatible(),Q.Log(Q.GetStackTrace(),t,6),this.pixelStreaming._onInitialSettings(r)}handleVideoEncoderAvgQP(e){Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.VideoEncoderAvgQP",6);const t=Number(new TextDecoder("utf-16").decode(e.slice(1)));this.setVideoEncoderAvgQP(t)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(e){const t=new Uint8Array(e);Q.Log(Q.GetStackTrace(),"DataChannelReceiveMessageType.QualityControlOwnership",6),this.isQualityController=new Boolean(t[1]).valueOf(),Q.Log(Q.GetStackTrace(),`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(e){this.pixelStreaming._onVideoStats(e)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(e){this.preferredCodec=e,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=e,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(e){this.videoAvgQp=e,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(e){var t;null===(t=this.keyboardController)||void 0===t||t.unregisterKeyBoardEvents(),e&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(e){var t;if(null===(t=this.mouseController)||void 0===t||t.unregisterMouseEvents(),e){const e=this.config.isFlagEnabled(it.HoveringMouseMode)?pt.HoveringMouse:pt.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(e)}}setTouchInputEnabled(e){var t;null===(t=this.touchController)||void 0===t||t.unregisterTouchEvents(),e&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(it.FakeMouseWithTouches),this.videoElementParentClientRect))}setGamePadInputEnabled(e){var t;null===(t=this.gamePadController)||void 0===t||t.unregisterGamePadEvents(),e&&(this.gamePadController=this.inputClassesFactory.registerGamePad(),this.gamePadController.onGamepadConnected=()=>{this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()},this.gamePadController.onGamepadDisconnected=e=>{this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e])})}registerDataChannelEventEmitters(e){e.onOpen=(e,t)=>this.pixelStreaming.dispatchEvent(new Ie({label:e,event:t})),e.onClose=(e,t)=>this.pixelStreaming.dispatchEvent(new Me({label:e,event:t})),e.onError=(e,t)=>this.pixelStreaming.dispatchEvent(new Re({label:e,event:t}))}registerMessageHandler(e,t,n){t===At.FromStreamer&&void 0===n&&Q.Warning(Q.GetStackTrace(),`Unable to register handler for ${e} as no handler was passed`),this.streamMessageController.registerMessageHandler(t,e,(r=>void 0===n&&t===At.ToStreamer?this.sendMessageController.sendMessageToStreamer(e,r):n(r)))}}class dn{constructor(e){this.toStreamerMessagesProvider=e,this.controllers=[]}static deepCopyGamepad(e){return JSON.parse(JSON.stringify({buttons:e.buttons.map((e=>JSON.parse(JSON.stringify({pressed:e.pressed,touched:e.touched,value:e.value})))),axes:e.axes}))}updateStatus(e,t,n){if(e.gamepad){const r=t.getPose(e.gripSpace,n);if(!r)return;let i=0;e.profiles.includes("htc-vive")?i=1:e.profiles.includes("oculus-touch")&&(i=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([i]);let o=2;switch(e.handedness){case"left":o=0;break;case"right":o=1}const s=r.transform.matrix,a=[];for(let e=0;e<16;e++)a[e]=new Float32Array([s[e]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],o]),void 0===this.controllers[o]&&(this.controllers[o]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[o].prevState=dn.deepCopyGamepad(e.gamepad)),this.controllers[o].currentState=dn.deepCopyGamepad(e.gamepad);const u=this.controllers[o],l=u.currentState,c=u.prevState;for(let e=0;e<l.buttons.length;e++){const t=l.buttons[e],n=c.buttons[e];if(t.pressed){let t=n.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([o,e,t])}else n.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([o,e,0]);if(t.touched){let t=n.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([o,e,t])}else n.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([o,e,0])}for(let e=0;e<l.axes.length;e++){let t=l.axes[e];t!=c.axes[e]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([o,e,t])}this.controllers[o].prevState=l}}}class hn{constructor(e){this.xrViewerPose=null,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.xrSession=null,this.webRtcController=e,this.xrGamepadController=new dn(this.webRtcController.streamMessageController),this.onSessionEnded=new EventTarget,this.onSessionStarted=new EventTarget,this.onFrame=new EventTarget}xrClicked(){if(this.xrSession)this.xrSession.end();else{if(!navigator.xr)return void Q.Error(Q.GetStackTrace(),"This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then((e=>{this.onXrSessionStarted(e)}))}}onXrSessionEnded(){Q.Log(Q.GetStackTrace(),"XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const e=document.createElement("canvas");this.gl=e.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const e=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(e,"\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n // varyings\n varying vec2 v_texCoord;\n\n void main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n // pass the texCoord to the fragment shader\n // The GPU will interpolate this value between points.\n v_texCoord = a_texCoord;\n }\n "),this.gl.compileShader(e);const t=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(t,"\n precision mediump float;\n\n // our texture\n uniform sampler2D u_image;\n\n // the texCoords passed in from the vertex shader.\n varying vec2 v_texCoord;\n\n void main() {\n gl_FragColor = texture2D(u_image, v_texCoord);\n }\n "),this.gl.compileShader(t);const n=this.gl.createProgram();this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),this.gl.useProgram(n),this.positionLocation=this.gl.getAttribLocation(n,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(n,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let e=this.webRtcController.videoPlayer.getVideoElement().videoHeight,t=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=e||this.prevVideoWidth!=t?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=e,this.prevVideoWidth=t}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(e){Q.Log(Q.GetStackTrace(),"XR Session started"),this.xrSession=e,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),e.requestReferenceSpace("local").then((t=>{if(this.xrRefSpace=t,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let t of this.xrSession.supportedFrameRates)90==t&&e.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))})),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}sendXRDataToUE(){if(null==this.leftView||null==this.rightView)return;const e=this.leftView.transform.matrix,t=this.leftView.projectionMatrix,n=this.rightView.transform.matrix,r=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([e[0],e[4],e[8],e[12],e[1],e[5],e[9],e[13],e[2],e[6],e[10],e[14],e[3],e[7],e[11],e[15],t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15],n[0],n[4],n[8],n[12],n[1],n[5],n[9],n[13],n[2],n[6],n[10],n[14],n[3],n[7],n[11],n[15],r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15]])}onXrFrame(e,t){if(this.xrViewerPose=t.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),null==this.leftView||null==this.rightView)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(it.XRControllerInput)&&this.xrSession.inputSources.forEach(((e,n,r)=>{this.xrGamepadController.updateStatus(e,t,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((e,t)=>this.onXrFrame(e,t))),this.onFrame.dispatchEvent(new et({time:e,frame:t}))}updateViews(){if(this.xrViewerPose)for(const e of this.xrViewerPose.views)"left"===e.eye?this.leftView=e:"right"===e.eye&&(this.rightView=e)}render(){if(!this.gl)return;const e=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e.framebuffer),this.gl.viewport(0,0,e.framebufferWidth,e.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(e){return"https:"!==location.protocol&&Q.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(e):new Promise((()=>!1))}}class pn{constructor(e){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(e)}unquantizeAndDenormalizeUnsigned(e,t){return null}createOnScreenKeyboardHelpers(e){this.hiddenInput||(this.hiddenInput=document.createElement("input"),this.hiddenInput.id="hiddenInput",this.hiddenInput.maxLength=0,this.hiddenInput.style.position="absolute",this.hiddenInput.style.left="-10%",this.hiddenInput.style.width="0px",this.hiddenInput.style.opacity="0",e.appendChild(this.hiddenInput)),this.editTextButton||(this.editTextButton=document.createElement("button"),this.editTextButton.id="editTextButton",this.editTextButton.innerHTML="edit text",e.appendChild(this.editTextButton),this.editTextButton.style.display="none",this.editTextButton.addEventListener("touchend",(e=>{this.hiddenInput.focus(),e.preventDefault()})))}showOnScreenKeyboard(e){if(e.showOnScreenKeyboard){this.editTextButton.style.display="default";const t=this.unquantizeAndDenormalizeUnsigned(e.x,e.y);this.editTextButton.style.top=t.y.toString()+"px",this.editTextButton.style.left=(t.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class fn{constructor(e){this.seq=e.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=e.Filler?e.Filler.length:0}update(e){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=e.ReceivedTimestamp,this.streamerSentTimestamp=e.SentTimestamp,this.responseFillerSize=e.Filler?e.Filler.length:0}}class gn{constructor(e,t){this.sink=e,this.callback=t,this.records=new Map,this.seq=0}start(e){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=e.duration?this.stop():this.sendRequest(e.requestSize,e.responseSize)}).bind(this),Math.floor(1e3/e.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const e=new Map(this.records);return{records:e,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((e,t)=>e+(t.playerReceivedTimestamp-t.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((e,t)=>e+(t.streamerReceivedTimestamp-t.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((e,t)=>e+(t.playerReceivedTimestamp-t.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let t="Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;\n";return e.forEach((e=>{t+=e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.streamerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.streamerSentTimestamp+";",t+="\n"})),t}}}isRunning(){return!!this.interval}receive(e){if(!this.isRunning())return;if(!e)return void Q.Error(Q.GetStackTrace(),"Undefined response from server");let t=this.records.get(e.Seq);t&&t.update(e)}sendRequest(e,t){let n=this.createRequest(e,t),r=new fn(n);this.records.set(r.seq,r),this.sink(n)}createRequest(e,t){return{Seq:this.seq++,FillResponseSize:t,Filler:e?"A".repeat(e):""}}}class mn{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,(null==t?void 0:t.videoElementParent)&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new rt,this.configureSettings(),this.setWebRtcPlayerController(new cn(this.config,this)),this.onScreenKeyboardHelper=new pn(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(e,t)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(e,t),this._activateOnScreenKeyboard=e=>this.onScreenKeyboardHelper.showOnScreenKeyboard(e),this._webXrController=new hn(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(e=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(it.IsQualityController,(e=>{!0!==e||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(it.AFKDetection,(e=>{this._webRtcController.setAfkEnabled(e)})),this.config._addOnSettingChangedListener(it.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(it.HoveringMouseMode,(e=>{this.config.setFlagLabel(it.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(it.MouseInput))})),this.config._addOnSettingChangedListener(it.KeyboardInput,(e=>{this._webRtcController.setKeyboardInputEnabled(e)})),this.config._addOnSettingChangedListener(it.MouseInput,(e=>{this._webRtcController.setMouseInputEnabled(e)})),this.config._addOnSettingChangedListener(it.FakeMouseWithTouches,(e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(it.TouchInput))})),this.config._addOnSettingChangedListener(it.TouchInput,(e=>{this._webRtcController.setTouchInputEnabled(e)})),this.config._addOnSettingChangedListener(it.GamepadInput,(e=>{this._webRtcController.setGamePadInputEnabled(e)})),this.config._addOnNumericSettingChangedListener(st.MinQP,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.MaxQP,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.WebRTCMinBitrate,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.WebRTCMaxBitrate,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(st.WebRTCFPS,(e=>{Q.Log(Q.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(e),Q.Log(Q.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(ct.PreferredCodec,(e=>{this._webRtcController&&this._webRtcController.setPreferredCodec(e)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(e){throw new Error("Method not implemented.")}_onInputControlOwnership(e){this._inputController=e}setWebRtcPlayerController(e){this._webRtcController=e,this._webRtcController.setPreferredCodec(this.config.getSettingOption(ct.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Le),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Ue),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Fe),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(it.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(e=!1){if(!this.config.isFlagEnabled("UseMic"))return e?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void Q.Warning(Q.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):Q.Info(Q.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(e){var t,n,r,i;for(const o of null!==(i=null===(r=null===(n=null===(t=this._webRtcController)||void 0===t?void 0:t.peerConnectionController)||void 0===n?void 0:n.peerConnection)||void 0===r?void 0:r.getTransceivers())&&void 0!==i?i:[])Pt.canTransceiverSendAudio(o)&&(o.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Ce)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new Ee)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new $e)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new ke({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new Pe)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Oe)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Ae)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new De),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new qe({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new Ke({response:e}))}_onVideoStats(e){this._videoStartTime&&void 0!==this._videoStartTime||(this._videoStartTime=Date.now()),e.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Ge({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new xe({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Je({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=null!==(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)&&void 0!==t&&t,!1===this.allowConsoleCommands&&Q.Info(Q.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const n=this.config.useUrlParams,r=new URLSearchParams(window.location.search);Q.Info(Q.GetStackTrace(),`using URL parameters ${n}`),e.EncoderSettings&&(this.config.setNumericSetting(st.MinQP,n&&r.has(st.MinQP)?Number.parseFloat(r.get(st.MinQP)):e.EncoderSettings.MinQP),this.config.setNumericSetting(st.MaxQP,n&&r.has(st.MaxQP)?Number.parseFloat(r.get(st.MaxQP)):e.EncoderSettings.MaxQP)),e.WebRTCSettings&&(this.config.setNumericSetting(st.WebRTCMinBitrate,n&&r.has(st.WebRTCMinBitrate)?Number.parseFloat(r.get(st.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(st.WebRTCMaxBitrate,n&&r.has(st.WebRTCMaxBitrate)?Number.parseFloat(r.get(st.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(st.WebRTCFPS,n&&r.has(st.WebRTCFPS)?Number.parseFloat(r.get(st.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(it.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new tt({count:e}))}_setupWebRtcTCPRelayDetection(e){let t=e.data.aggregatedStats.getActiveCandidatePair();if(null!=t){let n=e.data.aggregatedStats.localCandidates.find((e=>e.id==t.localCandidateId),null);null!=n&&"relay"==n.candidateType&&"tcp"==n.relayProtocol&&this._eventEmitter.dispatchEvent(new nt),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new gn(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(e=>{this._eventEmitter.dispatchEvent(new Xe({result:e}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:e}})=>{this._dataChannelLatencyTestController.receive(e)}))),this._dataChannelLatencyTestController.start(e))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(e),!0)}emitCommand(e){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in e||(this._webRtcController.emitCommand(e),0))}emitConsoleCommand(e){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(e),0))}addResponseEventListener(e,t){this._webRtcController.responseController.addResponseEventListener(e,t)}removeResponseEventListener(e){this._webRtcController.responseController.removeResponseEventListener(e)}dispatchEvent(e){return this._eventEmitter.dispatchEvent(e)}addEventListener(e,t){this._eventEmitter.addEventListener(e,t)}removeEventListener(e,t){this._eventEmitter.removeEventListener(e,t)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(e){this._webRtcController.signallingUrlBuilder=e}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(e,t,n){t!==At.FromStreamer||void 0!==n?t===At.ToStreamer&&void 0===n?this._webRtcController.streamMessageController.registerMessageHandler(t,e,(t=>this._webRtcController.sendMessageController.sendMessageToStreamer(e,t))):this._webRtcController.streamMessageController.registerMessageHandler(t,e,(e=>n(e))):Q.Warning(Q.GetStackTrace(),`Unable to register an undefined handler for ${e}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class bn{}var yn,vn,wn,Sn,_n=J.De,Tn=J.vU,xn=J.g,En=J.x_;!function(e){e[e.VideoInitialised=0]="VideoInitialised",e[e.DataChannelOpen=1]="DataChannelOpen",e[e.DataChannelResponse=2]="DataChannelResponse",e[e.WaitingForRenderer=3]="WaitingForRenderer",e[e.RendererTaken=4]="RendererTaken",e[e.WebRtcStats=5]="WebRtcStats"}(yn||(yn={}));class Cn{constructor(){this.type=yn.VideoInitialised}}class Pn{constructor(){this.type=yn.DataChannelOpen}}class On{constructor(e){this.msg=e,this.type=yn.DataChannelResponse}}class An{constructor(e){this.stats=e,this.type=yn.WebRtcStats}}!function(e){e.IndexInQueue="index_in_queue",e.RendererTaken="renderer_taken",e.RendererGone="renderer_gone",e.RendererError="renderer_error",e.ClientGone="client_gone",e.SwitchRendererRequest="switch_renderer_request"}(vn||(vn={})),function(e){e.AvatarAnswer="AvatarAnswer",e.AvatarStartedSpeaking="AvatarStartedSpeaking",e.AvatarStoppedSpeaking="AvatarStoppedSpeaking",e.CallToActionDismissed="CallToActionDismissed",e.CustomMetadataUpdated="CustomMetadataUpdated",e.DataProcessingWarning="DataProcessingWarning",e.DeviceError="DeviceError",e.DigitalHumanMuted="DigitalHumanMuted",e.DigitalHumanPlayedInMutedModeSuccess="DigitalHumanPlayedInMutedModeSuccess",e.DigitalHumanUnmuted="DigitalHumanUnmuted",e.EnableMicrophoneUpdated="EnableMicrophoneUpdated",e.FrameReady="FrameReady",e.FrameResize="FrameResize",e.MicPermissionDenied="MicPermissionDenied",e.Notification="Notification",e.PromptRequest="PromptRequest",e.PromptResult="PromptResult",e.ReadyToStart="ReadyToStart",e.SceneReady="SceneReady",e.SessionBackendError="SessionBackendError",e.SessionConnecting="SessionConnecting",e.SessionDisconnected="SessionDisconnected",e.SessionEnded="SessionEnded",e.SessionError="SessionError",e.SessionLive="SessionLive",e.SessionReconnecting="SessionReconnecting",e.SessionReconnectingFinished="SessionReconnectingFinished",e.SessionStateUpdate="SessionStateUpdate",e.SoftSwitchFinished="SoftSwitchFinished",e.SoftSwitchStarting="SoftSwitchStarting",e.SpeechEvent="SpeechEvent",e.SpeechTranscription="SpeechTranscription",e.UnhandledMessage="UnhandledMessage",e.UserStartedSpeaking="UserStartedSpeaking",e.UserStoppedSpeaking="UserStoppedSpeaking",e.VadInterruptionAllowed="VadInterruptionAllowed",e.VideoLayoutConfiguring="VideoLayoutConfiguring",e.WaitingInQueue="WaitingInQueue",e.WebRtcStats="WebRtcStats"}(wn||(wn={}));class kn{constructor(e){this.error=e,this.uneeqMessageType=wn.DeviceError}}class In{constructor(e,t,n,r){this.answer=e,this.answerAvatar=t,this.answerSpeech=n,this.transcriptId=r,this.uneeqMessageType=wn.AvatarAnswer}}class Mn{constructor(e){this.speechTranscription=e,this.uneeqMessageType=wn.SpeechTranscription}}class Rn{constructor(e){this.interruptionAllowed=e,this.uneeqMessageType=wn.VadInterruptionAllowed}}class Dn{constructor(){this.uneeqMessageType=wn.UserStartedSpeaking}}class $n{constructor(){this.uneeqMessageType=wn.UserStoppedSpeaking}}class Ln{constructor(){this.uneeqMessageType=wn.AvatarStartedSpeaking}}class Fn{constructor(){this.uneeqMessageType=wn.AvatarStoppedSpeaking}}class Un{constructor(e){this.sessionId=e,this.uneeqMessageType=wn.SessionLive}}class Nn{constructor(e){this.position=e,this.uneeqMessageType=wn.WaitingInQueue}}class jn{constructor(e){this.stats=e,this.uneeqMessageType=wn.WebRtcStats}}class Bn{constructor(e){this.error=e,this.uneeqMessageType=wn.SessionError}}class zn{constructor(e){this.error=e,this.uneeqMessageType=wn.SessionBackendError}}class Vn{constructor(e){this.speechEvent=e,this.uneeqMessageType=wn.SpeechEvent}}class Gn{constructor(e){this.reason=e,this.uneeqMessageType=wn.SessionEnded}}class Hn{constructor(){this.uneeqMessageType=wn.DigitalHumanPlayedInMutedModeSuccess,this.msg="Digital Human was successfully played in muted mode. After the user interacts with the page you will need to call unmuteDigitalHuman() to unmute the video."}}class Wn{constructor(){this.uneeqMessageType=wn.DigitalHumanUnmuted}}class qn{constructor(){this.uneeqMessageType=wn.DigitalHumanMuted}}class Kn{constructor(e){this.enabled=e,this.uneeqMessageType=wn.EnableMicrophoneUpdated}}class Xn{constructor(e){this.chatMetadata=e,this.uneeqMessageType=wn.CustomMetadataUpdated}}class Jn{constructor(e){this.promptRequest=e,this.uneeqMessageType=wn.PromptRequest}}class Qn{constructor(e){this.promptResult=e,this.uneeqMessageType=wn.PromptResult}}class Yn{constructor(){this.uneeqMessageType=wn.SceneReady}}class Zn{constructor(e){this.rendererId=e,this.uneeqMessageType=wn.SessionConnecting}}class er{constructor(){this.uneeqMessageType=wn.SessionDisconnected}}class tr{constructor(){this.uneeqMessageType=wn.SessionReconnecting}}class nr{constructor(){this.uneeqMessageType=wn.SessionReconnectingFinished}}class rr{constructor(){this.uneeqMessageType=wn.SoftSwitchStarting}}class ir{constructor(){this.uneeqMessageType=wn.SoftSwitchFinished}}class or{constructor(){this.uneeqMessageType=wn.VideoLayoutConfiguring}}!function(e){e.CameraAnchor="camera_to_anchor",e.ChatPrompt="chat_prompt",e.InterimTranscript="interim_transcript",e.StopSpeaking="stop_speaking",e.Speak="speak",e.SpeechStream="speech_stream",e.UserSpeaking="user_speaking"}(Sn||(Sn={}));const sr="sessionEndedDueToConnectionLoss",ar="sessionEndedDueToVideoPlaybackError";var ur;class lr{constructor(e,t,n){this.stream=e,this.videoElement=t,this.audioElement=n}analyzeAudioStats(){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){const e=this.stream._webRtcController.peerConnectionController.peerConnection;if(!e)return void r.error("Stream appears to be down, RTCPeerConnection is not defined");const t=yield e.getStats(null),n=this.getInboundAudioStats(t);if(!n)return void r.warn("WebRTC Connection - No inbound audio RTP stats found.");const i=n.codecId,o=this.getCodecFromStats(t,i);this.logAudioStats(n,o),this.logElementStatus(o)}))}getInboundAudioStats(e){let t=null;return e.forEach((e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&(t=e)})),t}getCodecFromStats(e,t){let n;return e.forEach((e=>{"codec"===e.type&&e.id===t&&(n=e)})),n}logAudioStats(e,t){const{packetsReceived:n,packetsLost:i,bytesReceived:o,jitter:s,audioLevel:a}=e;r.info(`WebRTC Connection - Audio - \n Codec: ${t?t.mimeType+" ("+t.payloadType+")":"Unknown"}, \n Packets received: ${n},\n Packets lost: ${i}, \n Bytes received: ${o}, \n Jitter: ${s},\n Audio level (0-1): ${null!=a?a:"N/A"}`),0===n&&r.warn("WebRTC Connection - Audio - No audio packets received — remote is probably not sending audio."),i>0&&r.warn(`WebRTC Connection - Audio - packet loss detected: ${i} packets lost.`),void 0===a?r.warn("WebRTC Connection - Audio - Audio level not available in stats."):0===a?r.warn("WebRTC Connection - Audio - Audio level is zero — digital human might not be talking at this exact moment as audio is silent or muted."):a<.02?r.warn("WebRTC Connection - Audio - Audio level is very low — audio might be too quiet."):r.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){var t,n,i;r.debug(`Video element muted: ${null===(t=this.videoElement)||void 0===t?void 0:t.muted}, (should be true as part of avoiding auto play restrictions)`),r.debug(`Audio element muted: ${null===(n=this.audioElement)||void 0===n?void 0:n.muted}, (should be false to be able to hear the digital human)`),r.debug(`Audio element volume: ${null===(i=this.audioElement)||void 0===i?void 0:i.volume}, (should be greater than zero to be able to hear the digital human)`);const o=null==e?void 0:e.mimeType;o&&this.audioElement&&(r.debug(`Audio element can play webrtc audio codec (${o}) : ${this.audioElement.canPlayType(o)}, (should be 'probably' or 'maybe)'`),"audio/opus"===o&&r.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${this.audioElement.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}}class cr{constructor(e,t,n){this.session=e,this.connectionUrl=t,this.videoContainerElement=n,this.messages=new q,this.videoInitialized=!1,this.dataChannelOpen=!1,this.sceneReady=!1,this.maxReconnectAttempts=3,this.reconnectionAttempts=0,this.allowReconnection=!0,this.isReconnectInProgress=!1,this.freezeCount=0,this.lastDecodedFrames=0,this.lastCheckTime=Date.now(),this.config=e.config,this.clientMessages=e.messages}init(){var e;r.info("Connection config",{connectionUrl:this.connectionUrl,forceTURN:this.config.forceTURN}),this.videoContainerElement||(this.videoContainerElement=document.createElement("div"),document.body.appendChild(this.videoContainerElement)),null===(e=this.clientMessages)||void 0===e||e.next(new or);const t=new _n({initialSettings:{AutoConnect:!1,AutoPlayVideo:!1,ForceTURN:this.config.forceTURN,HoveringMouse:!1,KeyboardInput:!1,MaxReconnectAttempts:3,MouseInput:!1,OfferToReceive:!1,ss:this.connectionUrl,StartVideoMuted:!0,TouchInput:!1,WaitForStreamer:!0}});this.stream=new xn(t,{videoElementParent:this.videoContainerElement}),this.stream.setSignallingUrlBuilder((function(){let e=t.getTextSettingValue(En.SignallingServerUrl);return t.isFlagEnabled(Tn.BrowserSendOffer)&&(e+=(e.includes("?")?"&":"?")+Tn.BrowserSendOffer+"=true"),e})),this.addStreamHandlers(),this.stream.connect(),this.addWebSocketHandlers()}addStreamHandlers(){var e,t,n,i,o,s,a,u,l,c,d;null===(e=this.stream)||void 0===e||e.addEventListener("videoInitialized",this.handleVideoInitialized.bind(this)),null===(t=this.stream)||void 0===t||t.addEventListener("dataChannelOpen",this.handleDataChannelOpen.bind(this)),null===(n=this.stream)||void 0===n||n.addEventListener("webRtcFailed",this.handleWebRtcFailed.bind(this)),null===(i=this.stream)||void 0===i||i.addEventListener("webRtcDisconnected",this.handleWebRtcDisconnected.bind(this)),null===(o=this.stream)||void 0===o||o.addEventListener("statsReceived",this.handleWebRtcStats.bind(this)),null===(s=this.stream)||void 0===s||s.addResponseEventListener("response-listener",this.handleDataChannelMessage.bind(this)),null===(a=this.stream)||void 0===a||a.addEventListener("videoEncoderAvgQP",(({data:{avgQP:e}})=>{r.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)})),null===(u=this.stream)||void 0===u||u.addEventListener("webRtcAutoConnect",(()=>{r.debug("WebRTC: AutoConnect triggered")})),null===(l=this.stream)||void 0===l||l.addEventListener("webRtcConnected",(()=>{r.debug("WebRTC: connected")})),null===(c=this.stream)||void 0===c||c.addEventListener("statsReceived",(({data:{aggregatedStats:e}})=>{r.trace("WebRTC: StatsReceived",e)})),null===(d=this.stream)||void 0===d||d.addEventListener("webRtcTCPRelayDetected",(()=>{r.warn("WebRTC: Stream quailty likely degraded due to network enviroment, stream is relayed over TCP.")}))}addWebSocketHandlers(){var e,t,n,r,i;null===(e=this.stream)||void 0===e||e.webSocketController.webSocket.addEventListener("error",this.handleWebSocketError.bind(this)),null===(t=this.stream)||void 0===t||t.webSocketController.signallingProtocol.addMessageHandler(vn.IndexInQueue,this.handleIndexInQueueMessage.bind(this)),null===(n=this.stream)||void 0===n||n.webSocketController.signallingProtocol.addMessageHandler(vn.RendererTaken,this.handleRendererTakenMessage.bind(this)),null===(r=this.stream)||void 0===r||r.webSocketController.signallingProtocol.addMessageHandler(vn.RendererGone,this.handleRendererGoneEvent.bind(this)),null===(i=this.stream)||void 0===i||i.webSocketController.signallingProtocol.addMessageHandler(vn.SwitchRendererRequest,this.handleSwitchRendererRequestEvent.bind(this))}handleWebSocketError(e){r.error("Signaling: WebSocket error",r.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){var e,t,n,i,o;if(r.info("Video initialized."),this.videoElement=null===(e=this.videoContainerElement)||void 0===e?void 0:e.getElementsByTagName("video")[0],this.audioElement=null===(i=null===(n=null===(t=this.stream)||void 0===t?void 0:t._webRtcController)||void 0===n?void 0:n.streamController)||void 0===i?void 0:i.audioElement,this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then((()=>{this.playAudioElement()})).catch((e=>{var t,n;if(e instanceof DOMException&&"NotAllowedError"===e.name)r.error('Fatal Error: Video cannot be played. User interaction or client permissions update is required to be able to "play" the video element.',e),null===(t=this.clientMessages)||void 0===t||t.next(new kn(e)),this.endSession("sessionEndedDueToPermissionsError",!0);else{const t="Fatal Error: Digital Human video cannot be played.";r.error(t,r.serialiseError(e)),null===(n=this.clientMessages)||void 0===n||n.next(new Bn(t)),this.endSession(ar,!0)}})),this.videoInitialized=!0,this.messages.next(new Cn),this.reconnectionAttempts=0;else{const e="Fatal Error: Video element not found.";r.error(e),null===(o=this.clientMessages)||void 0===o||o.next(new Bn(e)),this.endSession(ar,!0)}this.isReconnectInProgress=!1,setTimeout((()=>{var e;null===(e=this.clientMessages)||void 0===e||e.next(new nr)}),to)}playAudioElement(){this.audioElement?this.audioElement.play().then((()=>{var e;r.info("Audio played successfully."),null===(e=this.clientMessages)||void 0===e||e.next(new Wn)})).catch((e=>{var t,n;r.warn("Audio cannot be played.",e),null===(t=this.clientMessages)||void 0===t||t.next(new qn),null===(n=this.clientMessages)||void 0===n||n.next(new Hn)})):this.handleMissingAudioElement()}pauseAudioElement(){var e;this.audioElement?(this.audioElement.pause(),null===(e=this.clientMessages)||void 0===e||e.next(new qn)):this.handleMissingAudioElement()}handleMissingAudioElement(){var e;const t="Error: Digital Human audio element not found, cannot play audio.";r.error(t),null===(e=this.clientMessages)||void 0===e||e.next(new Bn(t))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),r.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new lr(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval((()=>{var e;null===(e=this.audioStatsAnalyzer)||void 0===e||e.analyzeAudioStats().catch((e=>{r.error("Error analyzing audio stats",r.serialiseError(e))}))}),e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}handleDataChannelOpen(){r.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new Pn)}handleWebRtcFailed(e){r.error("WebRTC failed",e),this.reconnectIfSafe(e)}handleWebRtcDisconnected(e){var t,n;r.warn(`WebRTC disconnected, message: ${null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.eventString}, allowClickToReconnect: ${null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.allowClickToReconnect}`),this.reconnectIfSafe(e)}handleWebRtcStats(e){var t,n;const r=new An(e.data.aggregatedStats);this.messages.next(r);const i=null!==(n=null===(t=e.data.aggregatedStats.inboundVideoStats)||void 0===t?void 0:t.framesDecoded)&&void 0!==n?n:0;this.checkForFreeze(i)}checkForFreeze(e){const t=Date.now();if(0!==this.lastDecodedFrames||0!==e)if(e===this.lastDecodedFrames){this.freezeCount++;const e=((t-this.lastCheckTime)/1e3).toFixed(1);r.warn(`[WebRTC] Video FROZEN for ${e}s (count=${this.freezeCount})`),this.freezeCount>=3&&(r.error("[WebRTC] Video frozen 3 times in a row, transferring session..."),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t;else r.debug("[WebRTC] Waiting for first video frame...")}reconnectIfSafe(e){var t,n,i,o;try{this.allowReconnection&&!this.isReconnectInProgress?(this.isReconnectInProgress=!0,r.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,r.info("Attempting to reconnect to signaling server. Attempt "+this.reconnectionAttempts),null===(t=this.stream)||void 0===t||t.reconnect(),null===(n=this.clientMessages)||void 0===n||n.next(new tr)):(r.info("Max reconnection attempts reached. Ending session."),null===(i=this.clientMessages)||void 0===i||i.next(new er),this.isReconnectInProgress=!1,this.endSession(sr,!1))):r.warn("Reconnection attempt already in progress or reconnecting is disabled")}catch(e){r.error("Error during reconnection attempt",r.serialiseError(e)),null===(o=this.clientMessages)||void 0===o||o.next(new Bn("Error during reconnection attempt")),this.isReconnectInProgress=!1,this.endSession(sr,!1)}}handleDataChannelMessage(e){r.trace("Signaling: Received data channel message",e);try{const t=JSON.parse(e);if(void 0===t.type)throw new Error("Signaling: Engine response missing type");this.messages.next(new On(t))}catch(e){r.error("Signaling: Failed to parse engine response",r.serialiseError(e))}}handleIndexInQueueMessage(e){var t;try{const n=JSON.parse(e),r=Number(n.message);null===(t=this.clientMessages)||void 0===t||t.next(new Nn(r))}catch(e){r.error("Signaling: Failed to parse position in queue message",r.serialiseError(e))}}handleRendererTakenMessage(e){var t;try{const n=JSON.parse(e);null===(t=this.clientMessages)||void 0===t||t.next(new Zn(n.message)),r.info("Signaling: Renderer taken event",n.message)}catch(e){r.error("Signaling: Failed to parse renderer taken message",r.serialiseError(e))}}handleRendererGoneEvent(e){r.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e)}handleSwitchRendererRequestEvent(e){r.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession()}socketSend(e){var t,n;r.trace("Signaling: Sending socket message",e),null===(n=null===(t=this.stream)||void 0===t?void 0:t.webSocketController)||void 0===n||n.webSocket.send(JSON.stringify(e))}dataSend(e){var t,n;const i=e.toJSON();r.info("Signaling: Sending data channel message",JSON.stringify(i)),i.action===Sn.ChatPrompt&&(null===(t=this.clientMessages)||void 0===t||t.next(new Jn(i.data))),null===(n=this.stream)||void 0===n||n.emitUIInteraction(e)}dataSendBinary(e){var t;r.info("Signaling: Sending data channel binary message");const n=this.uint8ToBase64(e);null===(t=this.stream)||void 0===t||t.emitUIInteraction(n)}uint8ToBase64(e){let t="";const n=e.byteLength;for(let r=0;r<n;r++)t+=String.fromCharCode(e[r]);return btoa(t)}endSession(e="sessionEndedByUser",t=!0){var n,i;r.info("Signaling: Ending session"),this.allowReconnection=!1,this.socketSend({message:e,type:vn.ClientGone,sessionId:this.config.sessionId}),null===(n=this.stream)||void 0===n||n.disconnect(),r.info("Session has ended, reason: "+e),t&&(null===(i=this.clientMessages)||void 0===i||i.next(new Gn(e)))}streamDisconnect(){var e;r.info("Signaling: Disconnecting stream"),this.allowReconnection=!1,null===(e=this.stream)||void 0===e||e.disconnect()}startSoftSwitch(){var e;r.info("Signaling: Start soft switching"),null===(e=this.clientMessages)||void 0===e||e.next(new rr)}stopSoftSwitch(){var e;r.info("Signaling: Stop soft switching"),null===(e=this.clientMessages)||void 0===e||e.next(new ir)}}!function(e){e.Google="google",e.Deepgram="deepgram"}(ur||(ur={}));var dr,hr=__webpack_require__(955),pr=__webpack_require__(603);!function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END"}(dr||(dr={}));const fr=[512,1024,1536];function gr(e){fr.includes(e.frameSamples)||r.warn("You are using an unusual frame size"),(e.positiveSpeechThreshold<0||e.negativeSpeechThreshold>1)&&r.error("postiveSpeechThreshold should be a number between 0 and 1"),(e.negativeSpeechThreshold<0||e.negativeSpeechThreshold>e.positiveSpeechThreshold)&&r.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),e.preSpeechPadFrames<0&&r.error("preSpeechPadFrames should be positive"),e.redemptionFrames<0&&r.error("preSpeechPadFrames should be positive")}const mr=e=>{const t=e.reduce(((e,t)=>(e.push(e[e.length-1]+t.length),e)),[0]),n=new Float32Array(t[t.length-1]);return e.forEach(((e,r)=>{const i=t[r];n.set(e,i)})),n};class br{constructor(e,t,n){this.modelProcessFunc=e,this.modelResetFunc=t,this.options=n,this.speaking=!1,this.redemptionCounter=0,this.active=!1,this.reset=()=>{this.speaking=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0},this.pause=()=>{this.active=!1,this.reset()},this.resume=()=>{this.active=!0},this.endSegment=()=>{const e=this.audioBuffer;this.audioBuffer=[];const t=this.speaking;this.reset();const n=e.reduce(((e,t)=>e+ +t.isSpeech),0);if(t){if(n>=this.options.minSpeechFrames){const t=mr(e.map((e=>e.frame)));return{msg:dr.SpeechEnd,audio:t}}return{msg:dr.VADMisfire}}return{}},this.process=e=>function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){if(!this.active)return{};const t=yield this.modelProcessFunc(e);if(this.audioBuffer.push({frame:e,isSpeech:t.isSpeech>=this.options.positiveSpeechThreshold}),t.isSpeech>=this.options.positiveSpeechThreshold&&this.redemptionCounter&&(this.redemptionCounter=0),t.isSpeech>=this.options.positiveSpeechThreshold&&!this.speaking)return this.speaking=!0,{probs:t,msg:dr.SpeechStart};if(t.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.options.redemptionFrames){this.redemptionCounter=0,this.speaking=!1;const e=this.audioBuffer;if(this.audioBuffer=[],e.reduce(((e,t)=>e+ +t.isSpeech),0)>=this.options.minSpeechFrames){const n=mr(e.map((e=>e.frame)));return{probs:t,msg:dr.SpeechEnd,audio:n}}return{probs:t,msg:dr.VADMisfire}}if(!this.speaking)for(;this.audioBuffer.length>this.options.preSpeechPadFrames;)this.audioBuffer.shift();return{probs:t}})),this.audioBuffer=[],this.reset()}}var yr,vr=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class wr{constructor(e,t){this.ort=e,this.modelFetcher=t,this.init=()=>vr(this,void 0,void 0,(function*(){r.debug("[VAD] initializing");const e=yield this.modelFetcher();this._session=yield this.ort.InferenceSession.create(e),this._sr=new this.ort.Tensor("int64",[BigInt(16e3)]),this.reset_state(),r.debug("[VAD] is initialized")})),this.reset_state=()=>{const e=Array(128).fill(0);this._h=new this.ort.Tensor("float32",e,[2,1,64]),this._c=new this.ort.Tensor("float32",e,[2,1,64])},this.process=e=>vr(this,void 0,void 0,(function*(){const t={input:new this.ort.Tensor("float32",e,[1,e.length]),h:this._h,c:this._c,sr:this._sr},n=yield this._session.run(t);this._h=n.hn,this._c=n.cn;const[r]=n.output.data;return{notSpeech:1-r,isSpeech:r}}))}}yr=wr,wr.new=(e,t)=>vr(void 0,void 0,void 0,(function*(){const n=new yr(e,t);return yield n.init(),n}));var Sr=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const _r=Object.assign(Object.assign({},{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,preSpeechPadFrames:1,redemptionFrames:8,frameSamples:1536,minSpeechFrames:3}),{onFrameProcessed:e=>{},onVADMisfire:()=>{r.debug("VAD misfire")},onSpeechStart:()=>{r.debug("Detected speech start")},onSpeechEnd:()=>{r.debug("Detected speech end")},stream:new MediaStream,assetBasePath:""});class Tr{static new(){return Sr(this,arguments,void 0,(function*(e={}){const t=new Tr(Object.assign(Object.assign({},_r),e));return yield t.init(),t}))}constructor(e){this.options=e,this.listening=!1,this.init=()=>Sr(this,void 0,void 0,(function*(){r.info("Initializing real time vad."),void 0===this.options.stream?this.stream=yield navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}):this.stream=this.options.stream,this.audioContext=new AudioContext;const e=new MediaStreamAudioSourceNode(this.audioContext,{mediaStream:this.stream});this.audioNodeVAD=yield xr.new(this.audioContext,this.options),this.audioNodeVAD.receive(e)})),this.pause=()=>{this.audioNodeVAD.pause(),this.listening=!1},this.start=()=>{this.audioNodeVAD.start(),this.listening=!0},gr(e)}}class xr{static new(e){return Sr(this,arguments,void 0,(function*(e,t={}){const n=new xr(e,Object.assign(Object.assign({},_r),t));return yield n.init(),n}))}constructor(e,t){this.ctx=e,this.options=t,this.pause=()=>{this.frameProcessor.pause()},this.start=()=>{this.frameProcessor.resume()},this.receive=e=>{e.connect(this.entryNode)},this.processFrame=e=>Sr(this,void 0,void 0,(function*(){const{probs:t,msg:n,audio:r}=yield this.frameProcessor.process(e);switch(void 0!==t&&this.options.onFrameProcessed(t),n){case dr.SpeechStart:this.options.onSpeechStart();break;case dr.VADMisfire:this.options.onVADMisfire();break;case dr.SpeechEnd:this.options.onSpeechEnd(r)}})),this.init=()=>Sr(this,void 0,void 0,(function*(){yield this.ctx.audioWorklet.addModule(this.options.assetBasePath+"vad.worklet.bundle.min.js");const e=new AudioWorkletNode(this.ctx,"vad-helper-worklet",{processorOptions:{frameSamples:this.options.frameSamples}});this.entryNode=e,pr.env.wasm.wasmPaths=this.options.assetBasePath;const t=yield wr.new(pr,this.modelFetcher);this.frameProcessor=new br(t.process,t.reset_state,{frameSamples:this.options.frameSamples,positiveSpeechThreshold:this.options.positiveSpeechThreshold,negativeSpeechThreshold:this.options.negativeSpeechThreshold,redemptionFrames:this.options.redemptionFrames,preSpeechPadFrames:this.options.preSpeechPadFrames,minSpeechFrames:this.options.minSpeechFrames}),e.port.onmessage=e=>Sr(this,void 0,void 0,(function*(){var t;if((null===(t=e.data)||void 0===t?void 0:t.message)===dr.AudioFrame){const t=e.data.data,n=new Float32Array(t);yield this.processFrame(n)}}))})),this.modelFetcher=()=>Sr(this,void 0,void 0,(function*(){const e=this.options.assetBasePath+"silero_vad.onnx";return yield fetch(e).then((e=>e.arrayBuffer()))})),gr(t)}}var Er;!function(e){e.startTranscription="startTranscription",e.stopTranscription="stopTranscription"}(Er||(Er={}));const Cr={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Pr;const Or=new Uint8Array(16),Ar=[];for(let e=0;e<256;++e)Ar.push((e+256).toString(16).slice(1));const kr=function(e,t,n){if(Cr.randomUUID&&!t&&!e)return Cr.randomUUID();const r=(e=e||{}).random??e.rng?.()??function(){if(!Pr){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pr=crypto.getRandomValues.bind(crypto)}return Pr(Or)}();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return function(e,t=0){return(Ar[e[t+0]]+Ar[e[t+1]]+Ar[e[t+2]]+Ar[e[t+3]]+"-"+Ar[e[t+4]]+Ar[e[t+5]]+"-"+Ar[e[t+6]]+Ar[e[t+7]]+"-"+Ar[e[t+8]]+Ar[e[t+9]]+"-"+Ar[e[t+10]]+Ar[e[t+11]]+Ar[e[t+12]]+Ar[e[t+13]]+Ar[e[t+14]]+Ar[e[t+15]]).toLowerCase()}(r)};class Ir{constructor(e=kr()){this.requestId=e}toJSON(){return{action:Sn.StopSpeaking,data:{requestId:this.requestId}}}}class Mr{constructor(e,t,n=kr()){this.prompt=e,this.metadata=t,this.requestId=n}toJSON(){return{action:Sn.ChatPrompt,data:{requestId:this.requestId,prompt:this.prompt,metadata:this.metadata}}}}var Rr;!function(e){e.Start="start",e.Stop="stop"}(Rr||(Rr={}));class Dr{constructor(e,t=kr()){this.state=e,this.requestId=t}toJSON(){return{action:Sn.UserSpeaking,data:{requestId:this.requestId,event:this.state}}}}class $r{constructor(e,t,n,r,i,o=kr()){this.transcript=e,this.stability=t,this.confidence=n,this.languageCode=r,this.isFinal=i,this.requestId=o}toJSON(){return{action:Sn.InterimTranscript,data:{requestId:this.requestId,transcript:this.transcript,stability:this.stability,confidence:this.confidence,languageCode:this.languageCode,isFinal:this.isFinal}}}}var Lr=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const Fr=48e3;class Ur{constructor(e){var t,n,r;this.options=e,this.speechBuffer=new hr.RingBuffer(5),this.recordingLive=!1,this.reconnectWs=!0,this.wsReconnectMessageQueue=[],this.awaitingFinalTranscript=!1,this.digitalHumanSpeaking=!1,this.interruptionBlocked=!1,this.options.assetBasePath=null!==(t=this.options.assetBasePath)&&void 0!==t?t:"https://cdn.uneeq.io/assets/platform/speech-recognition/",this.options.enableVad=null===(n=this.options.enableVad)||void 0===n||n,this.options.enableInterrupt=null!==(r=this.options.enableInterrupt)&&void 0!==r&&r,this.loadSavedAudioHeaders(),this.loadScripts(),this.handleAppMessages()}startRecognition(){this.initWebsocket(this.options)}stopRecognition(){this.mediaRecorder&&"recording"===this.mediaRecorder.state&&this.mediaRecorder.stop(),this.stream&&(this.stream.getTracks().forEach((e=>{e.stop()})),this.stream=void 0,this.clientMsgSend(new Kn(!1))),this.pauseMicVad()}pause(){var e;return this.stream&&this.micVad||r.warn(`[Speech Recognition] Problem pausing speech recognition, stream live: ${void 0!==this.stream} or microphone voice detection live: ${void 0!==this.micVad}.`),this.sendStoredTranscriptionIfReady(),null===(e=this.stream)||void 0===e||e.getTracks().forEach((e=>{e.enabled=!1})),this.pauseMicVad(),this.onVadSpeechEnd(),r.info("[Speech Recognition] paused"),!0}resume(){if(this.interruptionBlocked&&(this.digitalHumanSpeaking=!1,this.interruptionBlocked=!1,this.clientMsgSend(new Rn(!0))),!this.options.enableVad&&this.digitalHumanSpeaking&&(this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1),this.storedTranscription=void 0,this.stream&&this.micVad){this.stream.getTracks().forEach((e=>{e.enabled=!0}));const e=this.startMicVad();return r.info("[Speech Recognition] resumed: "+e),e}return r.warn(`[Speech Recognition] Could not resume speech recognition, stream live: ${void 0!==this.stream} or microphone voice detection live: ${void 0!==this.micVad}.`),!1}setChatMetadata(e){this.options.promptMetadata=e}pauseVadIfInterruptNotAllowed(){this.micVad&&!this.options.enableInterrupt&&(this.micVad.pause(),this.clientMsgSend(new Rn(!1))),this.options.enableInterrupt||(this.interruptionBlocked=!0)}loadScript(e){return Lr(this,void 0,void 0,(function*(){return yield new Promise((t=>{const n=document.createElement("script");n.src=e,n.onload=()=>{t(null)},document.body.appendChild(n)}))}))}loadScripts(){this.scriptsLoadedPromise=new Promise((e=>{this.loadScript(this.options.assetBasePath+"OpusMediaRecorder.umd.js").then((()=>{this.loadScript(this.options.assetBasePath+"encoderWorker.umd.js").then((()=>{e(null)})).catch((e=>{r.error("Error loading encoderWorker.umd.js",r.serialiseError(e))}))})).catch((e=>{r.error("Error loading OpusMediaRecorder.umd.js",r.serialiseError(e))}))}))}handleAppMessages(){this.options.messages.subscribe((e=>{switch(e.uneeqMessageType){case wn.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0,this.pauseVadIfInterruptNotAllowed();break;case wn.PromptResult:e.promptResult.success||this.handleSpeakingEnd();break;case wn.AvatarAnswer:""===e.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case wn.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case wn.SessionEnded:this.reconnectWs=!1,this.endRecognition();break;case wn.SessionReconnecting:this.handleSpeakingEnd(),this.reconnectWs=!1,this.endRecognition();break;case wn.CustomMetadataUpdated:this.options.promptMetadata=e.chatMetadata;break;case wn.SessionBackendError:this.handleSpeakingEnd()}}))}endRecognition(){this.stopRecognition(),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close()}handleSpeakingEnd(){this.digitalHumanSpeaking=!1,this.interruptionBlocked=!1,this.startMicVad(),this.options.enableInterrupt||this.clientMsgSend(new Rn(!0))}initWebsocket(e){this.endRecognition();let t=e.apiUrl.replace("https://","wss://").replace("http://","ws://");t+=`/speech-recognition-service/ws/recognize?jwt=${e.jwtToken}&session_id=${e.sessionId}`,r.info("[Speech Recognition] Initializing speech recognition websocket to "+t),this.ws=new WebSocket(t),this.ws.onopen=()=>{r.info("[Speech Recognition] Speech recognition web socket opened"),this.sendWebsocketMessageQueue(),this.initMicrophone()},this.ws.onclose=e=>{this.handleWebsocketClose(e)},this.ws.onerror=e=>{r.error("WebSocket error",r.serialiseError(e))},this.ws.onmessage=e=>{this.handleWebsocketMessage(e)}}sendWebsocketMessageQueue(){r.info("[Speech Recognition] Sending all queued websocket messages, queue length: "+this.wsReconnectMessageQueue.length),this.wsReconnectMessageQueue.forEach((e=>{this.wsSend(e,!1,!1)})),this.wsReconnectMessageQueue=[]}loadSavedAudioHeaders(){return Lr(this,void 0,void 0,(function*(){const e=this.options.assetBasePath+"opus-media-recorder-header.webm",t=yield fetch(e),n=yield t.arrayBuffer();this.headerBlob=new Blob([n],{type:"audio/webm;codecs=opus"})}))}initVoiceActivityDetection(e){r.info("[VAD] Going to initialize VAD module, with enableVad = "+this.options.enableVad),Tr.new({onSpeechStart:()=>{this.onVadSpeechStart()},onSpeechEnd:()=>{this.onVadSpeechEnd()},minSpeechFrames:1,positiveSpeechThreshold:this.options.enableVad?.5:0,negativeSpeechThreshold:this.options.enableVad?.35:0,redemptionFrames:8,assetBasePath:this.options.assetBasePath,stream:e}).then((e=>{this.micVad=e,this.interruptionBlocked?this.clientMsgSend(new Rn(!1)):this.startMicVad(),r.info("[VAD] module has started")})).catch((e=>{r.error("[VAD] could not start module",r.serialiseError(e))}))}startMicVad(){return!this.micVad||!this.options.enableInterrupt&&this.digitalHumanSpeaking?(r.info(`[VAD] VAD has not been started, microphone voice detection live: ${void 0!==this.micVad}, enableInterrupt: ${this.options.enableInterrupt}, isDigitalHumanSpeaking: ${this.digitalHumanSpeaking}.`),!1):(this.micVad.start(),r.info("[VAD] VAD has been started / unpaused"),!0)}pauseMicVad(){return this.micVad?(this.micVad.pause(),r.info("[VAD] has been paused"),!0):(r.info("[VAD] has not been initialized so has not been paused "),!1)}onVadSpeechStart(){r.info("[VAD] User started speaking"),this.dataChannelMsgSend(new Dr(Rr.Start)),this.clientMsgSend(new Dn),this.sendStartMessage(),this.wsSend(this.headerBlob),r.info("[VAD] Sending buffered speech audio");const e=new Blob(this.speechBuffer.toArray(),{type:"audio/webm;codecs=opus"});this.wsSend(e),this.recordingLive=!0,this.speechBuffer.clear()}onVadSpeechEnd(){r.info("[VAD] User has stopped speaking or intentionally ending current VAD"),this.dataChannelMsgSend(new Dr(Rr.Stop)),this.clientMsgSend(new $n),this.recordingLive=!1,this.sendStopMessage()}sendStoredTranscriptionIfReady(){this.options.enableVad||void 0===this.storedTranscription||this.awaitingFinalTranscript||(this.sendChatPrompt(this.storedTranscription.transcript),this.clientMsgSend(new Mn(this.storedTranscription)),this.storedTranscription=void 0)}handleWebsocketMessage(e){r.debug("[Speech Recognition] Got a websocket message: ",e);try{if("string"==typeof e.data){const t=JSON.parse(e.data),n=t.results?t.results[0]:null;"response"===t.state&&n&&(r.info(`[Speech Recognition] Speech transcription result ${JSON.stringify(n)}`),this.options.enableVad?this.handleVadTranscriptionResult(n):this.handlePttTranscriptionResult(n))}}catch(e){r.error("[Speech Recognition] Error processing message speech recognition socket message",r.serialiseError(e))}}handleWebsocketClose(e){r.warn("[Speech Recognition] WebSocket closed",e),this.reconnectWs&&this.initWebsocket(this.options)}sendStartMessage(){var e,t;const n={action:Er.startTranscription,channels:1,sampleRate:Fr,interimResults:!0,lang:this.options.locales||"en-US",phrases:null!==(e=this.options.hintPhrases)&&void 0!==e?e:"",phraseBoost:null!==(t=this.options.hintPhrasesBoost)&&void 0!==t?t:0};this.wsSend(JSON.stringify(n))}sendStopMessage(){const e={action:Er.stopTranscription};this.wsSend(JSON.stringify(e),!0)}wsSend(e,t=!1,n=!0){this.ws.readyState===WebSocket.OPEN&&this.ws.send(e),this.reconnectWs&&n&&(this.wsReconnectMessageQueue.push(e),t&&this.ws.readyState===WebSocket.OPEN&&(this.wsReconnectMessageQueue=[]),this.wsReconnectMessageQueue.length>3e3&&this.handleWsReconnectQueueOverflow())}handleWsReconnectQueueOverflow(){r.warn("[Speech Recognition] The websocket reconnection queue has exceeded maximum length of 3000. The audio reconnection queue will be reset, speech transcription performance may be impacted in the event of a reconnection."),this.wsReconnectMessageQueue=[]}initMicrophone(){this.stream?r.warn("[Microphone] Microphone already initialized, stream already exists, skipping initialization."):navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,sampleRate:Fr,channelCount:1}}).then((e=>{this.stream=e,this.initVoiceActivityDetection(e),this.initMediaRecorder(e),this.clientMsgSend(new Kn(!0))})).catch((e=>{r.error("[Microphone] Error starting recording",r.serialiseError(e)),this.clientMsgSend(new kn(new Error(JSON.stringify(e))))}))}getMediaRecorder(e,t,n){return new window.OpusMediaRecorder(e,t,n)}initMediaRecorder(e){const t={OggOpusEncoderWasmPath:this.options.assetBasePath+"OggOpusEncoder.wasm",WebMOpusEncoderWasmPath:this.options.assetBasePath+"WebMOpusEncoder.wasm"},n={mimeType:"audio/webm",audioBitsPerSecond:Fr};this.scriptsLoadedPromise.then((()=>{this.mediaRecorder=this.getMediaRecorder(e,n,t),this.mediaRecorder.ondataavailable=e=>{this.mediaRecorderOnData(e)},this.mediaRecorder.onstop=()=>{this.sendStopMessage()},this.mediaRecorder.start(100)})).catch((e=>{r.error("[Microphone] Error initializing media recorder",r.serialiseError(e))}))}mediaRecorderOnData(e){e.data&&e.data.size>0&&(this.recordingLive?this.wsSend(e.data):this.speechBuffer.add(e.data))}handlePttTranscriptionResult(e){var t;this.awaitingFinalTranscript=!e.final;try{this.recordingLive?e.final?void 0===this.storedTranscription?this.storedTranscription=e:this.storedTranscription.transcript+=e.transcript:this.digitalHumanSpeaking&&(this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1):e.final&&(void 0!==this.storedTranscription&&(e.transcript=this.storedTranscription.transcript+e.transcript),this.options.promptMetadata.userSpokenLocale=e.language_code,this.sendChatPrompt(e.transcript),this.sendInterimTranscription(e),this.clientMsgSend(new Mn(e)),this.storedTranscription=void 0),(null!==(t=e.stability)&&void 0!==t?t:1)>.5&&!e.final&&(void 0!==this.storedTranscription&&(e.transcript=this.storedTranscription.transcript+e.transcript),this.clientMsgSend(new Mn(e)),this.sendInterimTranscription(e))}catch(e){this.clientMsgSend(new Bn("Error processing speech transcription result")),this.storedTranscription=void 0}}handleVadTranscriptionResult(e){var t;""!==e.transcript&&(e.final?(this.options.promptMetadata.userSpokenLocale=e.language_code,this.sendChatPrompt(e.transcript)):this.digitalHumanSpeaking&&(this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1),this.sendInterimTranscription(e)),((null!==(t=e.stability)&&void 0!==t?t:1)>.5||e.final)&&this.clientMsgSend(new Mn(e))}sendChatPrompt(e){e&&""!==e.trim()&&(this.pauseVadIfInterruptNotAllowed(),this.dataChannelMsgSend(new Mr(e,this.options.promptMetadata)))}sendInterimTranscription(e){var t;if(e.transcript&&""!==e.transcript.trim()){const n=null!==(t=e.stability)&&void 0!==t?t:1;this.dataChannelMsgSend(new $r(e.transcript,n,e.confidence,e.language_code,e.final))}}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}}class Nr extends Error{constructor(e){super(e),this.__dgError=!0,this.name="DeepgramError"}}function jr(e){return"object"==typeof e&&null!==e&&"__dgError"in e}class Br extends Nr{constructor(e,t){super(e),this.name="DeepgramApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class zr extends Nr{constructor(e,t){super(e),this.name="DeepgramUnknownError",this.originalError=t}}class Vr extends Nr{constructor(){super("You are attempting to use an old format for a newer SDK version. Read more here: https://dpgr.am/js-v3"),this.name="DeepgramVersionError"}}class Gr extends Nr{constructor(e,t={}){super(e),this.name="DeepgramWebSocketError",this.originalEvent=t.originalEvent,this.statusCode=t.statusCode,this.requestId=t.requestId,this.responseHeaders=t.responseHeaders,this.url=t.url,this.readyState=t.readyState}toJSON(){return{name:this.name,message:this.message,statusCode:this.statusCode,requestId:this.requestId,responseHeaders:this.responseHeaders,url:this.url,readyState:this.readyState,originalEvent:this.originalEvent?{type:this.originalEvent.type,timeStamp:this.originalEvent.timeStamp}:void 0}}}var Hr=__webpack_require__(7),Wr=__webpack_require__(945),qr=__webpack_require__.n(Wr),Kr=__webpack_require__(744),Xr=__webpack_require__.n(Kr);const Jr="undefined"!=typeof process&&process.versions&&process.versions.node?process.versions.node:"unknown",Qr="undefined"!=typeof process&&process.versions&&process.versions.bun?process.versions.bun:"unknown",Yr="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent?window.navigator.userAgent:"unknown",Zr=()=>"unknown"!==Yr,ei=()=>"unknown"!==Qr;function ti(e={},t={}){return Xr()(t,e)}const ni=e=>!(!e||!e.url),ri=e=>!(!e||!e.text),ii=e=>!(!si(e)&&!oi(e)),oi=e=>null!=e&&Buffer.isBuffer(e),si=e=>null!=e&&!Zr()&&"object"==typeof e&&"function"==typeof e.pipe&&"function"==typeof e.read&&"object"==typeof e._readableState;URL;const ai="4.11.2",ui={"Content-Type":"application/json","X-Client-Info":`@deepgram/sdk; ${Zr()?"browser":"server"}; v${ai}`,"User-Agent":`@deepgram/sdk/${ai} ${"unknown"!==Jr?`node/${Jr}`:ei()?`bun/${Qr}`:Zr()?`javascript ${Yr}`:"unknown"}`},li="https://api.deepgram.com",ci="wss://agent.deepgram.com";var di;const hi={global:{fetch:{options:{url:li,headers:ui}},websocket:{options:{url:(di=li,di.toLowerCase().replace(/^http/,"ws")),_nodeOnlyHeaders:ui}}},agent:{fetch:{options:{url:li,headers:ui}},websocket:{options:{url:ci,_nodeOnlyHeaders:ui}}}};var pi,fi;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(pi||(pi={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(fi||(fi={}));const gi=()=>{};class mi extends Hr.EventEmitter{constructor(e){if(super(),this.factory=void 0,this.key=void 0,this.accessToken=void 0,this.namespace="global",this.version="v1",this.baseUrl=li,this.logger=gi,"function"==typeof e.accessToken?(this.factory=e.accessToken,this.accessToken=this.factory()):this.accessToken=e.accessToken,"function"==typeof e.key?(this.factory=e.key,this.key=this.factory()):this.key=e.key,this.key||this.accessToken||(this.accessToken=process.env.DEEPGRAM_ACCESS_TOKEN,this.accessToken||(this.key=process.env.DEEPGRAM_API_KEY)),!this.key&&!this.accessToken)throw new Nr("A deepgram API key or access token is required.");e=(e=>{var t,n,r,i,o,s;const a={};return e._experimentalCustomFetch&&(a.global={fetch:{client:e._experimentalCustomFetch}}),(null===(t=(e=Xr()(e,a)).restProxy)||void 0===t?void 0:t.url)&&(a.global={fetch:{options:{proxy:{url:null===(n=e.restProxy)||void 0===n?void 0:n.url}}}}),(null===(r=(e=Xr()(e,a)).global)||void 0===r?void 0:r.url)&&(a.global={fetch:{options:{url:e.global.url}},websocket:{options:{url:e.global.url}}}),(null===(i=(e=Xr()(e,a)).global)||void 0===i?void 0:i.headers)&&(a.global={fetch:{options:{headers:null===(o=e.global)||void 0===o?void 0:o.headers}},websocket:{options:{_nodeOnlyHeaders:null===(s=e.global)||void 0===s?void 0:s.headers}}}),Xr()(e,a)})(e),this.options=ti(e,hi)}v(e="v1"){return this.version=e,this}get namespaceOptions(){const e=ti(this.options[this.namespace],this.options.global);return Object.assign(Object.assign({},e),{key:this.key})}getRequestUrl(e,t={version:this.version},n){t.version=this.version,e=e.replace(/:(\w+)/g,(function(e,n){return t[n]}));const r=new URL(e,this.baseUrl);return n&&(i=r.searchParams,o=n,Object.keys(o).forEach((e=>{Array.isArray(o[e])?o[e].forEach((t=>{i.append(e,String(t))})):i.append(e,String(o[e]))}))),r;var i,o}log(e,t,n){this.logger(e,t,n)}}var bi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const yi=e=>{let t;return t=e||("undefined"==typeof fetch?qr():fetch),(...e)=>t(...e)};var vi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class wi extends mi{constructor(e){if(super(e),Zr()&&!this.proxy)throw new Nr("Due to CORS we are unable to support REST-based API calls to our API from the browser. Please consider using a proxy: https://dpgr.am/js-proxy for more information.");const{accessToken:t,key:n,fetch:r}=this;this.fetch=(({apiKey:e,customFetch:t,accessToken:n})=>{const r=yi(t),i="undefined"==typeof Headers?Wr.Headers:Headers;return(t,o)=>bi(void 0,void 0,void 0,(function*(){const s=new i(null==o?void 0:o.headers);return s.has("Authorization")||s.set("Authorization",n?`Bearer ${n}`:`Token ${e}`),r(t,Object.assign(Object.assign({},o),{headers:s}))}))})({accessToken:t,apiKey:n,customFetch:r}),this.proxy?this.baseUrl=this.namespaceOptions.fetch.options.proxy.url:this.baseUrl=this.namespaceOptions.fetch.options.url}_getErrorMessage(e){return e.msg||e.message||e.error_description||e.error||JSON.stringify(e)}_handleError(e,t){return vi(this,void 0,void 0,(function*(){const n=yield bi(void 0,void 0,void 0,(function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,945,23))).Response:Response}));e instanceof n?e.json().then((n=>{t(new Br(this._getErrorMessage(n),e.status||500))})).catch((e=>{t(new zr(this._getErrorMessage(e),e))})):t(new zr(this._getErrorMessage(e),e))}))}_getRequestOptions(e,t,n){let r={method:e};return r="GET"===e||"DELETE"===e?Object.assign(Object.assign({},r),t):Object.assign(Object.assign({duplex:"half",body:t},r),n),Xr()(this.namespaceOptions.fetch.options,r,{clone:!1})}_handleRequest(e,t,n,r){return vi(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{(0,this.fetch)(t,this._getRequestOptions(e,n,r)).then((e=>{if(!e.ok)throw e;i(e)})).catch((e=>this._handleError(e,o)))}))}))}get(e,t){return vi(this,void 0,void 0,(function*(){return this._handleRequest("GET",e,t)}))}post(e,t,n){return vi(this,void 0,void 0,(function*(){return this._handleRequest("POST",e,t,n)}))}put(e,t,n){return vi(this,void 0,void 0,(function*(){return this._handleRequest("PUT",e,t,n)}))}patch(e,t,n){return vi(this,void 0,void 0,(function*(){return this._handleRequest("PATCH",e,t,n)}))}delete(e,t){return vi(this,void 0,void 0,(function*(){return this._handleRequest("DELETE",e,t)}))}get proxy(){var e;return"proxy"===this.key&&!!(null===(e=this.namespaceOptions.fetch.options.proxy)||void 0===e?void 0:e.url)}}class Si extends wi{constructor(){super(...arguments),this.namespace="auth"}grantToken(e={},t=":version/auth/grant"){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t),r=JSON.stringify(e);return{result:yield this.post(n,r,{headers:{"Content-Type":"application/json"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}const _i="undefined"!=typeof WebSocket;class Ti extends mi{constructor(e){super(e),this.conn=null,this.sendBuffer=[],this.reconnect=gi;const{key:t,websocket:{options:n,client:r}}=this.namespaceOptions;this.proxy?this.baseUrl=n.proxy.url:this.baseUrl=n.url,this.transport=r||null,n._nodeOnlyHeaders?this.headers=n._nodeOnlyHeaders:this.headers={},"Authorization"in this.headers||(this.accessToken?this.headers.Authorization=`Bearer ${this.accessToken}`:this.headers.Authorization=`Token ${t}`)}connect(e,t){if(this.conn)return;this.reconnect=(n=e)=>{this.connect(n,t)};const n=this.getRequestUrl(t,{},e),r=this.accessToken,i=this.key;if(!r&&!i)throw new Error("No key or access token provided for WebSocket connection.");if(this.transport)return this.conn=new this.transport(n,void 0,{headers:this.headers}),void this.setupConnection();if(ei())__webpack_require__.e(591).then(__webpack_require__.t.bind(__webpack_require__,591,23)).then((({default:e})=>{this.conn=new e(n,{headers:this.headers}),console.log("Using WS package"),this.setupConnection()}));else{if(_i)return this.conn=new WebSocket(n,r?["bearer",r]:["token",i]),void this.setupConnection();this.conn=new xi(n,void 0,{close:()=>{this.conn=null}}),__webpack_require__.e(591).then(__webpack_require__.t.bind(__webpack_require__,591,23)).then((({default:e})=>{this.conn=new e(n,void 0,{headers:this.headers}),this.setupConnection()}))}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null)}connectionState(){switch(this.conn&&this.conn.readyState){case pi.connecting:return fi.Connecting;case pi.open:return fi.Open;case pi.closing:return fi.Closing;default:return fi.Closed}}getReadyState(){var e,t;return null!==(t=null===(e=this.conn)||void 0===e?void 0:e.readyState)&&void 0!==t?t:pi.closed}isConnected(){return this.connectionState()===fi.Open}send(e){const t=()=>function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){var t;if(e instanceof Blob){if(0===e.size)return void this.log("warn","skipping `send` for zero-byte blob",e);e=yield e.arrayBuffer()}"string"==typeof e||(null==e?void 0:e.byteLength)?null===(t=this.conn)||void 0===t||t.send(e):this.log("warn","skipping `send` for zero-byte payload",e)}));this.isConnected()?t():this.sendBuffer.push(t)}get proxy(){var e;return"proxy"===this.key&&!!(null===(e=this.namespaceOptions.websocket.options.proxy)||void 0===e?void 0:e.url)}extractErrorInformation(e,t){var n;const r={};if(t&&(r.readyState=t.readyState,r.url="string"==typeof t.url?t.url:null===(n=t.url)||void 0===n?void 0:n.toString()),t&&"object"==typeof t){const n=t;if(n._req&&n._req.res&&(r.statusCode=n._req.res.statusCode,n._req.res.headers)){r.responseHeaders=Object.assign({},n._req.res.headers);const e=n._req.res.headers["dg-request-id"]||n._req.res.headers["x-dg-request-id"];e&&(r.requestId=e)}if(e&&"target"in e&&e.target){const t=e.target;t.url&&(r.url=t.url),void 0!==t.readyState&&(r.readyState=t.readyState)}}return r}createEnhancedError(e,t){const n=new Gr(e.message||"WebSocket connection error",Object.assign({originalEvent:e},t));return Object.assign(Object.assign({},e),{error:n,statusCode:t.statusCode,requestId:t.requestId,responseHeaders:t.responseHeaders,url:t.url,readyState:t.readyState,message:this.buildEnhancedErrorMessage(e,t)})}buildEnhancedErrorMessage(e,t){let n=e.message||"WebSocket connection error";const r=[];if(t.statusCode&&r.push(`Status: ${t.statusCode}`),t.requestId&&r.push(`Request ID: ${t.requestId}`),void 0!==t.readyState){const e=["CONNECTING","OPEN","CLOSING","CLOSED"][t.readyState]||`Unknown(${t.readyState})`;r.push(`Ready State: ${e}`)}return t.url&&r.push(`URL: ${t.url}`),r.length>0&&(n+=` (${r.join(", ")})`),n}setupConnectionEvents(e){this.conn&&(this.conn.onopen=()=>{this.emit(e.Open,this)},this.conn.onclose=t=>{this.emit(e.Close,t)},this.conn.onerror=t=>{const n=this.extractErrorInformation(t,this.conn||void 0),r=this.createEnhancedError(t,n);this.emit(e.Error,r)})}}class xi{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=pi.connecting,this.send=()=>{},this.url=null,this.url=e.toString(),this.close=n.close}}var Ei;!function(e){e.Open="open",e.Close="close",e.Error="error",e.Transcript="Results",e.Metadata="Metadata",e.UtteranceEnd="UtteranceEnd",e.SpeechStarted="SpeechStarted",e.Unhandled="Unhandled"}(Ei||(Ei={}));class Ci extends Ti{constructor(e,t={},n=":version/listen"){var r,i;if(super(e),this.namespace="listen",(null===(r=t.keyterm)||void 0===r?void 0:r.length)&&!(null===(i=t.model)||void 0===i?void 0:i.startsWith("nova-3")))throw new Nr("Keyterms are only supported with the Nova 3 models.");this.connect(t,n)}setupConnection(){this.setupConnectionEvents({Open:Ei.Open,Close:Ei.Close,Error:Ei.Error}),this.conn&&(this.conn.onmessage=e=>{var t,n,r,i;try{const t=JSON.parse(e.data.toString());t.type===Ei.Metadata?this.emit(Ei.Metadata,t):t.type===Ei.Transcript?this.emit(Ei.Transcript,t):t.type===Ei.UtteranceEnd?this.emit(Ei.UtteranceEnd,t):t.type===Ei.SpeechStarted?this.emit(Ei.SpeechStarted,t):this.emit(Ei.Unhandled,t)}catch(o){this.emit(Ei.Error,{event:e,message:"Unable to parse `data` as JSON.",error:o,url:null===(t=this.conn)||void 0===t?void 0:t.url,readyState:null===(n=this.conn)||void 0===n?void 0:n.readyState,data:(null===(r=e.data)||void 0===r?void 0:r.toString().substring(0,200))+((null===(i=e.data)||void 0===i?void 0:i.toString().length)>200?"...":"")})}})}configure(e){this.send(JSON.stringify({type:"Configure",processors:e}))}keepAlive(){this.send(JSON.stringify({type:"KeepAlive"}))}finalize(){this.send(JSON.stringify({type:"Finalize"}))}finish(){this.requestClose()}requestClose(){this.send(JSON.stringify({type:"CloseStream"}))}}var Pi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Oi extends wi{constructor(){super(...arguments),this.namespace="listen"}transcribeUrl(e,t,n=":version/listen"){var r,i;return Pi(this,void 0,void 0,(function*(){try{let o;if(!ni(e))throw new Nr("Unknown transcription source type");if(o=JSON.stringify(e),void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");if((null===(r=null==t?void 0:t.keyterm)||void 0===r?void 0:r.length)&&!(null===(i=t.model)||void 0===i?void 0:i.startsWith("nova-3")))throw new Nr("Keyterms are only supported with the Nova 3 models.");const s=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(s,o).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}transcribeFile(e,t,n=":version/listen"){return Pi(this,void 0,void 0,(function*(){try{let r;if(!ii(e))throw new Nr("Unknown transcription source type");if(r=e,void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");const i=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(i,r,{headers:{"Content-Type":"deepgram/audio+video"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}transcribeUrlCallback(e,t,n,r=":version/listen"){return Pi(this,void 0,void 0,(function*(){try{let i;if(!ni(e))throw new Nr("Unknown transcription source type");i=JSON.stringify(e);const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}transcribeFileCallback(e,t,n,r=":version/listen"){return Pi(this,void 0,void 0,(function*(){try{let i;if(!ii(e))throw new Nr("Unknown transcription source type");i=e;const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i,{headers:{"Content-Type":"deepgram/audio+video"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}class Ai extends mi{constructor(){super(...arguments),this.namespace="listen"}get prerecorded(){return new Oi(this.options)}live(e={},t=":version/listen"){return new Ci(this.options,e,t)}}var ki=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Ii extends wi{constructor(){super(...arguments),this.namespace="manage"}getTokenDetails(e=":version/auth/token"){return ki(this,void 0,void 0,(function*(){try{const t=this.getRequestUrl(e);return{result:yield this.get(t).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjects(e=":version/projects"){return ki(this,void 0,void 0,(function*(){try{const t=this.getRequestUrl(e);return{result:yield this.get(t).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProject(e,t=":version/projects/:projectId"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}updateProject(e,t,n=":version/projects/:projectId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t),i=JSON.stringify(t);return{result:yield this.patch(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteProject(e,t=":version/projects/:projectId"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return yield this.delete(n),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}getProjectKeys(e,t=":version/projects/:projectId/keys"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectKey(e,t,n=":version/projects/:projectId/keys/:keyId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,keyId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}createProjectKey(e,t,n=":version/projects/:projectId/keys"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t),i=JSON.stringify(t);return{result:yield this.post(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteProjectKey(e,t,n=":version/projects/:projectId/keys/:keyId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,keyId:t});return yield this.delete(r),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}getProjectMembers(e,t=":version/projects/:projectId/members"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}removeProjectMember(e,t,n=":version/projects/:projectId/members/:memberId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,memberId:t});return yield this.delete(r),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}getProjectMemberScopes(e,t,n=":version/projects/:projectId/members/:memberId/scopes"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,memberId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}updateProjectMemberScope(e,t,n,r=":version/projects/:projectId/members/:memberId/scopes"){return ki(this,void 0,void 0,(function*(){try{const i=this.getRequestUrl(r,{projectId:e,memberId:t},n),o=JSON.stringify(n);return{result:yield this.put(i,o).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectInvites(e,t=":version/projects/:projectId/invites"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}sendProjectInvite(e,t,n=":version/projects/:projectId/invites"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t),i=JSON.stringify(t);return{result:yield this.post(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteProjectInvite(e,t,n=":version/projects/:projectId/invites/:email"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,email:t});return yield this.delete(r),{error:null}}catch(e){if(jr(e))return{error:e};throw e}}))}leaveProject(e,t=":version/projects/:projectId/leave"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.delete(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageRequests(e,t,n=":version/projects/:projectId/requests"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageRequest(e,t,n=":version/projects/:projectId/requests/:requestId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,requestId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageSummary(e,t,n=":version/projects/:projectId/usage"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectUsageFields(e,t,n=":version/projects/:projectId/usage/fields"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectBalances(e,t=":version/projects/:projectId/balances"){return ki(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getProjectBalance(e,t,n=":version/projects/:projectId/balances/:balanceId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,balanceId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getAllModels(e,t={},n=":version/projects/:projectId/models"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e},t);return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getModel(e,t,n=":version/projects/:projectId/models/:modelId"){return ki(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,modelId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}var Mi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Ri extends wi{constructor(){super(...arguments),this.namespace="models"}getAll(e=":version/models",t={}){return Mi(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(e,{},t);return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getModel(e,t=":version/models/:modelId"){return Mi(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{modelId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}var Di=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class $i extends wi{constructor(){super(...arguments),this.namespace="selfhosted"}listCredentials(e,t=":version/projects/:projectId/onprem/distribution/credentials"){return Di(this,void 0,void 0,(function*(){try{const n=this.getRequestUrl(t,{projectId:e});return{result:yield this.get(n).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}getCredentials(e,t,n=":version/projects/:projectId/onprem/distribution/credentials/:credentialsId"){return Di(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,credentialsId:t});return{result:yield this.get(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}createCredentials(e,t,n=":version/projects/:projectId/onprem/distribution/credentials"){return Di(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e}),i=JSON.stringify(t);return{result:yield this.post(r,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}deleteCredentials(e,t,n=":version/projects/:projectId/onprem/distribution/credentials/:credentialsId"){return Di(this,void 0,void 0,(function*(){try{const r=this.getRequestUrl(n,{projectId:e,credentialsId:t});return{result:yield this.delete(r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}var Li,Fi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class Ui extends wi{constructor(){super(...arguments),this.namespace="read"}analyzeUrl(e,t,n=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let r;if(!ni(e))throw new Nr("Unknown source type");if(r=JSON.stringify(e),void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous transcription. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");const i=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(i,r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}analyzeText(e,t,n=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let r;if(!ri(e))throw new Nr("Unknown source type");if(r=JSON.stringify(e),void 0!==t&&"callback"in t)throw new Nr("Callback cannot be provided as an option to a synchronous requests. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");const i=this.getRequestUrl(n,{},Object.assign({},t));return{result:yield this.post(i,r).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}analyzeUrlCallback(e,t,n,r=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let i;if(!ni(e))throw new Nr("Unknown source type");i=JSON.stringify(e);const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}analyzeTextCallback(e,t,n,r=":version/read"){return Fi(this,void 0,void 0,(function*(){try{let i;if(!ri(e))throw new Nr("Unknown source type");i=JSON.stringify(e);const o=this.getRequestUrl(r,{},Object.assign(Object.assign({},n),{callback:t.toString()}));return{result:yield this.post(o,i,{headers:{"Content-Type":"deepgram/audio+video"}}).then((e=>e.json())),error:null}}catch(e){if(jr(e))return{result:null,error:e};throw e}}))}}!function(e){e.Open="Open",e.Close="Close",e.Error="Error",e.Metadata="Metadata",e.Flushed="Flushed",e.Warning="Warning",e.Audio="Audio",e.Unhandled="Unhandled"}(Li||(Li={}));class Ni extends Ti{constructor(e,t={},n=":version/speak"){super(e),this.namespace="speak",this.connect(t,n)}setupConnection(){this.setupConnectionEvents({Open:Li.Open,Close:Li.Close,Error:Li.Error}),this.conn&&(this.conn.onmessage=e=>{this.handleMessage(e)})}handleTextMessage(e){e.type===Li.Metadata?this.emit(Li.Metadata,e):e.type===Li.Flushed?this.emit(Li.Flushed,e):e.type===Li.Warning?this.emit(Li.Warning,e):this.emit(Li.Unhandled,e)}handleBinaryMessage(e){this.emit(Li.Audio,e)}sendText(e){this.send(JSON.stringify({type:"Speak",text:e}))}flush(){this.send(JSON.stringify({type:"Flush"}))}clear(){this.send(JSON.stringify({type:"Clear"}))}requestClose(){this.send(JSON.stringify({type:"Close"}))}handleMessage(e){var t,n,r,i,o,s;if("string"==typeof e.data)try{const t=JSON.parse(e.data);this.handleTextMessage(t)}catch(o){this.emit(Li.Error,{event:e,message:"Unable to parse `data` as JSON.",error:o,url:null===(t=this.conn)||void 0===t?void 0:t.url,readyState:null===(n=this.conn)||void 0===n?void 0:n.readyState,data:(null===(r=e.data)||void 0===r?void 0:r.toString().substring(0,200))+((null===(i=e.data)||void 0===i?void 0:i.toString().length)>200?"...":"")})}else e.data instanceof Blob?e.data.arrayBuffer().then((e=>{this.handleBinaryMessage(Buffer.from(e))})):e.data instanceof ArrayBuffer?this.handleBinaryMessage(Buffer.from(e.data)):Buffer.isBuffer(e.data)?this.handleBinaryMessage(e.data):(console.log("Received unknown data type",e.data),this.emit(Li.Error,{event:e,message:"Received unknown data type.",url:null===(o=this.conn)||void 0===o?void 0:o.url,readyState:null===(s=this.conn)||void 0===s?void 0:s.readyState,dataType:typeof e.data}))}}var ji,Bi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};class zi extends wi{constructor(){super(...arguments),this.namespace="speak"}request(e,t,n=":version/speak"){return Bi(this,void 0,void 0,(function*(){let r;if(!ri(e))throw new Nr("Unknown transcription source type");r=JSON.stringify(e);const i=this.getRequestUrl(n,{},Object.assign({model:"aura-2-thalia-en"},t));return this.result=yield this.post(i,r,{headers:{Accept:"audio/*","Content-Type":"application/json"}}),this}))}getStream(){return Bi(this,void 0,void 0,(function*(){if(!this.result)throw new zr("Tried to get stream before making request","");return this.result.body}))}getHeaders(){return Bi(this,void 0,void 0,(function*(){if(!this.result)throw new zr("Tried to get headers before making request","");return this.result.headers}))}}class Vi extends mi{constructor(){super(...arguments),this.namespace="speak"}request(e,t,n=":version/speak"){return new zi(this.options).request(e,t,n)}live(e={},t=":version/speak"){return new Ni(this.options,e,t)}}!function(e){e.Open="Open",e.Close="Close",e.Error="Error",e.Audio="Audio",e.Welcome="Welcome",e.SettingsApplied="SettingsApplied",e.ConversationText="ConversationText",e.UserStartedSpeaking="UserStartedSpeaking",e.AgentThinking="AgentThinking",e.FunctionCallRequest="FunctionCallRequest",e.AgentStartedSpeaking="AgentStartedSpeaking",e.AgentAudioDone="AgentAudioDone",e.InjectionRefused="InjectionRefused",e.PromptUpdated="PromptUpdated",e.SpeakUpdated="SpeakUpdated",e.Unhandled="Unhandled"}(ji||(ji={}));class Gi extends Ti{constructor(e,t="/:version/agent/converse"){var n,r,i,o;super(e),this.namespace="agent",this.baseUrl=null!==(o=null===(i=null===(r=null===(n=e.agent)||void 0===n?void 0:n.websocket)||void 0===r?void 0:r.options)||void 0===i?void 0:i.url)&&void 0!==o?o:ci,this.connect({},t)}setupConnection(){this.setupConnectionEvents({Open:ji.Open,Close:ji.Close,Error:ji.Error}),this.conn&&(this.conn.onmessage=e=>{this.handleMessage(e)})}handleMessage(e){var t,n,r,i,o,s;if("string"==typeof e.data)try{const t=JSON.parse(e.data);this.handleTextMessage(t)}catch(o){this.emit(ji.Error,{event:e,data:(null===(t=e.data)||void 0===t?void 0:t.toString().substring(0,200))+((null===(n=e.data)||void 0===n?void 0:n.toString().length)>200?"...":""),message:"Unable to parse `data` as JSON.",error:o,url:null===(r=this.conn)||void 0===r?void 0:r.url,readyState:null===(i=this.conn)||void 0===i?void 0:i.readyState})}else e.data instanceof Blob?e.data.arrayBuffer().then((e=>{this.handleBinaryMessage(Buffer.from(e))})):e.data instanceof ArrayBuffer?this.handleBinaryMessage(Buffer.from(e.data)):Buffer.isBuffer(e.data)?this.handleBinaryMessage(e.data):(console.log("Received unknown data type",e.data),this.emit(ji.Error,{event:e,message:"Received unknown data type.",url:null===(o=this.conn)||void 0===o?void 0:o.url,readyState:null===(s=this.conn)||void 0===s?void 0:s.readyState,dataType:typeof e.data}))}handleBinaryMessage(e){this.emit(ji.Audio,e)}handleTextMessage(e){e.type in ji?this.emit(e.type,e):this.emit(ji.Unhandled,e)}configure(e){const t=JSON.stringify(Object.assign({type:"Settings"},e));this.send(t)}updatePrompt(e){this.send(JSON.stringify({type:"UpdatePrompt",prompt:e}))}updateSpeak(e){this.send(JSON.stringify({type:"UpdateSpeak",speak:e}))}injectAgentMessage(e){this.send(JSON.stringify({type:"InjectAgentMessage",content:e}))}injectUserMessage(e){this.send(JSON.stringify({type:"InjectUserMessage",content:e}))}functionCallResponse(e){this.send(JSON.stringify(Object.assign({type:"FunctionCallResponse"},e)))}keepAlive(){this.send(JSON.stringify({type:"KeepAlive"}))}}class Hi extends mi{get auth(){return new Si(this.options)}get listen(){return new Ai(this.options)}get manage(){return new Ii(this.options)}get models(){return new Ri(this.options)}get onprem(){return this.selfhosted}get selfhosted(){return new $i(this.options)}get read(){return new Ui(this.options)}get speak(){return new Vi(this.options)}agent(e="/:version/agent/converse"){return new Gi(this.options,e)}get transcription(){throw new Vr}get projects(){throw new Vr}get keys(){throw new Vr}get members(){throw new Vr}get scopes(){throw new Vr}get invitation(){throw new Vr}get usage(){throw new Vr}get billing(){throw new Vr}}var Wi=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))};const qi="[Deepgram STT]";class Ki{constructor(e){var t,n,r,i,o,s,a,u,l,c;this.options=e,this.connection=null,this.isConnected=!1,this.isPaused=!1,this.shouldReconnect=!0,this.isConnecting=!1,this.microphone=null,this.stream=null,this.reconnectAttempts=0,this.reconnectDelay=1e3,this.reconnectTimeoutId=null,this.digitalHumanSpeaking=!1,this.isUserCurrentlySpeaking=!1,this.isUiShowingSpeaking=!1,this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.options.model=this.options.model||"nova-2",this.options.language=this.options.language||"en",this.options.smartFormat=null===(t=this.options.smartFormat)||void 0===t||t,this.options.interimResults=null===(n=this.options.interimResults)||void 0===n||n,this.options.utteranceEndMs=null!==(r=this.options.utteranceEndMs)&&void 0!==r?r:1500,this.options.vadEvents=null===(i=this.options.vadEvents)||void 0===i||i,this.options.fillerWords=null!==(o=this.options.fillerWords)&&void 0!==o&&o,this.options.endpointing=null!==(s=this.options.endpointing)&&void 0!==s?s:500,this.options.echoCancellation=null===(a=this.options.echoCancellation)||void 0===a||a,this.options.noiseSuppression=null===(u=this.options.noiseSuppression)||void 0===u||u,this.options.autoGainControl=null===(l=this.options.autoGainControl)||void 0===l||l,this.options.interruptionWordThreshold=null!==(c=this.options.interruptionWordThreshold)&&void 0!==c?c:1,this.handleAppMessages()}startRecognition(){return Wi(this,void 0,void 0,(function*(){r.info(`${qi} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),yield this.connect()}))}stopRecognition(){return Wi(this,void 0,void 0,(function*(){r.info(`${qi} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),yield this.disconnect()}))}pause(){return Wi(this,void 0,void 0,(function*(){return r.info(`${qi} Pausing speech recognition`),this.isPaused=!0,this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.isUserCurrentlySpeaking&&(this.dataChannelMsgSend(new Dr(Rr.Stop)),this.isUserCurrentlySpeaking=!1),this.isUiShowingSpeaking&&(this.clientMsgSend(new $n),this.isUiShowingSpeaking=!1),this.stream&&(this.stream.getTracks().forEach((e=>{e.enabled=!1})),r.debug(`${qi} Audio tracks disabled`)),!0}))}resume(){return Wi(this,void 0,void 0,(function*(){return r.info(`${qi} Resuming speech recognition`),this.isPaused=!1,this.stream?(this.stream.getTracks().forEach((e=>{e.enabled=!0})),r.debug(`${qi} Audio tracks re-enabled`),!0):(r.debug(`${qi} No stream available, initiating connection`),yield this.connect(),!0)}))}setChatMetadata(e){this.options.promptMetadata=e}connect(){return Wi(this,void 0,void 0,(function*(){if(this.isConnected)r.warn(`${qi} Already connected`);else if(this.isConnecting)r.warn(`${qi} Connection already in progress`);else{this.isConnecting=!0;try{const e=yield this.getToken();r.info(`${qi} Connecting to Deepgram`);const t=function(e,t){let n={};return"string"==typeof e||"function"==typeof e?n.key=e:"object"==typeof e&&(n=e),new Hi(n)}({accessToken:e.token,global:{url:e.api_url}}),n={model:this.options.model,language:this.options.language,smart_format:this.options.smartFormat,interim_results:this.options.interimResults,utterance_end_ms:this.options.utteranceEndMs,vad_events:this.options.vadEvents,filler_words:this.options.fillerWords,endpointing:this.options.endpointing};this.connection=t.listen.live(n),yield new Promise(((e,t)=>{var n,i;const o=setTimeout((()=>{t(new Error("Connection timeout"))}),1e4),s=()=>{var t,n;clearTimeout(o),this.isConnected=!0,r.info(`${qi} Connection opened`),null===(t=this.connection)||void 0===t||t.off(Ei.Open,s),null===(n=this.connection)||void 0===n||n.off(Ei.Error,a),e()},a=e=>{var n,i;clearTimeout(o),r.error(`${qi} Connection error during open`,r.serialiseError(e)),null===(n=this.connection)||void 0===n||n.off(Ei.Open,s),null===(i=this.connection)||void 0===i||i.off(Ei.Error,a),t(e)};null===(n=this.connection)||void 0===n||n.on(Ei.Open,s),null===(i=this.connection)||void 0===i||i.on(Ei.Error,a)})),this.setupEventHandlers(),yield this.startMicrophone(),r.info(`${qi} Connected successfully`),this.isConnecting=!1,this.resetReconnectionState()}catch(e){this.isConnected=!1,this.isConnecting=!1,r.error(`${qi} Connection error`,r.serialiseError(e)),this.handleError(e),this.shouldReconnect&&!this.isPaused&&this.scheduleReconnect()}}}))}disconnect(){return Wi(this,void 0,void 0,(function*(){if(this.isConnected||this.connection){r.info(`${qi} Disconnecting`);try{this.stopMicrophone(),this.connection&&(this.connection.requestClose(),this.connection=null)}catch(e){r.error(`${qi} Disconnect error`,r.serialiseError(e))}this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.isUserCurrentlySpeaking&&(this.dataChannelMsgSend(new Dr(Rr.Stop)),this.isUserCurrentlySpeaking=!1),this.isUiShowingSpeaking&&(this.clientMsgSend(new $n),this.isUiShowingSpeaking=!1),this.isConnected=!1,this.clientMsgSend(new Kn(!1))}}))}scheduleReconnect(){if(this.reconnectAttempts>=5)return r.error(`${qi} Max reconnection attempts (5) reached`),void this.clientMsgSend(new Bn("Unable to connect to speech recognition service after 5 attempts"));this.reconnectAttempts++,r.info(`${qi} Scheduling reconnection attempt ${this.reconnectAttempts}/5 in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout((()=>{this.connect()}),this.reconnectDelay),this.reconnectDelay=Math.min(2*this.reconnectDelay,3e4)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=1e3,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}getToken(){return Wi(this,void 0,void 0,(function*(){const e=this.options.model||"nova-2",t=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(e)}`,n=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!n.ok)throw new Error(`Token fetch failed: ${n.status} ${n.statusText}`);return yield n.json()}))}startMicrophone(){return Wi(this,void 0,void 0,(function*(){try{r.info(`${qi} Starting microphone`),this.stream=yield navigator.mediaDevices.getUserMedia({audio:{echoCancellation:this.options.echoCancellation,noiseSuppression:this.options.noiseSuppression,autoGainControl:this.options.autoGainControl}}),this.microphone=new MediaRecorder(this.stream,{mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:48e3}),this.microphone.ondataavailable=e=>{e.data.size>0&&this.connection&&this.isConnected&&!this.isPaused&&e.data.arrayBuffer().then((e=>{var t;null===(t=this.connection)||void 0===t||t.send(e)})).catch((e=>{r.error(`${qi} Error converting audio data`,r.serialiseError(e))}))},this.microphone.start(250),r.debug(`${qi} Microphone started`),this.clientMsgSend(new Kn(!0))}catch(e){r.error(`${qi} Microphone error`,r.serialiseError(e)),this.clientMsgSend(new kn(new Error(JSON.stringify(e))))}}))}stopMicrophone(){this.microphone&&"recording"===this.microphone.state&&(this.microphone.stop(),this.microphone=null),this.stream&&(this.stream.getTracks().forEach((e=>{e.stop()})),this.stream=null),r.debug(`${qi} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on(Ei.Open,(()=>{this.handleConnectionOpen()})),this.connection.on(Ei.Transcript,(e=>{this.handleTranscript(e)})),this.connection.on(Ei.Close,(()=>{this.handleConnectionClose()})),this.connection.on(Ei.Error,(e=>{this.handleError(e)})),this.connection.on(Ei.Metadata,(e=>{r.debug(`${qi} Metadata`,e)})))}handleAppMessages(){this.options.messages.subscribe((e=>{switch(e.uneeqMessageType){case wn.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0;break;case wn.PromptResult:e.promptResult.success||this.handleSpeakingEnd();break;case wn.AvatarAnswer:""===e.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case wn.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case wn.SessionEnded:this.shouldReconnect=!1,this.stopRecognition();break;case wn.SessionReconnecting:this.handleSpeakingEnd(),this.shouldReconnect=!1,this.stopRecognition();break;case wn.CustomMetadataUpdated:this.options.promptMetadata=e.chatMetadata;break;case wn.SessionBackendError:this.handleSpeakingEnd()}}))}handleTranscript(e){var t,n,i;try{const o=e.channel;if(!(null==o?void 0:o.alternatives)||0===o.alternatives.length)return;const s=o.alternatives[0],a=String(s.transcript||""),u=!0===e.is_final,l=!0===e.speech_final;if(""===a&&l){if(""!==this.accumulatedTranscript.trim()){r.info(`${qi} Final transcript (from accumulated): "${this.accumulatedTranscript}"`),this.sendChatPrompt(this.accumulatedTranscript);const e=this.accumulatedWordCount>0?this.accumulatedConfidenceSum/this.accumulatedWordCount:1,t={transcript:this.accumulatedTranscript,final:!0,confidence:e,language_code:this.options.language||""};this.clientMsgSend(new Mn(t))}return this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0,this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new Dr(Rr.Stop))),void(this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new $n)))}if(""===a)return;if(u&&!l){""!==this.accumulatedTranscript&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=a;const e=a.trim().split(/\s+/).length,n=null!==(t=s.confidence)&&void 0!==t?t:1;this.accumulatedConfidenceSum+=n*e,this.accumulatedWordCount+=e,r.debug(`${qi} Accumulated transcript: "${this.accumulatedTranscript}"`)}const c=(""!==this.accumulatedTranscript?this.accumulatedTranscript:a).trim().split(/\s+/).length,d=null!==(n=this.options.interruptionWordThreshold)&&void 0!==n?n:1;!this.isUiShowingSpeaking&&c>=d&&(this.isUiShowingSpeaking=!0,this.clientMsgSend(new Dn)),!this.isUserCurrentlySpeaking&&c>=d&&(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new Dr(Rr.Start))),this.digitalHumanSpeaking&&c>=d&&(r.debug(`${qi} Interrupting digital human`),this.dataChannelMsgSend(new Ir),this.digitalHumanSpeaking=!1),this.isUserCurrentlySpeaking&&l&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new Dr(Rr.Stop))),this.isUiShowingSpeaking&&l&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new $n));const h={transcript:l?this.accumulatedTranscript+(""!==this.accumulatedTranscript?" ":"")+a:a,final:l,confidence:null!==(i=s.confidence)&&void 0!==i?i:1,language_code:this.options.language||""};if(this.clientMsgSend(new Mn(h)),l){const e=""!==this.accumulatedTranscript?this.accumulatedTranscript+" "+a:a;r.info(`${qi} Final transcript: "${e}"`),this.sendChatPrompt(e),this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0}}catch(e){r.error(`${qi} Error processing transcript`,r.serialiseError(e))}}handleConnectionOpen(){this.isConnected=!0}handleConnectionClose(){r.info(`${qi} Connection closed`),this.isConnected=!1,this.clientMsgSend(new Kn(!1)),this.shouldReconnect&&!this.isPaused&&(r.info(`${qi} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}handleError(e){var t;r.error(`${qi} Error occurred`,e);const n=String((null==e?void 0:e.message)||(null===(t=null==e?void 0:e.toString)||void 0===t?void 0:t.call(e))||"Unknown error");n.includes("microphone")||n.includes("permission")||n.includes("getUserMedia")?this.clientMsgSend(new kn(new Error(n))):this.clientMsgSend(new Bn(n))}sendChatPrompt(e){e&&""!==e.trim()&&(this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language),this.dataChannelMsgSend(new Mr(e,this.options.promptMetadata)))}handleSpeakingEnd(){this.digitalHumanSpeaking=!1,this.isPaused&&!this.isUserCurrentlySpeaking&&this.resume()}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}}var Xi,Ji,Qi;!function(e){e.NlpPromptResult="nlp_prompt_result",e.AvatarStartedSpeaking="avatar_started_speaking",e.AvatarStoppedSpeaking="avatar_stopped_speaking",e.Error="error",e.SceneReady="scene_ready",e.SpeechEvent="speech_event",e.SessionEnded="session_ended",e.SpeechStreamOpened="speech_stream_opened",e.SpeechStreamClosed="speech_stream_closed"}(Xi||(Xi={})),function(e){e.CloseUp="close_up",e.LooseCloseUp="loose_close_up",e.TightMediumShot="tight_medium_shot",e.MediumShot="medium_shot",e.MediumFullShot="medium_full_shot",e.FullShot="full_shot"}(Ji||(Ji={})),function(e){e.Left="left",e.Right="right",e.Center="center",e.Centre="centre"}(Qi||(Qi={}));class Yi{constructor(e,t=2e3,n=kr()){this.position=e,this.duration=t,this.requestId=n}toJSON(){return{action:Sn.CameraAnchor,data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}}class Zi{constructor(e){this.session=e,this.isTransferSessionInProgress=!1,this.addTransferSessionListener()}addTransferSessionListener(){this.isTransferSessionInProgress=!1,document.addEventListener("keydown",(e=>{e.ctrlKey&&e.shiftKey&&"y"===e.key.toLowerCase()&&this.transferSession()}))}transferSession(){this.isTransferSessionInProgress?r.warn("Transfer already in progress, skipping"):(this.isTransferSessionInProgress=!0,r.info("Beginning session transfer"),this.session.createSignaling(document.createElement("div")).init())}switchLiveVideo(e,t){r.info("New signaling video is ready for transfer"),this.session.signaling&&e&&t.videoElement&&(t.videoElement.classList.add("incoming-video"),this.session.signaling.videoElement&&t.videoElement&&(null==e||e.appendChild(t.videoElement)),this.session.signaling.startSoftSwitch(),setTimeout((()=>{var e,n;null===(e=this.session.signaling)||void 0===e||e.streamDisconnect(),this.session.signaling=t,this.isTransferSessionInProgress=!1,null===(n=this.session.signaling)||void 0===n||n.stopSoftSwitch(),r.info("Session transfer complete")}),1e3))}}const eo=[1200,1402],to=750;class no{constructor(e){this.config=e,this.messages=new G,this.promptMetadata={},this.welcomeRequested=!1,this.resolutionLogged=!1,this.sessionTransferManager=new Zi(this)}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new Xn(this.promptMetadata))}catch(t){r.error("Error parsing custom metadata",e,r.serialiseError(t))}}setEnableMicrophone(e){this.speechRec?e?this.speechRec.startRecognition():this.speechRec.stopRecognition():r.warn("setEnableMicrophone called but speech recognition is not initialized")}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,null==n||n.dataSend(new Yi(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,null==n||n.dataSend(new Yi(e,t))}createSession(){this.messages.subscribe((e=>{this.config.messageHandler&&this.config.messageHandler(e)})),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,r.info("Session created with id: "+this.id),this.updatePromptMetadata(this.config.customMetadata||{}),this.promptMetadata=this.initMetadata(),this.listenForTabClosure(),this.signaling=this.createSignaling(this.config.videoContainerElement),this.signaling.init()}createSignaling(e=document.createElement("div")){const t=new URLSearchParams({token:this.jwt});this.config.backgroundUrl&&t.append("backgroundUrl",this.config.backgroundUrl);const n=(this.config.connectionUrl+`/session-service/v1/ws/session?${t.toString()}`).replace("http://","ws://").replace("https://","wss://");r.debug("Socket URL:",n);const i=new cr(this,n,e);return i.messages.subscribe((e=>{this.signalingEventHandler(e,i)})),i}signalingEventHandler(e,t){var n,i;switch(e.type){case yn.VideoInitialised:case yn.DataChannelOpen:this.handleSessionReady(t);break;case yn.DataChannelResponse:this.handleDataChannelMessage(e);break;case yn.WebRtcStats:{const t=e.stats;!this.resolutionLogged&&(null===(n=t.inboundVideoStats)||void 0===n?void 0:n.frameWidth)&&(null===(i=t.inboundVideoStats)||void 0===i?void 0:i.frameHeight)&&(r.info("Video resolution:",`${t.inboundVideoStats.frameWidth}x${t.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new jn(t)),this.config.webRtcStatsLogMessages&&r.info("WebRTC stats",t);break}}}handleSessionReady(e){r.debug("Session ready check - video:",e.videoInitialized,"dataChannel:",e.dataChannelOpen,"scene:",e.sceneReady),e.videoInitialized&&e.dataChannelOpen&&e.sceneReady&&(this.setCameraAnchorDistance(this.config.cameraAnchorDistance,0,e),this.setCameraAnchorHorizontal(this.config.cameraAnchorHorizontal,0,e),setTimeout((()=>{this.sessionTransferManager.isTransferSessionInProgress&&this.config.videoContainerElement?this.sessionTransferManager.switchLiveVideo(this.config.videoContainerElement,e):(this.initSpeechRecognition(this.jwt),this.sendWelcomePrompt(),document.body.classList.add("uneeq-streaming-live")),this.messages.next(new Un(this.id))}),to))}initSpeechRecognition(e){if(this.speechRec)return void r.warn("Speech recognition already initialized");let t=this.config.speechRecognitionProvider||ur.Google;r.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!==ur.Google&&t!==ur.Deepgram&&(r.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t=ur.Google,this.config.speechRecognitionProvider=ur.Google),r.info(`[STT] Using provider: ${t}`),t===ur.Deepgram?this.createDeepgramSTT(e):this.createGoogleSTT(e),this.config.enableMicrophone&&this.speechRec&&this.speechRec.startRecognition()}createGoogleSTT(e){const t=this.getSpeechOptions(e);r.debug("Initializing Google STT (speech-recognition-service)"),this.speechRec=new Ur(t)}createDeepgramSTT(e){var t,n,i;r.warn("Deepgram STT is currently in beta, is subject to change, and is not suitable for production use"),r.debug("Initializing Deepgram STT");const o=this.config.deepgramConfig||{},s={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:o.model,language:o.language,smartFormat:o.smartFormat,interimResults:o.interimResults,utteranceEndMs:o.utteranceEndMs,vadEvents:o.vadEvents,encoding:o.encoding,sampleRate:o.sampleRate,channels:o.channels,fillerWords:o.fillerWords,endpointing:o.endpointing,interruptionWordThreshold:o.interruptionWordThreshold,echoCancellation:null===(t=o.microphone)||void 0===t?void 0:t.echoCancellation,noiseSuppression:null===(n=o.microphone)||void 0===n?void 0:n.noiseSuppression,autoGainControl:null===(i=o.microphone)||void 0===i?void 0:i.autoGainControl,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{var t;null===(t=this.signaling)||void 0===t||t.dataSend(e)},enableInterrupt:this.config.enableInterruptBySpeech};this.speechRec=new Ki(s)}getSpeechOptions(e){return{apiUrl:this.config.connectionUrl,assetBasePath:this.config.assetBasePath,enableInterrupt:this.config.enableInterruptBySpeech,enableVad:this.config.enableVad,jwtToken:e,hintPhrases:this.config.speechRecognitionHintPhrases,hintPhrasesBoost:this.config.speechRecognitionHintPhrasesBoost,locales:this.config.speechRecognitionLocales,messages:this.messages,promptMetadata:this.promptMetadata,sessionId:this.id,sendMessage:e=>{var t;null===(t=this.signaling)||void 0===t||t.dataSend(e)}}}initMetadata(){return{userSpokenLocale:"",browserDetectedLocales:this.config.speechRecognitionLocales,userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userScreenWidth:window.screen.availWidth,userScreenHeight:window.screen.availHeight,userAgent:navigator.userAgent,personaId:this.config.personaId,custom:this.config.customMetadata}}handleDataChannelMessage(e){var t;switch(r.debug("Processing data channel message",e),e.msg.type){case Xi.NlpPromptResult:this.messages.next(new Qn(e.msg));break;case Xi.AvatarStartedSpeaking:this.messages.next(new Ln);break;case Xi.AvatarStoppedSpeaking:this.messages.next(new Fn);break;case Xi.Error:{const t=e.msg;r.error(`an error has occurred - ${JSON.stringify(t)}`),this.handleChannelMessageError(t);break}case Xi.SceneReady:this.signaling&&(r.debug("Scene is ready"),this.signaling.sceneReady=!0,this.handleSessionReady(this.signaling),this.messages.next(new Yn));break;case Xi.SpeechEvent:this.messages.next(new Vn(e.msg));break;case Xi.SessionEnded:{const n=e.msg.reason;null===(t=this.signaling)||void 0===t||t.endSession(n);break}case Xi.SpeechStreamOpened:{const t=e.msg;this.audioStreamId=t.streamId;break}case Xi.SpeechStreamClosed:{const t=e.msg;t.streamId===this.audioStreamId?this.audioStreamId=void 0:r.warn("Received SpeechStreamClosed message for unexpected streamId",t.streamId);break}}}handleChannelMessageError(e){var t;const n=(null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.trim())||"An unknown error occurred";e&&eo.includes(e.code)?this.messages.next(new zn(e)):this.messages.next(new Bn(n))}sendWelcomePrompt(){var e;r.debug("Checking if the welcome prompt should be sent. Welcome requested already = "+this.welcomeRequested+". Prompt = ",this.config.welcomePrompt),this.config.welcomePrompt&&this.config.welcomePrompt.length>0&&!this.welcomeRequested&&(this.welcomeRequested=!0,null===(e=this.signaling)||void 0===e||e.dataSend(new Mr(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",(()=>{var e;r.info("Window unload detected, ending session."),null===(e=this.signaling)||void 0===e||e.endSession()}))}}class ro{constructor(e,t=kr()){this.prompt=e,this.requestId=t}toJSON(){return{action:Sn.Speak,data:{requestId:this.requestId,prompt:this.prompt}}}}var io;!function(e){e.Open="open",e.Close="close",e.Interrupt="interrupt"}(io||(io={}));class oo{constructor(e,t,n={},r=kr()){this.action=e,this.streamId=t,this.metadata=n,this.requestId=r}toJSON(){return{action:Sn.SpeechStream,data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}}class so{constructor(e){var t;this.config=e,r.setLevel(null!==(t=e.logLevel)&&void 0!==t?t:"info")}init(){r.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new no(this.config),this.session.createSession()}ensureSessionExists(){var e;return!!(null===(e=this.session)||void 0===e?void 0:e.id)||(r.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){var t,n,r;e&&""!==e.trim()&&this.ensureSessionExists()&&(null===(n=null===(t=this.session)||void 0===t?void 0:t.signaling)||void 0===n||n.dataSend(new Mr(e,null===(r=this.session)||void 0===r?void 0:r.promptMetadata)))}speak(e){var t,n;e&&""!==e.trim()&&this.ensureSessionExists()&&(null===(n=null===(t=this.session)||void 0===t?void 0:t.signaling)||void 0===n||n.dataSend(new ro(e)))}openAudioStream(){var e;const t=this.session;this.ensureSessionExists()&&(null===(e=null==t?void 0:t.signaling)||void 0===e||e.dataSend(new oo(io.Open,null==t?void 0:t.audioStreamId)))}closeAudioStream(){var e;const t=this.session;this.ensureSessionExists()&&void 0!==(null==t?void 0:t.audioStreamId)&&(null===(e=t.signaling)||void 0===e||e.dataSend(new oo(io.Close,t.audioStreamId)))}interruptAudioStream(){var e;const t=this.session;this.ensureSessionExists()&&void 0!==(null==t?void 0:t.audioStreamId)&&(null===(e=t.signaling)||void 0===e||e.dataSend(new oo(io.Interrupt,t.audioStreamId)))}speakAudio(e){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){this.ensureSessionExists()&&(yield function(e,t){return function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){var n;try{if(void 0===(null==e?void 0:e.audioStreamId))return void r.warn("Audio stream is not open | Call openAudioStream() first");let i;if("string"==typeof t){const e="undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("binary");i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else if(t instanceof Uint8Array)i=t;else{if(!("undefined"!=typeof Blob&&t instanceof Blob))return void r.error("speakAudio: Unsupported audio type",t);{const e=yield t.arrayBuffer();i=new Uint8Array(e)}}const o=Uint8Array.from([1]),s=Uint8Array.from([e.audioStreamId]),a=new Uint8Array(2+i.length);a.set(o,0),a.set(s,1),a.set(i,2),null===(n=e.signaling)||void 0===n||n.dataSendBinary(a)}catch(e){r.error("speakAudioSend: Error sending audio",e)}}))}(this.session,e))}))}cameraAnchorDistance(e,t){var n;this.ensureSessionExists()&&(null===(n=this.session)||void 0===n||n.setCameraAnchorDistance(e,t))}cameraAnchorHorizontal(e,t){var n;this.ensureSessionExists()&&(null===(n=this.session)||void 0===n||n.setCameraAnchorHorizontal(e,t))}endSession(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.endSession())}unmuteDigitalHuman(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.playAudioElement(),r.debug("Unmuted digital human."))}muteDigitalHuman(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.pauseAudioElement(),r.debug("Muted digital human."))}stopSpeaking(){var e,t;this.ensureSessionExists()&&(null===(t=null===(e=this.session)||void 0===e?void 0:e.signaling)||void 0===t||t.dataSend(new Ir))}setCustomPromptMetadata(e){var t;this.ensureSessionExists()&&(null===(t=this.session)||void 0===t||t.updatePromptMetadata(e))}enableMicrophone(e=!0){var t;this.ensureSessionExists()&&(null===(t=this.session)||void 0===t||t.setEnableMicrophone(e))}pauseSpeechRecognition(){var e,t,n;if(this.ensureSessionExists()){const r=null!==(n=null===(t=null===(e=this.session)||void 0===e?void 0:e.speechRec)||void 0===t?void 0:t.pause())&&void 0!==n&&n;return r instanceof Promise||r}return!1}resumeSpeechRecognition(){var e,t,n;if(this.ensureSessionExists()){const r=null!==(n=null===(t=null===(e=this.session)||void 0===e?void 0:e.speechRec)||void 0===t?void 0:t.resume())&&void 0!==n&&n;return r instanceof Promise||r}return!1}setWebRtcStatsEnabled(e,t){var n,r,i;(null===(n=this.session)||void 0===n?void 0:n.config)&&(this.session.config.webRtcStatsEmitMessages=e,this.session.config.webRtcStatsLogMessages=t,t?null===(r=this.session.signaling)||void 0===r||r.startAudioStatsMonitor():null===(i=this.session.signaling)||void 0===i||i.stopAudioStatsMonitor())}}window.Uneeq=so})(),__webpack_exports__})()));