diff --git "a/assets/index-C-k-PxxY.js" "b/assets/index-C-k-PxxY.js" new file mode 100644--- /dev/null +++ "b/assets/index-C-k-PxxY.js" @@ -0,0 +1,2688 @@ +var FM=Object.defineProperty;var zM=(e,t,n)=>t in e?FM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qe=(e,t,n)=>zM(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const f of l.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&o(f)}).observe(document,{childList:!0,subtree:!0});function n(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function o(a){if(a.ep)return;a.ep=!0;const l=n(a);fetch(a.href,l)}})();var So=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function b_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var b1={exports:{}},Xh={},x1={exports:{}},Mr={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Kf=Symbol.for("react.element"),OM=Symbol.for("react.portal"),DM=Symbol.for("react.fragment"),LM=Symbol.for("react.strict_mode"),RM=Symbol.for("react.profiler"),BM=Symbol.for("react.provider"),NM=Symbol.for("react.context"),jM=Symbol.for("react.forward_ref"),UM=Symbol.for("react.suspense"),VM=Symbol.for("react.memo"),WM=Symbol.for("react.lazy"),Zw=Symbol.iterator;function GM(e){return e===null||typeof e!="object"?null:(e=Zw&&e[Zw]||e["@@iterator"],typeof e=="function"?e:null)}var M1={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T1=Object.assign,k1={};function tu(e,t,n){this.props=e,this.context=t,this.refs=k1,this.updater=n||M1}tu.prototype.isReactComponent={};tu.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};tu.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function S1(){}S1.prototype=tu.prototype;function x_(e,t,n){this.props=e,this.context=t,this.refs=k1,this.updater=n||M1}var M_=x_.prototype=new S1;M_.constructor=x_;T1(M_,tu.prototype);M_.isPureReactComponent=!0;var Jw=Array.isArray,E1=Object.prototype.hasOwnProperty,T_={current:null},C1={key:!0,ref:!0,__self:!0,__source:!0};function P1(e,t,n){var o,a={},l=null,f=null;if(t!=null)for(o in t.ref!==void 0&&(f=t.ref),t.key!==void 0&&(l=""+t.key),t)E1.call(t,o)&&!C1.hasOwnProperty(o)&&(a[o]=t[o]);var _=arguments.length-2;if(_===1)a.children=n;else if(1<_){for(var h=Array(_),g=0;g<_;g++)h[g]=arguments[g+2];a.children=h}if(e&&e.defaultProps)for(o in _=e.defaultProps,_)a[o]===void 0&&(a[o]=_[o]);return{$$typeof:Kf,type:e,key:l,ref:f,props:a,_owner:T_.current}}function qM(e,t){return{$$typeof:Kf,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function k_(e){return typeof e=="object"&&e!==null&&e.$$typeof===Kf}function HM(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var ev=/\/+/g;function Ym(e,t){return typeof e=="object"&&e!==null&&e.key!=null?HM(""+e.key):t.toString(36)}function ch(e,t,n,o,a){var l=typeof e;(l==="undefined"||l==="boolean")&&(e=null);var f=!1;if(e===null)f=!0;else switch(l){case"string":case"number":f=!0;break;case"object":switch(e.$$typeof){case Kf:case OM:f=!0}}if(f)return f=e,a=a(f),e=o===""?"."+Ym(f,0):o,Jw(a)?(n="",e!=null&&(n=e.replace(ev,"$&/")+"/"),ch(a,t,n,"",function(g){return g})):a!=null&&(k_(a)&&(a=qM(a,n+(!a.key||f&&f.key===a.key?"":(""+a.key).replace(ev,"$&/")+"/")+e)),t.push(a)),1;if(f=0,o=o===""?".":o+":",Jw(e))for(var _=0;_<e.length;_++){l=e[_];var h=o+Ym(l,_);f+=ch(l,t,n,h,a)}else if(h=GM(e),typeof h=="function")for(e=h.call(e),_=0;!(l=e.next()).done;)l=l.value,h=o+Ym(l,_++),f+=ch(l,t,n,h,a);else if(l==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return f}function Gp(e,t,n){if(e==null)return e;var o=[],a=0;return ch(e,o,"","",function(l){return t.call(n,l,a++)}),o}function KM(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ti={current:null},dh={transition:null},QM={ReactCurrentDispatcher:ti,ReactCurrentBatchConfig:dh,ReactCurrentOwner:T_};function $1(){throw Error("act(...) is not supported in production builds of React.")}Mr.Children={map:Gp,forEach:function(e,t,n){Gp(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return Gp(e,function(){t++}),t},toArray:function(e){return Gp(e,function(t){return t})||[]},only:function(e){if(!k_(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};Mr.Component=tu;Mr.Fragment=DM;Mr.Profiler=RM;Mr.PureComponent=x_;Mr.StrictMode=LM;Mr.Suspense=UM;Mr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=QM;Mr.act=$1;Mr.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var o=T1({},e.props),a=e.key,l=e.ref,f=e._owner;if(t!=null){if(t.ref!==void 0&&(l=t.ref,f=T_.current),t.key!==void 0&&(a=""+t.key),e.type&&e.type.defaultProps)var _=e.type.defaultProps;for(h in t)E1.call(t,h)&&!C1.hasOwnProperty(h)&&(o[h]=t[h]===void 0&&_!==void 0?_[h]:t[h])}var h=arguments.length-2;if(h===1)o.children=n;else if(1<h){_=Array(h);for(var g=0;g<h;g++)_[g]=arguments[g+2];o.children=_}return{$$typeof:Kf,type:e.type,key:a,ref:l,props:o,_owner:f}};Mr.createContext=function(e){return e={$$typeof:NM,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:BM,_context:e},e.Consumer=e};Mr.createElement=P1;Mr.createFactory=function(e){var t=P1.bind(null,e);return t.type=e,t};Mr.createRef=function(){return{current:null}};Mr.forwardRef=function(e){return{$$typeof:jM,render:e}};Mr.isValidElement=k_;Mr.lazy=function(e){return{$$typeof:WM,_payload:{_status:-1,_result:e},_init:KM}};Mr.memo=function(e,t){return{$$typeof:VM,type:e,compare:t===void 0?null:t}};Mr.startTransition=function(e){var t=dh.transition;dh.transition={};try{e()}finally{dh.transition=t}};Mr.unstable_act=$1;Mr.useCallback=function(e,t){return ti.current.useCallback(e,t)};Mr.useContext=function(e){return ti.current.useContext(e)};Mr.useDebugValue=function(){};Mr.useDeferredValue=function(e){return ti.current.useDeferredValue(e)};Mr.useEffect=function(e,t){return ti.current.useEffect(e,t)};Mr.useId=function(){return ti.current.useId()};Mr.useImperativeHandle=function(e,t,n){return ti.current.useImperativeHandle(e,t,n)};Mr.useInsertionEffect=function(e,t){return ti.current.useInsertionEffect(e,t)};Mr.useLayoutEffect=function(e,t){return ti.current.useLayoutEffect(e,t)};Mr.useMemo=function(e,t){return ti.current.useMemo(e,t)};Mr.useReducer=function(e,t,n){return ti.current.useReducer(e,t,n)};Mr.useRef=function(e){return ti.current.useRef(e)};Mr.useState=function(e){return ti.current.useState(e)};Mr.useSyncExternalStore=function(e,t,n){return ti.current.useSyncExternalStore(e,t,n)};Mr.useTransition=function(){return ti.current.useTransition()};Mr.version="18.3.1";x1.exports=Mr;var hr=x1.exports;const XM=b_(hr);/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var YM=hr,ZM=Symbol.for("react.element"),JM=Symbol.for("react.fragment"),eT=Object.prototype.hasOwnProperty,tT=YM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,rT={key:!0,ref:!0,__self:!0,__source:!0};function A1(e,t,n){var o,a={},l=null,f=null;n!==void 0&&(l=""+n),t.key!==void 0&&(l=""+t.key),t.ref!==void 0&&(f=t.ref);for(o in t)eT.call(t,o)&&!rT.hasOwnProperty(o)&&(a[o]=t[o]);if(e&&e.defaultProps)for(o in t=e.defaultProps,t)a[o]===void 0&&(a[o]=t[o]);return{$$typeof:ZM,type:e,key:l,ref:f,props:a,_owner:tT.current}}Xh.Fragment=JM;Xh.jsx=A1;Xh.jsxs=A1;b1.exports=Xh;var Vr=b1.exports,I1={exports:{}},wi={},F1={exports:{}},z1={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(e){function t(Q,ae){var Se=Q.length;Q.push(ae);e:for(;0<Se;){var X=Se-1>>>1,me=Q[X];if(0<a(me,ae))Q[X]=ae,Q[Se]=me,Se=X;else break e}}function n(Q){return Q.length===0?null:Q[0]}function o(Q){if(Q.length===0)return null;var ae=Q[0],Se=Q.pop();if(Se!==ae){Q[0]=Se;e:for(var X=0,me=Q.length,Ke=me>>>1;X<Ke;){var De=2*(X+1)-1,Be=Q[De],We=De+1,ot=Q[We];if(0>a(Be,Se))We<me&&0>a(ot,Be)?(Q[X]=ot,Q[We]=Se,X=We):(Q[X]=Be,Q[De]=Se,X=De);else if(We<me&&0>a(ot,Se))Q[X]=ot,Q[We]=Se,X=We;else break e}}return ae}function a(Q,ae){var Se=Q.sortIndex-ae.sortIndex;return Se!==0?Se:Q.id-ae.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var f=Date,_=f.now();e.unstable_now=function(){return f.now()-_}}var h=[],g=[],M=1,w=null,C=3,k=!1,z=!1,S=!1,P=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function I(Q){for(var ae=n(g);ae!==null;){if(ae.callback===null)o(g);else if(ae.startTime<=Q)o(g),ae.sortIndex=ae.expirationTime,t(h,ae);else break;ae=n(g)}}function U(Q){if(S=!1,I(Q),!z)if(n(h)!==null)z=!0,Qe(O);else{var ae=n(g);ae!==null&&ge(U,ae.startTime-Q)}}function O(Q,ae){z=!1,S&&(S=!1,y(D),D=-1),k=!0;var Se=C;try{for(I(ae),w=n(h);w!==null&&(!(w.expirationTime>ae)||Q&&!Ce());){var X=w.callback;if(typeof X=="function"){w.callback=null,C=w.priorityLevel;var me=X(w.expirationTime<=ae);ae=e.unstable_now(),typeof me=="function"?w.callback=me:w===n(h)&&o(h),I(ae)}else o(h);w=n(h)}if(w!==null)var Ke=!0;else{var De=n(g);De!==null&&ge(U,De.startTime-ae),Ke=!1}return Ke}finally{w=null,C=Se,k=!1}}var N=!1,j=null,D=-1,Y=5,de=-1;function Ce(){return!(e.unstable_now()-de<Y)}function ee(){if(j!==null){var Q=e.unstable_now();de=Q;var ae=!0;try{ae=j(!0,Q)}finally{ae?ye():(N=!1,j=null)}}else N=!1}var ye;if(typeof x=="function")ye=function(){x(ee)};else if(typeof MessageChannel<"u"){var R=new MessageChannel,Me=R.port2;R.port1.onmessage=ee,ye=function(){Me.postMessage(null)}}else ye=function(){P(ee,0)};function Qe(Q){j=Q,N||(N=!0,ye())}function ge(Q,ae){D=P(function(){Q(e.unstable_now())},ae)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(Q){Q.callback=null},e.unstable_continueExecution=function(){z||k||(z=!0,Qe(O))},e.unstable_forceFrameRate=function(Q){0>Q||125<Q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Y=0<Q?Math.floor(1e3/Q):5},e.unstable_getCurrentPriorityLevel=function(){return C},e.unstable_getFirstCallbackNode=function(){return n(h)},e.unstable_next=function(Q){switch(C){case 1:case 2:case 3:var ae=3;break;default:ae=C}var Se=C;C=ae;try{return Q()}finally{C=Se}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(Q,ae){switch(Q){case 1:case 2:case 3:case 4:case 5:break;default:Q=3}var Se=C;C=Q;try{return ae()}finally{C=Se}},e.unstable_scheduleCallback=function(Q,ae,Se){var X=e.unstable_now();switch(typeof Se=="object"&&Se!==null?(Se=Se.delay,Se=typeof Se=="number"&&0<Se?X+Se:X):Se=X,Q){case 1:var me=-1;break;case 2:me=250;break;case 5:me=1073741823;break;case 4:me=1e4;break;default:me=5e3}return me=Se+me,Q={id:M++,callback:ae,priorityLevel:Q,startTime:Se,expirationTime:me,sortIndex:-1},Se>X?(Q.sortIndex=Se,t(g,Q),n(h)===null&&Q===n(g)&&(S?(y(D),D=-1):S=!0,ge(U,Se-X))):(Q.sortIndex=me,t(h,Q),z||k||(z=!0,Qe(O))),Q},e.unstable_shouldYield=Ce,e.unstable_wrapCallback=function(Q){var ae=C;return function(){var Se=C;C=ae;try{return Q.apply(this,arguments)}finally{C=Se}}}})(z1);F1.exports=z1;var nT=F1.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var iT=hr,yi=nT;function bt(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var O1=new Set,$f={};function ua(e,t){Kl(e,t),Kl(e+"Capture",t)}function Kl(e,t){for($f[e]=t,e=0;e<t.length;e++)O1.add(t[e])}var $o=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Tg=Object.prototype.hasOwnProperty,oT=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,tv={},rv={};function sT(e){return Tg.call(rv,e)?!0:Tg.call(tv,e)?!1:oT.test(e)?rv[e]=!0:(tv[e]=!0,!1)}function aT(e,t,n,o){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function lT(e,t,n,o){if(t===null||typeof t>"u"||aT(e,t,n,o))return!0;if(o)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ri(e,t,n,o,a,l,f){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=f}var Ln={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ln[e]=new ri(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ln[t]=new ri(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ln[e]=new ri(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ln[e]=new ri(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ln[e]=new ri(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ln[e]=new ri(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ln[e]=new ri(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ln[e]=new ri(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ln[e]=new ri(e,5,!1,e.toLowerCase(),null,!1,!1)});var S_=/[\-:]([a-z])/g;function E_(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(S_,E_);Ln[t]=new ri(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(S_,E_);Ln[t]=new ri(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(S_,E_);Ln[t]=new ri(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ln[e]=new ri(e,1,!1,e.toLowerCase(),null,!1,!1)});Ln.xlinkHref=new ri("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ln[e]=new ri(e,1,!1,e.toLowerCase(),null,!0,!0)});function C_(e,t,n,o){var a=Ln.hasOwnProperty(t)?Ln[t]:null;(a!==null?a.type!==0:o||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(lT(t,n,a,o)&&(n=null),o||a===null?sT(t)&&(n===null?e.removeAttribute(t):e.setAttribute(t,""+n)):a.mustUseProperty?e[a.propertyName]=n===null?a.type===3?!1:"":n:(t=a.attributeName,o=a.attributeNamespace,n===null?e.removeAttribute(t):(a=a.type,n=a===3||a===4&&n===!0?"":""+n,o?e.setAttributeNS(o,t,n):e.setAttribute(t,n))))}var zo=iT.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,qp=Symbol.for("react.element"),$l=Symbol.for("react.portal"),Al=Symbol.for("react.fragment"),P_=Symbol.for("react.strict_mode"),kg=Symbol.for("react.profiler"),D1=Symbol.for("react.provider"),L1=Symbol.for("react.context"),$_=Symbol.for("react.forward_ref"),Sg=Symbol.for("react.suspense"),Eg=Symbol.for("react.suspense_list"),A_=Symbol.for("react.memo"),ss=Symbol.for("react.lazy"),R1=Symbol.for("react.offscreen"),nv=Symbol.iterator;function lf(e){return e===null||typeof e!="object"?null:(e=nv&&e[nv]||e["@@iterator"],typeof e=="function"?e:null)}var on=Object.assign,Zm;function gf(e){if(Zm===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);Zm=t&&t[1]||""}return` +`+Zm+e}var Jm=!1;function eg(e,t){if(!e||Jm)return"";Jm=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(g){var o=g}Reflect.construct(e,[],t)}else{try{t.call()}catch(g){o=g}e.call(t.prototype)}else{try{throw Error()}catch(g){o=g}e()}}catch(g){if(g&&o&&typeof g.stack=="string"){for(var a=g.stack.split(` +`),l=o.stack.split(` +`),f=a.length-1,_=l.length-1;1<=f&&0<=_&&a[f]!==l[_];)_--;for(;1<=f&&0<=_;f--,_--)if(a[f]!==l[_]){if(f!==1||_!==1)do if(f--,_--,0>_||a[f]!==l[_]){var h=` +`+a[f].replace(" at new "," at ");return e.displayName&&h.includes("<anonymous>")&&(h=h.replace("<anonymous>",e.displayName)),h}while(1<=f&&0<=_);break}}}finally{Jm=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?gf(e):""}function uT(e){switch(e.tag){case 5:return gf(e.type);case 16:return gf("Lazy");case 13:return gf("Suspense");case 19:return gf("SuspenseList");case 0:case 2:case 15:return e=eg(e.type,!1),e;case 11:return e=eg(e.type.render,!1),e;case 1:return e=eg(e.type,!0),e;default:return""}}function Cg(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Al:return"Fragment";case $l:return"Portal";case kg:return"Profiler";case P_:return"StrictMode";case Sg:return"Suspense";case Eg:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case L1:return(e.displayName||"Context")+".Consumer";case D1:return(e._context.displayName||"Context")+".Provider";case $_:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case A_:return t=e.displayName||null,t!==null?t:Cg(e.type)||"Memo";case ss:t=e._payload,e=e._init;try{return Cg(e(t))}catch{}}return null}function cT(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Cg(t);case 8:return t===P_?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function vs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function B1(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function dT(e){var t=B1(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,l=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(f){o=""+f,l.call(this,f)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return o},setValue:function(f){o=""+f},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Hp(e){e._valueTracker||(e._valueTracker=dT(e))}function N1(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),o="";return e&&(o=B1(e)?e.checked?"true":"false":e.value),e=o,e!==n?(t.setValue(e),!0):!1}function Mh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Pg(e,t){var n=t.checked;return on({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function iv(e,t){var n=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;n=vs(t.value!=null?t.value:n),e._wrapperState={initialChecked:o,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function j1(e,t){t=t.checked,t!=null&&C_(e,"checked",t,!1)}function $g(e,t){j1(e,t);var n=vs(t.value),o=t.type;if(n!=null)o==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ag(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ag(e,t.type,vs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ov(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var o=t.type;if(!(o!=="submit"&&o!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ag(e,t,n){(t!=="number"||Mh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var _f=Array.isArray;function Ul(e,t,n,o){if(e=e.options,t){t={};for(var a=0;a<n.length;a++)t["$"+n[a]]=!0;for(n=0;n<e.length;n++)a=t.hasOwnProperty("$"+e[n].value),e[n].selected!==a&&(e[n].selected=a),a&&o&&(e[n].defaultSelected=!0)}else{for(n=""+vs(n),t=null,a=0;a<e.length;a++){if(e[a].value===n){e[a].selected=!0,o&&(e[a].defaultSelected=!0);return}t!==null||e[a].disabled||(t=e[a])}t!==null&&(t.selected=!0)}}function Ig(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(bt(91));return on({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function sv(e,t){var n=t.value;if(n==null){if(n=t.children,t=t.defaultValue,n!=null){if(t!=null)throw Error(bt(92));if(_f(n)){if(1<n.length)throw Error(bt(93));n=n[0]}t=n}t==null&&(t=""),n=t}e._wrapperState={initialValue:vs(n)}}function U1(e,t){var n=vs(t.value),o=vs(t.defaultValue);n!=null&&(n=""+n,n!==e.value&&(e.value=n),t.defaultValue==null&&e.defaultValue!==n&&(e.defaultValue=n)),o!=null&&(e.defaultValue=""+o)}function av(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function V1(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Fg(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?V1(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var Kp,W1=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,n,o,a){MSApp.execUnsafeLocalFunction(function(){return e(t,n,o,a)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(Kp=Kp||document.createElement("div"),Kp.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=Kp.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Af(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var bf={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},fT=["Webkit","ms","Moz","O"];Object.keys(bf).forEach(function(e){fT.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),bf[t]=bf[e]})});function G1(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||bf.hasOwnProperty(e)&&bf[e]?(""+t).trim():t+"px"}function q1(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var o=n.indexOf("--")===0,a=G1(n,t[n],o);n==="float"&&(n="cssFloat"),o?e.setProperty(n,a):e[n]=a}}var pT=on({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function zg(e,t){if(t){if(pT[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(bt(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(bt(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(bt(61))}if(t.style!=null&&typeof t.style!="object")throw Error(bt(62))}}function Og(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Dg=null;function I_(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Lg=null,Vl=null,Wl=null;function lv(e){if(e=Yf(e)){if(typeof Lg!="function")throw Error(bt(280));var t=e.stateNode;t&&(t=tm(t),Lg(e.stateNode,e.type,t))}}function H1(e){Vl?Wl?Wl.push(e):Wl=[e]:Vl=e}function K1(){if(Vl){var e=Vl,t=Wl;if(Wl=Vl=null,lv(e),t)for(e=0;e<t.length;e++)lv(t[e])}}function Q1(e,t){return e(t)}function X1(){}var tg=!1;function Y1(e,t,n){if(tg)return e(t,n);tg=!0;try{return Q1(e,t,n)}finally{tg=!1,(Vl!==null||Wl!==null)&&(X1(),K1())}}function If(e,t){var n=e.stateNode;if(n===null)return null;var o=tm(n);if(o===null)return null;n=o[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(o=!o.disabled)||(e=e.type,o=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!o;break e;default:e=!1}if(e)return null;if(n&&typeof n!="function")throw Error(bt(231,t,typeof n));return n}var Rg=!1;if($o)try{var uf={};Object.defineProperty(uf,"passive",{get:function(){Rg=!0}}),window.addEventListener("test",uf,uf),window.removeEventListener("test",uf,uf)}catch{Rg=!1}function hT(e,t,n,o,a,l,f,_,h){var g=Array.prototype.slice.call(arguments,3);try{t.apply(n,g)}catch(M){this.onError(M)}}var xf=!1,Th=null,kh=!1,Bg=null,mT={onError:function(e){xf=!0,Th=e}};function gT(e,t,n,o,a,l,f,_,h){xf=!1,Th=null,hT.apply(mT,arguments)}function _T(e,t,n,o,a,l,f,_,h){if(gT.apply(this,arguments),xf){if(xf){var g=Th;xf=!1,Th=null}else throw Error(bt(198));kh||(kh=!0,Bg=g)}}function ca(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function Z1(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function uv(e){if(ca(e)!==e)throw Error(bt(188))}function yT(e){var t=e.alternate;if(!t){if(t=ca(e),t===null)throw Error(bt(188));return t!==e?null:e}for(var n=e,o=t;;){var a=n.return;if(a===null)break;var l=a.alternate;if(l===null){if(o=a.return,o!==null){n=o;continue}break}if(a.child===l.child){for(l=a.child;l;){if(l===n)return uv(a),e;if(l===o)return uv(a),t;l=l.sibling}throw Error(bt(188))}if(n.return!==o.return)n=a,o=l;else{for(var f=!1,_=a.child;_;){if(_===n){f=!0,n=a,o=l;break}if(_===o){f=!0,o=a,n=l;break}_=_.sibling}if(!f){for(_=l.child;_;){if(_===n){f=!0,n=l,o=a;break}if(_===o){f=!0,o=l,n=a;break}_=_.sibling}if(!f)throw Error(bt(189))}}if(n.alternate!==o)throw Error(bt(190))}if(n.tag!==3)throw Error(bt(188));return n.stateNode.current===n?e:t}function J1(e){return e=yT(e),e!==null?eb(e):null}function eb(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=eb(e);if(t!==null)return t;e=e.sibling}return null}var tb=yi.unstable_scheduleCallback,cv=yi.unstable_cancelCallback,wT=yi.unstable_shouldYield,vT=yi.unstable_requestPaint,fn=yi.unstable_now,bT=yi.unstable_getCurrentPriorityLevel,F_=yi.unstable_ImmediatePriority,rb=yi.unstable_UserBlockingPriority,Sh=yi.unstable_NormalPriority,xT=yi.unstable_LowPriority,nb=yi.unstable_IdlePriority,Yh=null,lo=null;function MT(e){if(lo&&typeof lo.onCommitFiberRoot=="function")try{lo.onCommitFiberRoot(Yh,e,void 0,(e.current.flags&128)===128)}catch{}}var Ki=Math.clz32?Math.clz32:ST,TT=Math.log,kT=Math.LN2;function ST(e){return e>>>=0,e===0?32:31-(TT(e)/kT|0)|0}var Qp=64,Xp=4194304;function yf(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Eh(e,t){var n=e.pendingLanes;if(n===0)return 0;var o=0,a=e.suspendedLanes,l=e.pingedLanes,f=n&268435455;if(f!==0){var _=f&~a;_!==0?o=yf(_):(l&=f,l!==0&&(o=yf(l)))}else f=n&~a,f!==0?o=yf(f):l!==0&&(o=yf(l));if(o===0)return 0;if(t!==0&&t!==o&&!(t&a)&&(a=o&-o,l=t&-t,a>=l||a===16&&(l&4194240)!==0))return t;if(o&4&&(o|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0<t;)n=31-Ki(t),a=1<<n,o|=e[n],t&=~a;return o}function ET(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function CT(e,t){for(var n=e.suspendedLanes,o=e.pingedLanes,a=e.expirationTimes,l=e.pendingLanes;0<l;){var f=31-Ki(l),_=1<<f,h=a[f];h===-1?(!(_&n)||_&o)&&(a[f]=ET(_,t)):h<=t&&(e.expiredLanes|=_),l&=~_}}function Ng(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function ib(){var e=Qp;return Qp<<=1,!(Qp&4194240)&&(Qp=64),e}function rg(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Qf(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ki(t),e[t]=n}function PT(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var o=e.eventTimes;for(e=e.expirationTimes;0<n;){var a=31-Ki(n),l=1<<a;t[a]=0,o[a]=-1,e[a]=-1,n&=~l}}function z_(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var o=31-Ki(n),a=1<<o;a&t|e[o]&t&&(e[o]|=t),n&=~a}}var Rr=0;function ob(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var sb,O_,ab,lb,ub,jg=!1,Yp=[],fs=null,ps=null,hs=null,Ff=new Map,zf=new Map,ls=[],$T="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function dv(e,t){switch(e){case"focusin":case"focusout":fs=null;break;case"dragenter":case"dragleave":ps=null;break;case"mouseover":case"mouseout":hs=null;break;case"pointerover":case"pointerout":Ff.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":zf.delete(t.pointerId)}}function cf(e,t,n,o,a,l){return e===null||e.nativeEvent!==l?(e={blockedOn:t,domEventName:n,eventSystemFlags:o,nativeEvent:l,targetContainers:[a]},t!==null&&(t=Yf(t),t!==null&&O_(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,a!==null&&t.indexOf(a)===-1&&t.push(a),e)}function AT(e,t,n,o,a){switch(t){case"focusin":return fs=cf(fs,e,t,n,o,a),!0;case"dragenter":return ps=cf(ps,e,t,n,o,a),!0;case"mouseover":return hs=cf(hs,e,t,n,o,a),!0;case"pointerover":var l=a.pointerId;return Ff.set(l,cf(Ff.get(l)||null,e,t,n,o,a)),!0;case"gotpointercapture":return l=a.pointerId,zf.set(l,cf(zf.get(l)||null,e,t,n,o,a)),!0}return!1}function cb(e){var t=Js(e.target);if(t!==null){var n=ca(t);if(n!==null){if(t=n.tag,t===13){if(t=Z1(n),t!==null){e.blockedOn=t,ub(e.priority,function(){ab(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function fh(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=Ug(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(n===null){n=e.nativeEvent;var o=new n.constructor(n.type,n);Dg=o,n.target.dispatchEvent(o),Dg=null}else return t=Yf(n),t!==null&&O_(t),e.blockedOn=n,!1;t.shift()}return!0}function fv(e,t,n){fh(e)&&n.delete(t)}function IT(){jg=!1,fs!==null&&fh(fs)&&(fs=null),ps!==null&&fh(ps)&&(ps=null),hs!==null&&fh(hs)&&(hs=null),Ff.forEach(fv),zf.forEach(fv)}function df(e,t){e.blockedOn===t&&(e.blockedOn=null,jg||(jg=!0,yi.unstable_scheduleCallback(yi.unstable_NormalPriority,IT)))}function Of(e){function t(a){return df(a,e)}if(0<Yp.length){df(Yp[0],e);for(var n=1;n<Yp.length;n++){var o=Yp[n];o.blockedOn===e&&(o.blockedOn=null)}}for(fs!==null&&df(fs,e),ps!==null&&df(ps,e),hs!==null&&df(hs,e),Ff.forEach(t),zf.forEach(t),n=0;n<ls.length;n++)o=ls[n],o.blockedOn===e&&(o.blockedOn=null);for(;0<ls.length&&(n=ls[0],n.blockedOn===null);)cb(n),n.blockedOn===null&&ls.shift()}var Gl=zo.ReactCurrentBatchConfig,Ch=!0;function FT(e,t,n,o){var a=Rr,l=Gl.transition;Gl.transition=null;try{Rr=1,D_(e,t,n,o)}finally{Rr=a,Gl.transition=l}}function zT(e,t,n,o){var a=Rr,l=Gl.transition;Gl.transition=null;try{Rr=4,D_(e,t,n,o)}finally{Rr=a,Gl.transition=l}}function D_(e,t,n,o){if(Ch){var a=Ug(e,t,n,o);if(a===null)fg(e,t,o,Ph,n),dv(e,o);else if(AT(a,e,t,n,o))o.stopPropagation();else if(dv(e,o),t&4&&-1<$T.indexOf(e)){for(;a!==null;){var l=Yf(a);if(l!==null&&sb(l),l=Ug(e,t,n,o),l===null&&fg(e,t,o,Ph,n),l===a)break;a=l}a!==null&&o.stopPropagation()}else fg(e,t,o,null,n)}}var Ph=null;function Ug(e,t,n,o){if(Ph=null,e=I_(o),e=Js(e),e!==null)if(t=ca(e),t===null)e=null;else if(n=t.tag,n===13){if(e=Z1(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Ph=e,null}function db(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(bT()){case F_:return 1;case rb:return 4;case Sh:case xT:return 16;case nb:return 536870912;default:return 16}default:return 16}}var cs=null,L_=null,ph=null;function fb(){if(ph)return ph;var e,t=L_,n=t.length,o,a="value"in cs?cs.value:cs.textContent,l=a.length;for(e=0;e<n&&t[e]===a[e];e++);var f=n-e;for(o=1;o<=f&&t[n-o]===a[l-o];o++);return ph=a.slice(e,1<o?1-o:void 0)}function hh(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Zp(){return!0}function pv(){return!1}function vi(e){function t(n,o,a,l,f){this._reactName=n,this._targetInst=a,this.type=o,this.nativeEvent=l,this.target=f,this.currentTarget=null;for(var _ in e)e.hasOwnProperty(_)&&(n=e[_],this[_]=n?n(l):l[_]);return this.isDefaultPrevented=(l.defaultPrevented!=null?l.defaultPrevented:l.returnValue===!1)?Zp:pv,this.isPropagationStopped=pv,this}return on(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=Zp)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=Zp)},persist:function(){},isPersistent:Zp}),t}var ru={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},R_=vi(ru),Xf=on({},ru,{view:0,detail:0}),OT=vi(Xf),ng,ig,ff,Zh=on({},Xf,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:B_,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==ff&&(ff&&e.type==="mousemove"?(ng=e.screenX-ff.screenX,ig=e.screenY-ff.screenY):ig=ng=0,ff=e),ng)},movementY:function(e){return"movementY"in e?e.movementY:ig}}),hv=vi(Zh),DT=on({},Zh,{dataTransfer:0}),LT=vi(DT),RT=on({},Xf,{relatedTarget:0}),og=vi(RT),BT=on({},ru,{animationName:0,elapsedTime:0,pseudoElement:0}),NT=vi(BT),jT=on({},ru,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),UT=vi(jT),VT=on({},ru,{data:0}),mv=vi(VT),WT={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},GT={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},qT={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function HT(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=qT[e])?!!t[e]:!1}function B_(){return HT}var KT=on({},Xf,{key:function(e){if(e.key){var t=WT[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=hh(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?GT[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:B_,charCode:function(e){return e.type==="keypress"?hh(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?hh(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),QT=vi(KT),XT=on({},Zh,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),gv=vi(XT),YT=on({},Xf,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:B_}),ZT=vi(YT),JT=on({},ru,{propertyName:0,elapsedTime:0,pseudoElement:0}),ek=vi(JT),tk=on({},Zh,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),rk=vi(tk),nk=[9,13,27,32],N_=$o&&"CompositionEvent"in window,Mf=null;$o&&"documentMode"in document&&(Mf=document.documentMode);var ik=$o&&"TextEvent"in window&&!Mf,pb=$o&&(!N_||Mf&&8<Mf&&11>=Mf),_v=" ",yv=!1;function hb(e,t){switch(e){case"keyup":return nk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function mb(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Il=!1;function ok(e,t){switch(e){case"compositionend":return mb(t);case"keypress":return t.which!==32?null:(yv=!0,_v);case"textInput":return e=t.data,e===_v&&yv?null:e;default:return null}}function sk(e,t){if(Il)return e==="compositionend"||!N_&&hb(e,t)?(e=fb(),ph=L_=cs=null,Il=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return pb&&t.locale!=="ko"?null:t.data;default:return null}}var ak={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function wv(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!ak[e.type]:t==="textarea"}function gb(e,t,n,o){H1(o),t=$h(t,"onChange"),0<t.length&&(n=new R_("onChange","change",null,n,o),e.push({event:n,listeners:t}))}var Tf=null,Df=null;function lk(e){Eb(e,0)}function Jh(e){var t=Ol(e);if(N1(t))return e}function uk(e,t){if(e==="change")return t}var _b=!1;if($o){var sg;if($o){var ag="oninput"in document;if(!ag){var vv=document.createElement("div");vv.setAttribute("oninput","return;"),ag=typeof vv.oninput=="function"}sg=ag}else sg=!1;_b=sg&&(!document.documentMode||9<document.documentMode)}function bv(){Tf&&(Tf.detachEvent("onpropertychange",yb),Df=Tf=null)}function yb(e){if(e.propertyName==="value"&&Jh(Df)){var t=[];gb(t,Df,e,I_(e)),Y1(lk,t)}}function ck(e,t,n){e==="focusin"?(bv(),Tf=t,Df=n,Tf.attachEvent("onpropertychange",yb)):e==="focusout"&&bv()}function dk(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Jh(Df)}function fk(e,t){if(e==="click")return Jh(t)}function pk(e,t){if(e==="input"||e==="change")return Jh(t)}function hk(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xi=typeof Object.is=="function"?Object.is:hk;function Lf(e,t){if(Xi(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(o=0;o<n.length;o++){var a=n[o];if(!Tg.call(t,a)||!Xi(e[a],t[a]))return!1}return!0}function xv(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Mv(e,t){var n=xv(e);e=0;for(var o;n;){if(n.nodeType===3){if(o=e+n.textContent.length,e<=t&&o>=t)return{node:n,offset:t-e};e=o}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=xv(n)}}function wb(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wb(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vb(){for(var e=window,t=Mh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Mh(e.document)}return t}function j_(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function mk(e){var t=vb(),n=e.focusedElem,o=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&wb(n.ownerDocument.documentElement,n)){if(o!==null&&j_(n)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=n.textContent.length,l=Math.min(o.start,a);o=o.end===void 0?l:Math.min(o.end,a),!e.extend&&l>o&&(a=o,o=l,l=a),a=Mv(n,l);var f=Mv(n,o);a&&f&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==f.node||e.focusOffset!==f.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),l>o?(e.addRange(t),e.extend(f.node,f.offset)):(t.setEnd(f.node,f.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<t.length;n++)e=t[n],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var gk=$o&&"documentMode"in document&&11>=document.documentMode,Fl=null,Vg=null,kf=null,Wg=!1;function Tv(e,t,n){var o=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Wg||Fl==null||Fl!==Mh(o)||(o=Fl,"selectionStart"in o&&j_(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),kf&&Lf(kf,o)||(kf=o,o=$h(Vg,"onSelect"),0<o.length&&(t=new R_("onSelect","select",null,t,n),e.push({event:t,listeners:o}),t.target=Fl)))}function Jp(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var zl={animationend:Jp("Animation","AnimationEnd"),animationiteration:Jp("Animation","AnimationIteration"),animationstart:Jp("Animation","AnimationStart"),transitionend:Jp("Transition","TransitionEnd")},lg={},bb={};$o&&(bb=document.createElement("div").style,"AnimationEvent"in window||(delete zl.animationend.animation,delete zl.animationiteration.animation,delete zl.animationstart.animation),"TransitionEvent"in window||delete zl.transitionend.transition);function em(e){if(lg[e])return lg[e];if(!zl[e])return e;var t=zl[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in bb)return lg[e]=t[n];return e}var xb=em("animationend"),Mb=em("animationiteration"),Tb=em("animationstart"),kb=em("transitionend"),Sb=new Map,kv="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function xs(e,t){Sb.set(e,t),ua(t,[e])}for(var ug=0;ug<kv.length;ug++){var cg=kv[ug],_k=cg.toLowerCase(),yk=cg[0].toUpperCase()+cg.slice(1);xs(_k,"on"+yk)}xs(xb,"onAnimationEnd");xs(Mb,"onAnimationIteration");xs(Tb,"onAnimationStart");xs("dblclick","onDoubleClick");xs("focusin","onFocus");xs("focusout","onBlur");xs(kb,"onTransitionEnd");Kl("onMouseEnter",["mouseout","mouseover"]);Kl("onMouseLeave",["mouseout","mouseover"]);Kl("onPointerEnter",["pointerout","pointerover"]);Kl("onPointerLeave",["pointerout","pointerover"]);ua("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));ua("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));ua("onBeforeInput",["compositionend","keypress","textInput","paste"]);ua("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));ua("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));ua("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var wf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),wk=new Set("cancel close invalid load scroll toggle".split(" ").concat(wf));function Sv(e,t,n){var o=e.type||"unknown-event";e.currentTarget=n,_T(o,t,void 0,e),e.currentTarget=null}function Eb(e,t){t=(t&4)!==0;for(var n=0;n<e.length;n++){var o=e[n],a=o.event;o=o.listeners;e:{var l=void 0;if(t)for(var f=o.length-1;0<=f;f--){var _=o[f],h=_.instance,g=_.currentTarget;if(_=_.listener,h!==l&&a.isPropagationStopped())break e;Sv(a,_,g),l=h}else for(f=0;f<o.length;f++){if(_=o[f],h=_.instance,g=_.currentTarget,_=_.listener,h!==l&&a.isPropagationStopped())break e;Sv(a,_,g),l=h}}}if(kh)throw e=Bg,kh=!1,Bg=null,e}function Xr(e,t){var n=t[Qg];n===void 0&&(n=t[Qg]=new Set);var o=e+"__bubble";n.has(o)||(Cb(t,e,2,!1),n.add(o))}function dg(e,t,n){var o=0;t&&(o|=4),Cb(n,e,o,t)}var eh="_reactListening"+Math.random().toString(36).slice(2);function Rf(e){if(!e[eh]){e[eh]=!0,O1.forEach(function(n){n!=="selectionchange"&&(wk.has(n)||dg(n,!1,e),dg(n,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[eh]||(t[eh]=!0,dg("selectionchange",!1,t))}}function Cb(e,t,n,o){switch(db(t)){case 1:var a=FT;break;case 4:a=zT;break;default:a=D_}n=a.bind(null,t,n,e),a=void 0,!Rg||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(a=!0),o?a!==void 0?e.addEventListener(t,n,{capture:!0,passive:a}):e.addEventListener(t,n,!0):a!==void 0?e.addEventListener(t,n,{passive:a}):e.addEventListener(t,n,!1)}function fg(e,t,n,o,a){var l=o;if(!(t&1)&&!(t&2)&&o!==null)e:for(;;){if(o===null)return;var f=o.tag;if(f===3||f===4){var _=o.stateNode.containerInfo;if(_===a||_.nodeType===8&&_.parentNode===a)break;if(f===4)for(f=o.return;f!==null;){var h=f.tag;if((h===3||h===4)&&(h=f.stateNode.containerInfo,h===a||h.nodeType===8&&h.parentNode===a))return;f=f.return}for(;_!==null;){if(f=Js(_),f===null)return;if(h=f.tag,h===5||h===6){o=l=f;continue e}_=_.parentNode}}o=o.return}Y1(function(){var g=l,M=I_(n),w=[];e:{var C=Sb.get(e);if(C!==void 0){var k=R_,z=e;switch(e){case"keypress":if(hh(n)===0)break e;case"keydown":case"keyup":k=QT;break;case"focusin":z="focus",k=og;break;case"focusout":z="blur",k=og;break;case"beforeblur":case"afterblur":k=og;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":k=hv;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":k=LT;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":k=ZT;break;case xb:case Mb:case Tb:k=NT;break;case kb:k=ek;break;case"scroll":k=OT;break;case"wheel":k=rk;break;case"copy":case"cut":case"paste":k=UT;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":k=gv}var S=(t&4)!==0,P=!S&&e==="scroll",y=S?C!==null?C+"Capture":null:C;S=[];for(var x=g,I;x!==null;){I=x;var U=I.stateNode;if(I.tag===5&&U!==null&&(I=U,y!==null&&(U=If(x,y),U!=null&&S.push(Bf(x,U,I)))),P)break;x=x.return}0<S.length&&(C=new k(C,z,null,n,M),w.push({event:C,listeners:S}))}}if(!(t&7)){e:{if(C=e==="mouseover"||e==="pointerover",k=e==="mouseout"||e==="pointerout",C&&n!==Dg&&(z=n.relatedTarget||n.fromElement)&&(Js(z)||z[Ao]))break e;if((k||C)&&(C=M.window===M?M:(C=M.ownerDocument)?C.defaultView||C.parentWindow:window,k?(z=n.relatedTarget||n.toElement,k=g,z=z?Js(z):null,z!==null&&(P=ca(z),z!==P||z.tag!==5&&z.tag!==6)&&(z=null)):(k=null,z=g),k!==z)){if(S=hv,U="onMouseLeave",y="onMouseEnter",x="mouse",(e==="pointerout"||e==="pointerover")&&(S=gv,U="onPointerLeave",y="onPointerEnter",x="pointer"),P=k==null?C:Ol(k),I=z==null?C:Ol(z),C=new S(U,x+"leave",k,n,M),C.target=P,C.relatedTarget=I,U=null,Js(M)===g&&(S=new S(y,x+"enter",z,n,M),S.target=I,S.relatedTarget=P,U=S),P=U,k&&z)t:{for(S=k,y=z,x=0,I=S;I;I=Pl(I))x++;for(I=0,U=y;U;U=Pl(U))I++;for(;0<x-I;)S=Pl(S),x--;for(;0<I-x;)y=Pl(y),I--;for(;x--;){if(S===y||y!==null&&S===y.alternate)break t;S=Pl(S),y=Pl(y)}S=null}else S=null;k!==null&&Ev(w,C,k,S,!1),z!==null&&P!==null&&Ev(w,P,z,S,!0)}}e:{if(C=g?Ol(g):window,k=C.nodeName&&C.nodeName.toLowerCase(),k==="select"||k==="input"&&C.type==="file")var O=uk;else if(wv(C))if(_b)O=pk;else{O=dk;var N=ck}else(k=C.nodeName)&&k.toLowerCase()==="input"&&(C.type==="checkbox"||C.type==="radio")&&(O=fk);if(O&&(O=O(e,g))){gb(w,O,n,M);break e}N&&N(e,C,g),e==="focusout"&&(N=C._wrapperState)&&N.controlled&&C.type==="number"&&Ag(C,"number",C.value)}switch(N=g?Ol(g):window,e){case"focusin":(wv(N)||N.contentEditable==="true")&&(Fl=N,Vg=g,kf=null);break;case"focusout":kf=Vg=Fl=null;break;case"mousedown":Wg=!0;break;case"contextmenu":case"mouseup":case"dragend":Wg=!1,Tv(w,n,M);break;case"selectionchange":if(gk)break;case"keydown":case"keyup":Tv(w,n,M)}var j;if(N_)e:{switch(e){case"compositionstart":var D="onCompositionStart";break e;case"compositionend":D="onCompositionEnd";break e;case"compositionupdate":D="onCompositionUpdate";break e}D=void 0}else Il?hb(e,n)&&(D="onCompositionEnd"):e==="keydown"&&n.keyCode===229&&(D="onCompositionStart");D&&(pb&&n.locale!=="ko"&&(Il||D!=="onCompositionStart"?D==="onCompositionEnd"&&Il&&(j=fb()):(cs=M,L_="value"in cs?cs.value:cs.textContent,Il=!0)),N=$h(g,D),0<N.length&&(D=new mv(D,e,null,n,M),w.push({event:D,listeners:N}),j?D.data=j:(j=mb(n),j!==null&&(D.data=j)))),(j=ik?ok(e,n):sk(e,n))&&(g=$h(g,"onBeforeInput"),0<g.length&&(M=new mv("onBeforeInput","beforeinput",null,n,M),w.push({event:M,listeners:g}),M.data=j))}Eb(w,t)})}function Bf(e,t,n){return{instance:e,listener:t,currentTarget:n}}function $h(e,t){for(var n=t+"Capture",o=[];e!==null;){var a=e,l=a.stateNode;a.tag===5&&l!==null&&(a=l,l=If(e,n),l!=null&&o.unshift(Bf(e,l,a)),l=If(e,t),l!=null&&o.push(Bf(e,l,a))),e=e.return}return o}function Pl(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function Ev(e,t,n,o,a){for(var l=t._reactName,f=[];n!==null&&n!==o;){var _=n,h=_.alternate,g=_.stateNode;if(h!==null&&h===o)break;_.tag===5&&g!==null&&(_=g,a?(h=If(n,l),h!=null&&f.unshift(Bf(n,h,_))):a||(h=If(n,l),h!=null&&f.push(Bf(n,h,_)))),n=n.return}f.length!==0&&e.push({event:t,listeners:f})}var vk=/\r\n?/g,bk=/\u0000|\uFFFD/g;function Cv(e){return(typeof e=="string"?e:""+e).replace(vk,` +`).replace(bk,"")}function th(e,t,n){if(t=Cv(t),Cv(e)!==t&&n)throw Error(bt(425))}function Ah(){}var Gg=null,qg=null;function Hg(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Kg=typeof setTimeout=="function"?setTimeout:void 0,xk=typeof clearTimeout=="function"?clearTimeout:void 0,Pv=typeof Promise=="function"?Promise:void 0,Mk=typeof queueMicrotask=="function"?queueMicrotask:typeof Pv<"u"?function(e){return Pv.resolve(null).then(e).catch(Tk)}:Kg;function Tk(e){setTimeout(function(){throw e})}function pg(e,t){var n=t,o=0;do{var a=n.nextSibling;if(e.removeChild(n),a&&a.nodeType===8)if(n=a.data,n==="/$"){if(o===0){e.removeChild(a),Of(t);return}o--}else n!=="$"&&n!=="$?"&&n!=="$!"||o++;n=a}while(n);Of(t)}function ms(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function $v(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var nu=Math.random().toString(36).slice(2),ao="__reactFiber$"+nu,Nf="__reactProps$"+nu,Ao="__reactContainer$"+nu,Qg="__reactEvents$"+nu,kk="__reactListeners$"+nu,Sk="__reactHandles$"+nu;function Js(e){var t=e[ao];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Ao]||n[ao]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=$v(e);e!==null;){if(n=e[ao])return n;e=$v(e)}return t}e=n,n=e.parentNode}return null}function Yf(e){return e=e[ao]||e[Ao],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Ol(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(bt(33))}function tm(e){return e[Nf]||null}var Xg=[],Dl=-1;function Ms(e){return{current:e}}function Zr(e){0>Dl||(e.current=Xg[Dl],Xg[Dl]=null,Dl--)}function Kr(e,t){Dl++,Xg[Dl]=e.current,e.current=t}var bs={},Gn=Ms(bs),ai=Ms(!1),ia=bs;function Ql(e,t){var n=e.type.contextTypes;if(!n)return bs;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},l;for(l in n)a[l]=t[l];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function li(e){return e=e.childContextTypes,e!=null}function Ih(){Zr(ai),Zr(Gn)}function Av(e,t,n){if(Gn.current!==bs)throw Error(bt(168));Kr(Gn,t),Kr(ai,n)}function Pb(e,t,n){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return n;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(bt(108,cT(e)||"Unknown",a));return on({},n,o)}function Fh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||bs,ia=Gn.current,Kr(Gn,e),Kr(ai,ai.current),!0}function Iv(e,t,n){var o=e.stateNode;if(!o)throw Error(bt(169));n?(e=Pb(e,t,ia),o.__reactInternalMemoizedMergedChildContext=e,Zr(ai),Zr(Gn),Kr(Gn,e)):Zr(ai),Kr(ai,n)}var ko=null,rm=!1,hg=!1;function $b(e){ko===null?ko=[e]:ko.push(e)}function Ek(e){rm=!0,$b(e)}function Ts(){if(!hg&&ko!==null){hg=!0;var e=0,t=Rr;try{var n=ko;for(Rr=1;e<n.length;e++){var o=n[e];do o=o(!0);while(o!==null)}ko=null,rm=!1}catch(a){throw ko!==null&&(ko=ko.slice(e+1)),tb(F_,Ts),a}finally{Rr=t,hg=!1}}return null}var Ll=[],Rl=0,zh=null,Oh=0,Ai=[],Ii=0,oa=null,Eo=1,Co="";function Xs(e,t){Ll[Rl++]=Oh,Ll[Rl++]=zh,zh=e,Oh=t}function Ab(e,t,n){Ai[Ii++]=Eo,Ai[Ii++]=Co,Ai[Ii++]=oa,oa=e;var o=Eo;e=Co;var a=32-Ki(o)-1;o&=~(1<<a),n+=1;var l=32-Ki(t)+a;if(30<l){var f=a-a%5;l=(o&(1<<f)-1).toString(32),o>>=f,a-=f,Eo=1<<32-Ki(t)+a|n<<a|o,Co=l+e}else Eo=1<<l|n<<a|o,Co=e}function U_(e){e.return!==null&&(Xs(e,1),Ab(e,1,0))}function V_(e){for(;e===zh;)zh=Ll[--Rl],Ll[Rl]=null,Oh=Ll[--Rl],Ll[Rl]=null;for(;e===oa;)oa=Ai[--Ii],Ai[Ii]=null,Co=Ai[--Ii],Ai[Ii]=null,Eo=Ai[--Ii],Ai[Ii]=null}var _i=null,gi=null,en=!1,Hi=null;function Ib(e,t){var n=Fi(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function Fv(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,_i=e,gi=ms(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,_i=e,gi=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=oa!==null?{id:Eo,overflow:Co}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=Fi(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,_i=e,gi=null,!0):!1;default:return!1}}function Yg(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Zg(e){if(en){var t=gi;if(t){var n=t;if(!Fv(e,t)){if(Yg(e))throw Error(bt(418));t=ms(n.nextSibling);var o=_i;t&&Fv(e,t)?Ib(o,n):(e.flags=e.flags&-4097|2,en=!1,_i=e)}}else{if(Yg(e))throw Error(bt(418));e.flags=e.flags&-4097|2,en=!1,_i=e}}}function zv(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;_i=e}function rh(e){if(e!==_i)return!1;if(!en)return zv(e),en=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!Hg(e.type,e.memoizedProps)),t&&(t=gi)){if(Yg(e))throw Fb(),Error(bt(418));for(;t;)Ib(e,t),t=ms(t.nextSibling)}if(zv(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(bt(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="/$"){if(t===0){gi=ms(e.nextSibling);break e}t--}else n!=="$"&&n!=="$!"&&n!=="$?"||t++}e=e.nextSibling}gi=null}}else gi=_i?ms(e.stateNode.nextSibling):null;return!0}function Fb(){for(var e=gi;e;)e=ms(e.nextSibling)}function Xl(){gi=_i=null,en=!1}function W_(e){Hi===null?Hi=[e]:Hi.push(e)}var Ck=zo.ReactCurrentBatchConfig;function pf(e,t,n){if(e=n.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(bt(309));var o=n.stateNode}if(!o)throw Error(bt(147,e));var a=o,l=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===l?t.ref:(t=function(f){var _=a.refs;f===null?delete _[l]:_[l]=f},t._stringRef=l,t)}if(typeof e!="string")throw Error(bt(284));if(!n._owner)throw Error(bt(290,e))}return e}function nh(e,t){throw e=Object.prototype.toString.call(t),Error(bt(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Ov(e){var t=e._init;return t(e._payload)}function zb(e){function t(y,x){if(e){var I=y.deletions;I===null?(y.deletions=[x],y.flags|=16):I.push(x)}}function n(y,x){if(!e)return null;for(;x!==null;)t(y,x),x=x.sibling;return null}function o(y,x){for(y=new Map;x!==null;)x.key!==null?y.set(x.key,x):y.set(x.index,x),x=x.sibling;return y}function a(y,x){return y=ws(y,x),y.index=0,y.sibling=null,y}function l(y,x,I){return y.index=I,e?(I=y.alternate,I!==null?(I=I.index,I<x?(y.flags|=2,x):I):(y.flags|=2,x)):(y.flags|=1048576,x)}function f(y){return e&&y.alternate===null&&(y.flags|=2),y}function _(y,x,I,U){return x===null||x.tag!==6?(x=bg(I,y.mode,U),x.return=y,x):(x=a(x,I),x.return=y,x)}function h(y,x,I,U){var O=I.type;return O===Al?M(y,x,I.props.children,U,I.key):x!==null&&(x.elementType===O||typeof O=="object"&&O!==null&&O.$$typeof===ss&&Ov(O)===x.type)?(U=a(x,I.props),U.ref=pf(y,x,I),U.return=y,U):(U=bh(I.type,I.key,I.props,null,y.mode,U),U.ref=pf(y,x,I),U.return=y,U)}function g(y,x,I,U){return x===null||x.tag!==4||x.stateNode.containerInfo!==I.containerInfo||x.stateNode.implementation!==I.implementation?(x=xg(I,y.mode,U),x.return=y,x):(x=a(x,I.children||[]),x.return=y,x)}function M(y,x,I,U,O){return x===null||x.tag!==7?(x=na(I,y.mode,U,O),x.return=y,x):(x=a(x,I),x.return=y,x)}function w(y,x,I){if(typeof x=="string"&&x!==""||typeof x=="number")return x=bg(""+x,y.mode,I),x.return=y,x;if(typeof x=="object"&&x!==null){switch(x.$$typeof){case qp:return I=bh(x.type,x.key,x.props,null,y.mode,I),I.ref=pf(y,null,x),I.return=y,I;case $l:return x=xg(x,y.mode,I),x.return=y,x;case ss:var U=x._init;return w(y,U(x._payload),I)}if(_f(x)||lf(x))return x=na(x,y.mode,I,null),x.return=y,x;nh(y,x)}return null}function C(y,x,I,U){var O=x!==null?x.key:null;if(typeof I=="string"&&I!==""||typeof I=="number")return O!==null?null:_(y,x,""+I,U);if(typeof I=="object"&&I!==null){switch(I.$$typeof){case qp:return I.key===O?h(y,x,I,U):null;case $l:return I.key===O?g(y,x,I,U):null;case ss:return O=I._init,C(y,x,O(I._payload),U)}if(_f(I)||lf(I))return O!==null?null:M(y,x,I,U,null);nh(y,I)}return null}function k(y,x,I,U,O){if(typeof U=="string"&&U!==""||typeof U=="number")return y=y.get(I)||null,_(x,y,""+U,O);if(typeof U=="object"&&U!==null){switch(U.$$typeof){case qp:return y=y.get(U.key===null?I:U.key)||null,h(x,y,U,O);case $l:return y=y.get(U.key===null?I:U.key)||null,g(x,y,U,O);case ss:var N=U._init;return k(y,x,I,N(U._payload),O)}if(_f(U)||lf(U))return y=y.get(I)||null,M(x,y,U,O,null);nh(x,U)}return null}function z(y,x,I,U){for(var O=null,N=null,j=x,D=x=0,Y=null;j!==null&&D<I.length;D++){j.index>D?(Y=j,j=null):Y=j.sibling;var de=C(y,j,I[D],U);if(de===null){j===null&&(j=Y);break}e&&j&&de.alternate===null&&t(y,j),x=l(de,x,D),N===null?O=de:N.sibling=de,N=de,j=Y}if(D===I.length)return n(y,j),en&&Xs(y,D),O;if(j===null){for(;D<I.length;D++)j=w(y,I[D],U),j!==null&&(x=l(j,x,D),N===null?O=j:N.sibling=j,N=j);return en&&Xs(y,D),O}for(j=o(y,j);D<I.length;D++)Y=k(j,y,D,I[D],U),Y!==null&&(e&&Y.alternate!==null&&j.delete(Y.key===null?D:Y.key),x=l(Y,x,D),N===null?O=Y:N.sibling=Y,N=Y);return e&&j.forEach(function(Ce){return t(y,Ce)}),en&&Xs(y,D),O}function S(y,x,I,U){var O=lf(I);if(typeof O!="function")throw Error(bt(150));if(I=O.call(I),I==null)throw Error(bt(151));for(var N=O=null,j=x,D=x=0,Y=null,de=I.next();j!==null&&!de.done;D++,de=I.next()){j.index>D?(Y=j,j=null):Y=j.sibling;var Ce=C(y,j,de.value,U);if(Ce===null){j===null&&(j=Y);break}e&&j&&Ce.alternate===null&&t(y,j),x=l(Ce,x,D),N===null?O=Ce:N.sibling=Ce,N=Ce,j=Y}if(de.done)return n(y,j),en&&Xs(y,D),O;if(j===null){for(;!de.done;D++,de=I.next())de=w(y,de.value,U),de!==null&&(x=l(de,x,D),N===null?O=de:N.sibling=de,N=de);return en&&Xs(y,D),O}for(j=o(y,j);!de.done;D++,de=I.next())de=k(j,y,D,de.value,U),de!==null&&(e&&de.alternate!==null&&j.delete(de.key===null?D:de.key),x=l(de,x,D),N===null?O=de:N.sibling=de,N=de);return e&&j.forEach(function(ee){return t(y,ee)}),en&&Xs(y,D),O}function P(y,x,I,U){if(typeof I=="object"&&I!==null&&I.type===Al&&I.key===null&&(I=I.props.children),typeof I=="object"&&I!==null){switch(I.$$typeof){case qp:e:{for(var O=I.key,N=x;N!==null;){if(N.key===O){if(O=I.type,O===Al){if(N.tag===7){n(y,N.sibling),x=a(N,I.props.children),x.return=y,y=x;break e}}else if(N.elementType===O||typeof O=="object"&&O!==null&&O.$$typeof===ss&&Ov(O)===N.type){n(y,N.sibling),x=a(N,I.props),x.ref=pf(y,N,I),x.return=y,y=x;break e}n(y,N);break}else t(y,N);N=N.sibling}I.type===Al?(x=na(I.props.children,y.mode,U,I.key),x.return=y,y=x):(U=bh(I.type,I.key,I.props,null,y.mode,U),U.ref=pf(y,x,I),U.return=y,y=U)}return f(y);case $l:e:{for(N=I.key;x!==null;){if(x.key===N)if(x.tag===4&&x.stateNode.containerInfo===I.containerInfo&&x.stateNode.implementation===I.implementation){n(y,x.sibling),x=a(x,I.children||[]),x.return=y,y=x;break e}else{n(y,x);break}else t(y,x);x=x.sibling}x=xg(I,y.mode,U),x.return=y,y=x}return f(y);case ss:return N=I._init,P(y,x,N(I._payload),U)}if(_f(I))return z(y,x,I,U);if(lf(I))return S(y,x,I,U);nh(y,I)}return typeof I=="string"&&I!==""||typeof I=="number"?(I=""+I,x!==null&&x.tag===6?(n(y,x.sibling),x=a(x,I),x.return=y,y=x):(n(y,x),x=bg(I,y.mode,U),x.return=y,y=x),f(y)):n(y,x)}return P}var Yl=zb(!0),Ob=zb(!1),Dh=Ms(null),Lh=null,Bl=null,G_=null;function q_(){G_=Bl=Lh=null}function H_(e){var t=Dh.current;Zr(Dh),e._currentValue=t}function Jg(e,t,n){for(;e!==null;){var o=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,o!==null&&(o.childLanes|=t)):o!==null&&(o.childLanes&t)!==t&&(o.childLanes|=t),e===n)break;e=e.return}}function ql(e,t){Lh=e,G_=Bl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(si=!0),e.firstContext=null)}function Oi(e){var t=e._currentValue;if(G_!==e)if(e={context:e,memoizedValue:t,next:null},Bl===null){if(Lh===null)throw Error(bt(308));Bl=e,Lh.dependencies={lanes:0,firstContext:e}}else Bl=Bl.next=e;return t}var ea=null;function K_(e){ea===null?ea=[e]:ea.push(e)}function Db(e,t,n,o){var a=t.interleaved;return a===null?(n.next=n,K_(t)):(n.next=a.next,a.next=n),t.interleaved=n,Io(e,o)}function Io(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var as=!1;function Q_(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Lb(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Po(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gs(e,t,n){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,Ir&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Io(e,n)}return a=o.interleaved,a===null?(t.next=t,K_(o)):(t.next=a.next,a.next=t),o.interleaved=t,Io(e,n)}function mh(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,z_(e,n)}}function Dv(e,t){var n=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,n===o)){var a=null,l=null;if(n=n.firstBaseUpdate,n!==null){do{var f={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};l===null?a=l=f:l=l.next=f,n=n.next}while(n!==null);l===null?a=l=t:l=l.next=t}else a=l=t;n={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:l,shared:o.shared,effects:o.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Rh(e,t,n,o){var a=e.updateQueue;as=!1;var l=a.firstBaseUpdate,f=a.lastBaseUpdate,_=a.shared.pending;if(_!==null){a.shared.pending=null;var h=_,g=h.next;h.next=null,f===null?l=g:f.next=g,f=h;var M=e.alternate;M!==null&&(M=M.updateQueue,_=M.lastBaseUpdate,_!==f&&(_===null?M.firstBaseUpdate=g:_.next=g,M.lastBaseUpdate=h))}if(l!==null){var w=a.baseState;f=0,M=g=h=null,_=l;do{var C=_.lane,k=_.eventTime;if((o&C)===C){M!==null&&(M=M.next={eventTime:k,lane:0,tag:_.tag,payload:_.payload,callback:_.callback,next:null});e:{var z=e,S=_;switch(C=t,k=n,S.tag){case 1:if(z=S.payload,typeof z=="function"){w=z.call(k,w,C);break e}w=z;break e;case 3:z.flags=z.flags&-65537|128;case 0:if(z=S.payload,C=typeof z=="function"?z.call(k,w,C):z,C==null)break e;w=on({},w,C);break e;case 2:as=!0}}_.callback!==null&&_.lane!==0&&(e.flags|=64,C=a.effects,C===null?a.effects=[_]:C.push(_))}else k={eventTime:k,lane:C,tag:_.tag,payload:_.payload,callback:_.callback,next:null},M===null?(g=M=k,h=w):M=M.next=k,f|=C;if(_=_.next,_===null){if(_=a.shared.pending,_===null)break;C=_,_=C.next,C.next=null,a.lastBaseUpdate=C,a.shared.pending=null}}while(!0);if(M===null&&(h=w),a.baseState=h,a.firstBaseUpdate=g,a.lastBaseUpdate=M,t=a.shared.interleaved,t!==null){a=t;do f|=a.lane,a=a.next;while(a!==t)}else l===null&&(a.shared.lanes=0);aa|=f,e.lanes=f,e.memoizedState=w}}function Lv(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var o=e[t],a=o.callback;if(a!==null){if(o.callback=null,o=n,typeof a!="function")throw Error(bt(191,a));a.call(o)}}}var Zf={},uo=Ms(Zf),jf=Ms(Zf),Uf=Ms(Zf);function ta(e){if(e===Zf)throw Error(bt(174));return e}function X_(e,t){switch(Kr(Uf,t),Kr(jf,e),Kr(uo,Zf),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Fg(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Fg(t,e)}Zr(uo),Kr(uo,t)}function Zl(){Zr(uo),Zr(jf),Zr(Uf)}function Rb(e){ta(Uf.current);var t=ta(uo.current),n=Fg(t,e.type);t!==n&&(Kr(jf,e),Kr(uo,n))}function Y_(e){jf.current===e&&(Zr(uo),Zr(jf))}var rn=Ms(0);function Bh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var mg=[];function Z_(){for(var e=0;e<mg.length;e++)mg[e]._workInProgressVersionPrimary=null;mg.length=0}var gh=zo.ReactCurrentDispatcher,gg=zo.ReactCurrentBatchConfig,sa=0,nn=null,Mn=null,Cn=null,Nh=!1,Sf=!1,Vf=0,Pk=0;function Un(){throw Error(bt(321))}function J_(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Xi(e[n],t[n]))return!1;return!0}function e0(e,t,n,o,a,l){if(sa=l,nn=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,gh.current=e===null||e.memoizedState===null?Fk:zk,e=n(o,a),Sf){l=0;do{if(Sf=!1,Vf=0,25<=l)throw Error(bt(301));l+=1,Cn=Mn=null,t.updateQueue=null,gh.current=Ok,e=n(o,a)}while(Sf)}if(gh.current=jh,t=Mn!==null&&Mn.next!==null,sa=0,Cn=Mn=nn=null,Nh=!1,t)throw Error(bt(300));return e}function t0(){var e=Vf!==0;return Vf=0,e}function so(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Cn===null?nn.memoizedState=Cn=e:Cn=Cn.next=e,Cn}function Di(){if(Mn===null){var e=nn.alternate;e=e!==null?e.memoizedState:null}else e=Mn.next;var t=Cn===null?nn.memoizedState:Cn.next;if(t!==null)Cn=t,Mn=e;else{if(e===null)throw Error(bt(310));Mn=e,e={memoizedState:Mn.memoizedState,baseState:Mn.baseState,baseQueue:Mn.baseQueue,queue:Mn.queue,next:null},Cn===null?nn.memoizedState=Cn=e:Cn=Cn.next=e}return Cn}function Wf(e,t){return typeof t=="function"?t(e):t}function _g(e){var t=Di(),n=t.queue;if(n===null)throw Error(bt(311));n.lastRenderedReducer=e;var o=Mn,a=o.baseQueue,l=n.pending;if(l!==null){if(a!==null){var f=a.next;a.next=l.next,l.next=f}o.baseQueue=a=l,n.pending=null}if(a!==null){l=a.next,o=o.baseState;var _=f=null,h=null,g=l;do{var M=g.lane;if((sa&M)===M)h!==null&&(h=h.next={lane:0,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null}),o=g.hasEagerState?g.eagerState:e(o,g.action);else{var w={lane:M,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null};h===null?(_=h=w,f=o):h=h.next=w,nn.lanes|=M,aa|=M}g=g.next}while(g!==null&&g!==l);h===null?f=o:h.next=_,Xi(o,t.memoizedState)||(si=!0),t.memoizedState=o,t.baseState=f,t.baseQueue=h,n.lastRenderedState=o}if(e=n.interleaved,e!==null){a=e;do l=a.lane,nn.lanes|=l,aa|=l,a=a.next;while(a!==e)}else a===null&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function yg(e){var t=Di(),n=t.queue;if(n===null)throw Error(bt(311));n.lastRenderedReducer=e;var o=n.dispatch,a=n.pending,l=t.memoizedState;if(a!==null){n.pending=null;var f=a=a.next;do l=e(l,f.action),f=f.next;while(f!==a);Xi(l,t.memoizedState)||(si=!0),t.memoizedState=l,t.baseQueue===null&&(t.baseState=l),n.lastRenderedState=l}return[l,o]}function Bb(){}function Nb(e,t){var n=nn,o=Di(),a=t(),l=!Xi(o.memoizedState,a);if(l&&(o.memoizedState=a,si=!0),o=o.queue,r0(Vb.bind(null,n,o,e),[e]),o.getSnapshot!==t||l||Cn!==null&&Cn.memoizedState.tag&1){if(n.flags|=2048,Gf(9,Ub.bind(null,n,o,a,t),void 0,null),Pn===null)throw Error(bt(349));sa&30||jb(n,t,a)}return a}function jb(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=nn.updateQueue,t===null?(t={lastEffect:null,stores:null},nn.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function Ub(e,t,n,o){t.value=n,t.getSnapshot=o,Wb(t)&&Gb(e)}function Vb(e,t,n){return n(function(){Wb(t)&&Gb(e)})}function Wb(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Xi(e,n)}catch{return!0}}function Gb(e){var t=Io(e,1);t!==null&&Qi(t,e,1,-1)}function Rv(e){var t=so();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Wf,lastRenderedState:e},t.queue=e,e=e.dispatch=Ik.bind(null,nn,e),[t.memoizedState,e]}function Gf(e,t,n,o){return e={tag:e,create:t,destroy:n,deps:o,next:null},t=nn.updateQueue,t===null?(t={lastEffect:null,stores:null},nn.updateQueue=t,t.lastEffect=e.next=e):(n=t.lastEffect,n===null?t.lastEffect=e.next=e:(o=n.next,n.next=e,e.next=o,t.lastEffect=e)),e}function qb(){return Di().memoizedState}function _h(e,t,n,o){var a=so();nn.flags|=e,a.memoizedState=Gf(1|t,n,void 0,o===void 0?null:o)}function nm(e,t,n,o){var a=Di();o=o===void 0?null:o;var l=void 0;if(Mn!==null){var f=Mn.memoizedState;if(l=f.destroy,o!==null&&J_(o,f.deps)){a.memoizedState=Gf(t,n,l,o);return}}nn.flags|=e,a.memoizedState=Gf(1|t,n,l,o)}function Bv(e,t){return _h(8390656,8,e,t)}function r0(e,t){return nm(2048,8,e,t)}function Hb(e,t){return nm(4,2,e,t)}function Kb(e,t){return nm(4,4,e,t)}function Qb(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Xb(e,t,n){return n=n!=null?n.concat([e]):null,nm(4,4,Qb.bind(null,t,e),n)}function n0(){}function Yb(e,t){var n=Di();t=t===void 0?null:t;var o=n.memoizedState;return o!==null&&t!==null&&J_(t,o[1])?o[0]:(n.memoizedState=[e,t],e)}function Zb(e,t){var n=Di();t=t===void 0?null:t;var o=n.memoizedState;return o!==null&&t!==null&&J_(t,o[1])?o[0]:(e=e(),n.memoizedState=[e,t],e)}function Jb(e,t,n){return sa&21?(Xi(n,t)||(n=ib(),nn.lanes|=n,aa|=n,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,si=!0),e.memoizedState=n)}function $k(e,t){var n=Rr;Rr=n!==0&&4>n?n:4,e(!0);var o=gg.transition;gg.transition={};try{e(!1),t()}finally{Rr=n,gg.transition=o}}function e2(){return Di().memoizedState}function Ak(e,t,n){var o=ys(e);if(n={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null},t2(e))r2(t,n);else if(n=Db(e,t,n,o),n!==null){var a=ei();Qi(n,e,o,a),n2(n,t,o)}}function Ik(e,t,n){var o=ys(e),a={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null};if(t2(e))r2(t,a);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var f=t.lastRenderedState,_=l(f,n);if(a.hasEagerState=!0,a.eagerState=_,Xi(_,f)){var h=t.interleaved;h===null?(a.next=a,K_(t)):(a.next=h.next,h.next=a),t.interleaved=a;return}}catch{}finally{}n=Db(e,t,a,o),n!==null&&(a=ei(),Qi(n,e,o,a),n2(n,t,o))}}function t2(e){var t=e.alternate;return e===nn||t!==null&&t===nn}function r2(e,t){Sf=Nh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function n2(e,t,n){if(n&4194240){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,z_(e,n)}}var jh={readContext:Oi,useCallback:Un,useContext:Un,useEffect:Un,useImperativeHandle:Un,useInsertionEffect:Un,useLayoutEffect:Un,useMemo:Un,useReducer:Un,useRef:Un,useState:Un,useDebugValue:Un,useDeferredValue:Un,useTransition:Un,useMutableSource:Un,useSyncExternalStore:Un,useId:Un,unstable_isNewReconciler:!1},Fk={readContext:Oi,useCallback:function(e,t){return so().memoizedState=[e,t===void 0?null:t],e},useContext:Oi,useEffect:Bv,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,_h(4194308,4,Qb.bind(null,t,e),n)},useLayoutEffect:function(e,t){return _h(4194308,4,e,t)},useInsertionEffect:function(e,t){return _h(4,2,e,t)},useMemo:function(e,t){var n=so();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var o=so();return t=n!==void 0?n(t):t,o.memoizedState=o.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},o.queue=e,e=e.dispatch=Ak.bind(null,nn,e),[o.memoizedState,e]},useRef:function(e){var t=so();return e={current:e},t.memoizedState=e},useState:Rv,useDebugValue:n0,useDeferredValue:function(e){return so().memoizedState=e},useTransition:function(){var e=Rv(!1),t=e[0];return e=$k.bind(null,e[1]),so().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var o=nn,a=so();if(en){if(n===void 0)throw Error(bt(407));n=n()}else{if(n=t(),Pn===null)throw Error(bt(349));sa&30||jb(o,t,n)}a.memoizedState=n;var l={value:n,getSnapshot:t};return a.queue=l,Bv(Vb.bind(null,o,l,e),[e]),o.flags|=2048,Gf(9,Ub.bind(null,o,l,n,t),void 0,null),n},useId:function(){var e=so(),t=Pn.identifierPrefix;if(en){var n=Co,o=Eo;n=(o&~(1<<32-Ki(o)-1)).toString(32)+n,t=":"+t+"R"+n,n=Vf++,0<n&&(t+="H"+n.toString(32)),t+=":"}else n=Pk++,t=":"+t+"r"+n.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},zk={readContext:Oi,useCallback:Yb,useContext:Oi,useEffect:r0,useImperativeHandle:Xb,useInsertionEffect:Hb,useLayoutEffect:Kb,useMemo:Zb,useReducer:_g,useRef:qb,useState:function(){return _g(Wf)},useDebugValue:n0,useDeferredValue:function(e){var t=Di();return Jb(t,Mn.memoizedState,e)},useTransition:function(){var e=_g(Wf)[0],t=Di().memoizedState;return[e,t]},useMutableSource:Bb,useSyncExternalStore:Nb,useId:e2,unstable_isNewReconciler:!1},Ok={readContext:Oi,useCallback:Yb,useContext:Oi,useEffect:r0,useImperativeHandle:Xb,useInsertionEffect:Hb,useLayoutEffect:Kb,useMemo:Zb,useReducer:yg,useRef:qb,useState:function(){return yg(Wf)},useDebugValue:n0,useDeferredValue:function(e){var t=Di();return Mn===null?t.memoizedState=e:Jb(t,Mn.memoizedState,e)},useTransition:function(){var e=yg(Wf)[0],t=Di().memoizedState;return[e,t]},useMutableSource:Bb,useSyncExternalStore:Nb,useId:e2,unstable_isNewReconciler:!1};function Gi(e,t){if(e&&e.defaultProps){t=on({},t),e=e.defaultProps;for(var n in e)t[n]===void 0&&(t[n]=e[n]);return t}return t}function e_(e,t,n,o){t=e.memoizedState,n=n(o,t),n=n==null?t:on({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var im={isMounted:function(e){return(e=e._reactInternals)?ca(e)===e:!1},enqueueSetState:function(e,t,n){e=e._reactInternals;var o=ei(),a=ys(e),l=Po(o,a);l.payload=t,n!=null&&(l.callback=n),t=gs(e,l,a),t!==null&&(Qi(t,e,a,o),mh(t,e,a))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var o=ei(),a=ys(e),l=Po(o,a);l.tag=1,l.payload=t,n!=null&&(l.callback=n),t=gs(e,l,a),t!==null&&(Qi(t,e,a,o),mh(t,e,a))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=ei(),o=ys(e),a=Po(n,o);a.tag=2,t!=null&&(a.callback=t),t=gs(e,a,o),t!==null&&(Qi(t,e,o,n),mh(t,e,o))}};function Nv(e,t,n,o,a,l,f){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,l,f):t.prototype&&t.prototype.isPureReactComponent?!Lf(n,o)||!Lf(a,l):!0}function i2(e,t,n){var o=!1,a=bs,l=t.contextType;return typeof l=="object"&&l!==null?l=Oi(l):(a=li(t)?ia:Gn.current,o=t.contextTypes,l=(o=o!=null)?Ql(e,a):bs),t=new t(n,l),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=im,e.stateNode=t,t._reactInternals=e,o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=a,e.__reactInternalMemoizedMaskedChildContext=l),t}function jv(e,t,n,o){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(n,o),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(n,o),t.state!==e&&im.enqueueReplaceState(t,t.state,null)}function t_(e,t,n,o){var a=e.stateNode;a.props=n,a.state=e.memoizedState,a.refs={},Q_(e);var l=t.contextType;typeof l=="object"&&l!==null?a.context=Oi(l):(l=li(t)?ia:Gn.current,a.context=Ql(e,l)),a.state=e.memoizedState,l=t.getDerivedStateFromProps,typeof l=="function"&&(e_(e,t,l,n),a.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof a.getSnapshotBeforeUpdate=="function"||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(t=a.state,typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount(),t!==a.state&&im.enqueueReplaceState(a,a.state,null),Rh(e,n,a,o),a.state=e.memoizedState),typeof a.componentDidMount=="function"&&(e.flags|=4194308)}function Jl(e,t){try{var n="",o=t;do n+=uT(o),o=o.return;while(o);var a=n}catch(l){a=` +Error generating stack: `+l.message+` +`+l.stack}return{value:e,source:t,stack:a,digest:null}}function wg(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function r_(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var Dk=typeof WeakMap=="function"?WeakMap:Map;function o2(e,t,n){n=Po(-1,n),n.tag=3,n.payload={element:null};var o=t.value;return n.callback=function(){Vh||(Vh=!0,f_=o),r_(e,t)},n}function s2(e,t,n){n=Po(-1,n),n.tag=3;var o=e.type.getDerivedStateFromError;if(typeof o=="function"){var a=t.value;n.payload=function(){return o(a)},n.callback=function(){r_(e,t)}}var l=e.stateNode;return l!==null&&typeof l.componentDidCatch=="function"&&(n.callback=function(){r_(e,t),typeof o!="function"&&(_s===null?_s=new Set([this]):_s.add(this));var f=t.stack;this.componentDidCatch(t.value,{componentStack:f!==null?f:""})}),n}function Uv(e,t,n){var o=e.pingCache;if(o===null){o=e.pingCache=new Dk;var a=new Set;o.set(t,a)}else a=o.get(t),a===void 0&&(a=new Set,o.set(t,a));a.has(n)||(a.add(n),e=Xk.bind(null,e,t,n),t.then(e,e))}function Vv(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Wv(e,t,n,o,a){return e.mode&1?(e.flags|=65536,e.lanes=a,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Po(-1,1),t.tag=2,gs(n,t,1))),n.lanes|=1),e)}var Lk=zo.ReactCurrentOwner,si=!1;function Jn(e,t,n,o){t.child=e===null?Ob(t,null,n,o):Yl(t,e.child,n,o)}function Gv(e,t,n,o,a){n=n.render;var l=t.ref;return ql(t,a),o=e0(e,t,n,o,l,a),n=t0(),e!==null&&!si?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,Fo(e,t,a)):(en&&n&&U_(t),t.flags|=1,Jn(e,t,o,a),t.child)}function qv(e,t,n,o,a){if(e===null){var l=n.type;return typeof l=="function"&&!d0(l)&&l.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=l,a2(e,t,l,o,a)):(e=bh(n.type,null,o,t,t.mode,a),e.ref=t.ref,e.return=t,t.child=e)}if(l=e.child,!(e.lanes&a)){var f=l.memoizedProps;if(n=n.compare,n=n!==null?n:Lf,n(f,o)&&e.ref===t.ref)return Fo(e,t,a)}return t.flags|=1,e=ws(l,o),e.ref=t.ref,e.return=t,t.child=e}function a2(e,t,n,o,a){if(e!==null){var l=e.memoizedProps;if(Lf(l,o)&&e.ref===t.ref)if(si=!1,t.pendingProps=o=l,(e.lanes&a)!==0)e.flags&131072&&(si=!0);else return t.lanes=e.lanes,Fo(e,t,a)}return n_(e,t,n,o,a)}function l2(e,t,n){var o=t.pendingProps,a=o.children,l=e!==null?e.memoizedState:null;if(o.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},Kr(jl,mi),mi|=n;else{if(!(n&1073741824))return e=l!==null?l.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Kr(jl,mi),mi|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},o=l!==null?l.baseLanes:n,Kr(jl,mi),mi|=o}else l!==null?(o=l.baseLanes|n,t.memoizedState=null):o=n,Kr(jl,mi),mi|=o;return Jn(e,t,a,n),t.child}function u2(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function n_(e,t,n,o,a){var l=li(n)?ia:Gn.current;return l=Ql(t,l),ql(t,a),n=e0(e,t,n,o,l,a),o=t0(),e!==null&&!si?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,Fo(e,t,a)):(en&&o&&U_(t),t.flags|=1,Jn(e,t,n,a),t.child)}function Hv(e,t,n,o,a){if(li(n)){var l=!0;Fh(t)}else l=!1;if(ql(t,a),t.stateNode===null)yh(e,t),i2(t,n,o),t_(t,n,o,a),o=!0;else if(e===null){var f=t.stateNode,_=t.memoizedProps;f.props=_;var h=f.context,g=n.contextType;typeof g=="object"&&g!==null?g=Oi(g):(g=li(n)?ia:Gn.current,g=Ql(t,g));var M=n.getDerivedStateFromProps,w=typeof M=="function"||typeof f.getSnapshotBeforeUpdate=="function";w||typeof f.UNSAFE_componentWillReceiveProps!="function"&&typeof f.componentWillReceiveProps!="function"||(_!==o||h!==g)&&jv(t,f,o,g),as=!1;var C=t.memoizedState;f.state=C,Rh(t,o,f,a),h=t.memoizedState,_!==o||C!==h||ai.current||as?(typeof M=="function"&&(e_(t,n,M,o),h=t.memoizedState),(_=as||Nv(t,n,_,o,C,h,g))?(w||typeof f.UNSAFE_componentWillMount!="function"&&typeof f.componentWillMount!="function"||(typeof f.componentWillMount=="function"&&f.componentWillMount(),typeof f.UNSAFE_componentWillMount=="function"&&f.UNSAFE_componentWillMount()),typeof f.componentDidMount=="function"&&(t.flags|=4194308)):(typeof f.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=h),f.props=o,f.state=h,f.context=g,o=_):(typeof f.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{f=t.stateNode,Lb(e,t),_=t.memoizedProps,g=t.type===t.elementType?_:Gi(t.type,_),f.props=g,w=t.pendingProps,C=f.context,h=n.contextType,typeof h=="object"&&h!==null?h=Oi(h):(h=li(n)?ia:Gn.current,h=Ql(t,h));var k=n.getDerivedStateFromProps;(M=typeof k=="function"||typeof f.getSnapshotBeforeUpdate=="function")||typeof f.UNSAFE_componentWillReceiveProps!="function"&&typeof f.componentWillReceiveProps!="function"||(_!==w||C!==h)&&jv(t,f,o,h),as=!1,C=t.memoizedState,f.state=C,Rh(t,o,f,a);var z=t.memoizedState;_!==w||C!==z||ai.current||as?(typeof k=="function"&&(e_(t,n,k,o),z=t.memoizedState),(g=as||Nv(t,n,g,o,C,z,h)||!1)?(M||typeof f.UNSAFE_componentWillUpdate!="function"&&typeof f.componentWillUpdate!="function"||(typeof f.componentWillUpdate=="function"&&f.componentWillUpdate(o,z,h),typeof f.UNSAFE_componentWillUpdate=="function"&&f.UNSAFE_componentWillUpdate(o,z,h)),typeof f.componentDidUpdate=="function"&&(t.flags|=4),typeof f.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof f.componentDidUpdate!="function"||_===e.memoizedProps&&C===e.memoizedState||(t.flags|=4),typeof f.getSnapshotBeforeUpdate!="function"||_===e.memoizedProps&&C===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=z),f.props=o,f.state=z,f.context=h,o=g):(typeof f.componentDidUpdate!="function"||_===e.memoizedProps&&C===e.memoizedState||(t.flags|=4),typeof f.getSnapshotBeforeUpdate!="function"||_===e.memoizedProps&&C===e.memoizedState||(t.flags|=1024),o=!1)}return i_(e,t,n,o,l,a)}function i_(e,t,n,o,a,l){u2(e,t);var f=(t.flags&128)!==0;if(!o&&!f)return a&&Iv(t,n,!1),Fo(e,t,l);o=t.stateNode,Lk.current=t;var _=f&&typeof n.getDerivedStateFromError!="function"?null:o.render();return t.flags|=1,e!==null&&f?(t.child=Yl(t,e.child,null,l),t.child=Yl(t,null,_,l)):Jn(e,t,_,l),t.memoizedState=o.state,a&&Iv(t,n,!0),t.child}function c2(e){var t=e.stateNode;t.pendingContext?Av(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Av(e,t.context,!1),X_(e,t.containerInfo)}function Kv(e,t,n,o,a){return Xl(),W_(a),t.flags|=256,Jn(e,t,n,o),t.child}var o_={dehydrated:null,treeContext:null,retryLane:0};function s_(e){return{baseLanes:e,cachePool:null,transitions:null}}function d2(e,t,n){var o=t.pendingProps,a=rn.current,l=!1,f=(t.flags&128)!==0,_;if((_=f)||(_=e!==null&&e.memoizedState===null?!1:(a&2)!==0),_?(l=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(a|=1),Kr(rn,a&1),e===null)return Zg(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(f=o.children,e=o.fallback,l?(o=t.mode,l=t.child,f={mode:"hidden",children:f},!(o&1)&&l!==null?(l.childLanes=0,l.pendingProps=f):l=am(f,o,0,null),e=na(e,o,n,null),l.return=t,e.return=t,l.sibling=e,t.child=l,t.child.memoizedState=s_(n),t.memoizedState=o_,e):i0(t,f));if(a=e.memoizedState,a!==null&&(_=a.dehydrated,_!==null))return Rk(e,t,f,o,_,a,n);if(l){l=o.fallback,f=t.mode,a=e.child,_=a.sibling;var h={mode:"hidden",children:o.children};return!(f&1)&&t.child!==a?(o=t.child,o.childLanes=0,o.pendingProps=h,t.deletions=null):(o=ws(a,h),o.subtreeFlags=a.subtreeFlags&14680064),_!==null?l=ws(_,l):(l=na(l,f,n,null),l.flags|=2),l.return=t,o.return=t,o.sibling=l,t.child=o,o=l,l=t.child,f=e.child.memoizedState,f=f===null?s_(n):{baseLanes:f.baseLanes|n,cachePool:null,transitions:f.transitions},l.memoizedState=f,l.childLanes=e.childLanes&~n,t.memoizedState=o_,o}return l=e.child,e=l.sibling,o=ws(l,{mode:"visible",children:o.children}),!(t.mode&1)&&(o.lanes=n),o.return=t,o.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=o,t.memoizedState=null,o}function i0(e,t){return t=am({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function ih(e,t,n,o){return o!==null&&W_(o),Yl(t,e.child,null,n),e=i0(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Rk(e,t,n,o,a,l,f){if(n)return t.flags&256?(t.flags&=-257,o=wg(Error(bt(422))),ih(e,t,f,o)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(l=o.fallback,a=t.mode,o=am({mode:"visible",children:o.children},a,0,null),l=na(l,a,f,null),l.flags|=2,o.return=t,l.return=t,o.sibling=l,t.child=o,t.mode&1&&Yl(t,e.child,null,f),t.child.memoizedState=s_(f),t.memoizedState=o_,l);if(!(t.mode&1))return ih(e,t,f,null);if(a.data==="$!"){if(o=a.nextSibling&&a.nextSibling.dataset,o)var _=o.dgst;return o=_,l=Error(bt(419)),o=wg(l,o,void 0),ih(e,t,f,o)}if(_=(f&e.childLanes)!==0,si||_){if(o=Pn,o!==null){switch(f&-f){case 4:a=2;break;case 16:a=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}a=a&(o.suspendedLanes|f)?0:a,a!==0&&a!==l.retryLane&&(l.retryLane=a,Io(e,a),Qi(o,e,a,-1))}return c0(),o=wg(Error(bt(421))),ih(e,t,f,o)}return a.data==="$?"?(t.flags|=128,t.child=e.child,t=Yk.bind(null,e),a._reactRetry=t,null):(e=l.treeContext,gi=ms(a.nextSibling),_i=t,en=!0,Hi=null,e!==null&&(Ai[Ii++]=Eo,Ai[Ii++]=Co,Ai[Ii++]=oa,Eo=e.id,Co=e.overflow,oa=t),t=i0(t,o.children),t.flags|=4096,t)}function Qv(e,t,n){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),Jg(e.return,t,n)}function vg(e,t,n,o,a){var l=e.memoizedState;l===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:n,tailMode:a}:(l.isBackwards=t,l.rendering=null,l.renderingStartTime=0,l.last=o,l.tail=n,l.tailMode=a)}function f2(e,t,n){var o=t.pendingProps,a=o.revealOrder,l=o.tail;if(Jn(e,t,o.children,n),o=rn.current,o&2)o=o&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Qv(e,n,t);else if(e.tag===19)Qv(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}o&=1}if(Kr(rn,o),!(t.mode&1))t.memoizedState=null;else switch(a){case"forwards":for(n=t.child,a=null;n!==null;)e=n.alternate,e!==null&&Bh(e)===null&&(a=n),n=n.sibling;n=a,n===null?(a=t.child,t.child=null):(a=n.sibling,n.sibling=null),vg(t,!1,a,n,l);break;case"backwards":for(n=null,a=t.child,t.child=null;a!==null;){if(e=a.alternate,e!==null&&Bh(e)===null){t.child=a;break}e=a.sibling,a.sibling=n,n=a,a=e}vg(t,!0,n,null,l);break;case"together":vg(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function yh(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Fo(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),aa|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(bt(153));if(t.child!==null){for(e=t.child,n=ws(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=ws(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function Bk(e,t,n){switch(t.tag){case 3:c2(t),Xl();break;case 5:Rb(t);break;case 1:li(t.type)&&Fh(t);break;case 4:X_(t,t.stateNode.containerInfo);break;case 10:var o=t.type._context,a=t.memoizedProps.value;Kr(Dh,o._currentValue),o._currentValue=a;break;case 13:if(o=t.memoizedState,o!==null)return o.dehydrated!==null?(Kr(rn,rn.current&1),t.flags|=128,null):n&t.child.childLanes?d2(e,t,n):(Kr(rn,rn.current&1),e=Fo(e,t,n),e!==null?e.sibling:null);Kr(rn,rn.current&1);break;case 19:if(o=(n&t.childLanes)!==0,e.flags&128){if(o)return f2(e,t,n);t.flags|=128}if(a=t.memoizedState,a!==null&&(a.rendering=null,a.tail=null,a.lastEffect=null),Kr(rn,rn.current),o)break;return null;case 22:case 23:return t.lanes=0,l2(e,t,n)}return Fo(e,t,n)}var p2,a_,h2,m2;p2=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};a_=function(){};h2=function(e,t,n,o){var a=e.memoizedProps;if(a!==o){e=t.stateNode,ta(uo.current);var l=null;switch(n){case"input":a=Pg(e,a),o=Pg(e,o),l=[];break;case"select":a=on({},a,{value:void 0}),o=on({},o,{value:void 0}),l=[];break;case"textarea":a=Ig(e,a),o=Ig(e,o),l=[];break;default:typeof a.onClick!="function"&&typeof o.onClick=="function"&&(e.onclick=Ah)}zg(n,o);var f;n=null;for(g in a)if(!o.hasOwnProperty(g)&&a.hasOwnProperty(g)&&a[g]!=null)if(g==="style"){var _=a[g];for(f in _)_.hasOwnProperty(f)&&(n||(n={}),n[f]="")}else g!=="dangerouslySetInnerHTML"&&g!=="children"&&g!=="suppressContentEditableWarning"&&g!=="suppressHydrationWarning"&&g!=="autoFocus"&&($f.hasOwnProperty(g)?l||(l=[]):(l=l||[]).push(g,null));for(g in o){var h=o[g];if(_=a!=null?a[g]:void 0,o.hasOwnProperty(g)&&h!==_&&(h!=null||_!=null))if(g==="style")if(_){for(f in _)!_.hasOwnProperty(f)||h&&h.hasOwnProperty(f)||(n||(n={}),n[f]="");for(f in h)h.hasOwnProperty(f)&&_[f]!==h[f]&&(n||(n={}),n[f]=h[f])}else n||(l||(l=[]),l.push(g,n)),n=h;else g==="dangerouslySetInnerHTML"?(h=h?h.__html:void 0,_=_?_.__html:void 0,h!=null&&_!==h&&(l=l||[]).push(g,h)):g==="children"?typeof h!="string"&&typeof h!="number"||(l=l||[]).push(g,""+h):g!=="suppressContentEditableWarning"&&g!=="suppressHydrationWarning"&&($f.hasOwnProperty(g)?(h!=null&&g==="onScroll"&&Xr("scroll",e),l||_===h||(l=[])):(l=l||[]).push(g,h))}n&&(l=l||[]).push("style",n);var g=l;(t.updateQueue=g)&&(t.flags|=4)}};m2=function(e,t,n,o){n!==o&&(t.flags|=4)};function hf(e,t){if(!en)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var o=null;n!==null;)n.alternate!==null&&(o=n),n=n.sibling;o===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function Vn(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,o=0;if(t)for(var a=e.child;a!==null;)n|=a.lanes|a.childLanes,o|=a.subtreeFlags&14680064,o|=a.flags&14680064,a.return=e,a=a.sibling;else for(a=e.child;a!==null;)n|=a.lanes|a.childLanes,o|=a.subtreeFlags,o|=a.flags,a.return=e,a=a.sibling;return e.subtreeFlags|=o,e.childLanes=n,t}function Nk(e,t,n){var o=t.pendingProps;switch(V_(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Vn(t),null;case 1:return li(t.type)&&Ih(),Vn(t),null;case 3:return o=t.stateNode,Zl(),Zr(ai),Zr(Gn),Z_(),o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(e===null||e.child===null)&&(rh(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Hi!==null&&(m_(Hi),Hi=null))),a_(e,t),Vn(t),null;case 5:Y_(t);var a=ta(Uf.current);if(n=t.type,e!==null&&t.stateNode!=null)h2(e,t,n,o,a),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!o){if(t.stateNode===null)throw Error(bt(166));return Vn(t),null}if(e=ta(uo.current),rh(t)){o=t.stateNode,n=t.type;var l=t.memoizedProps;switch(o[ao]=t,o[Nf]=l,e=(t.mode&1)!==0,n){case"dialog":Xr("cancel",o),Xr("close",o);break;case"iframe":case"object":case"embed":Xr("load",o);break;case"video":case"audio":for(a=0;a<wf.length;a++)Xr(wf[a],o);break;case"source":Xr("error",o);break;case"img":case"image":case"link":Xr("error",o),Xr("load",o);break;case"details":Xr("toggle",o);break;case"input":iv(o,l),Xr("invalid",o);break;case"select":o._wrapperState={wasMultiple:!!l.multiple},Xr("invalid",o);break;case"textarea":sv(o,l),Xr("invalid",o)}zg(n,l),a=null;for(var f in l)if(l.hasOwnProperty(f)){var _=l[f];f==="children"?typeof _=="string"?o.textContent!==_&&(l.suppressHydrationWarning!==!0&&th(o.textContent,_,e),a=["children",_]):typeof _=="number"&&o.textContent!==""+_&&(l.suppressHydrationWarning!==!0&&th(o.textContent,_,e),a=["children",""+_]):$f.hasOwnProperty(f)&&_!=null&&f==="onScroll"&&Xr("scroll",o)}switch(n){case"input":Hp(o),ov(o,l,!0);break;case"textarea":Hp(o),av(o);break;case"select":case"option":break;default:typeof l.onClick=="function"&&(o.onclick=Ah)}o=a,t.updateQueue=o,o!==null&&(t.flags|=4)}else{f=a.nodeType===9?a:a.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=V1(n)),e==="http://www.w3.org/1999/xhtml"?n==="script"?(e=f.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=f.createElement(n,{is:o.is}):(e=f.createElement(n),n==="select"&&(f=e,o.multiple?f.multiple=!0:o.size&&(f.size=o.size))):e=f.createElementNS(e,n),e[ao]=t,e[Nf]=o,p2(e,t,!1,!1),t.stateNode=e;e:{switch(f=Og(n,o),n){case"dialog":Xr("cancel",e),Xr("close",e),a=o;break;case"iframe":case"object":case"embed":Xr("load",e),a=o;break;case"video":case"audio":for(a=0;a<wf.length;a++)Xr(wf[a],e);a=o;break;case"source":Xr("error",e),a=o;break;case"img":case"image":case"link":Xr("error",e),Xr("load",e),a=o;break;case"details":Xr("toggle",e),a=o;break;case"input":iv(e,o),a=Pg(e,o),Xr("invalid",e);break;case"option":a=o;break;case"select":e._wrapperState={wasMultiple:!!o.multiple},a=on({},o,{value:void 0}),Xr("invalid",e);break;case"textarea":sv(e,o),a=Ig(e,o),Xr("invalid",e);break;default:a=o}zg(n,a),_=a;for(l in _)if(_.hasOwnProperty(l)){var h=_[l];l==="style"?q1(e,h):l==="dangerouslySetInnerHTML"?(h=h?h.__html:void 0,h!=null&&W1(e,h)):l==="children"?typeof h=="string"?(n!=="textarea"||h!=="")&&Af(e,h):typeof h=="number"&&Af(e,""+h):l!=="suppressContentEditableWarning"&&l!=="suppressHydrationWarning"&&l!=="autoFocus"&&($f.hasOwnProperty(l)?h!=null&&l==="onScroll"&&Xr("scroll",e):h!=null&&C_(e,l,h,f))}switch(n){case"input":Hp(e),ov(e,o,!1);break;case"textarea":Hp(e),av(e);break;case"option":o.value!=null&&e.setAttribute("value",""+vs(o.value));break;case"select":e.multiple=!!o.multiple,l=o.value,l!=null?Ul(e,!!o.multiple,l,!1):o.defaultValue!=null&&Ul(e,!!o.multiple,o.defaultValue,!0);break;default:typeof a.onClick=="function"&&(e.onclick=Ah)}switch(n){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}}o&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return Vn(t),null;case 6:if(e&&t.stateNode!=null)m2(e,t,e.memoizedProps,o);else{if(typeof o!="string"&&t.stateNode===null)throw Error(bt(166));if(n=ta(Uf.current),ta(uo.current),rh(t)){if(o=t.stateNode,n=t.memoizedProps,o[ao]=t,(l=o.nodeValue!==n)&&(e=_i,e!==null))switch(e.tag){case 3:th(o.nodeValue,n,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&th(o.nodeValue,n,(e.mode&1)!==0)}l&&(t.flags|=4)}else o=(n.nodeType===9?n:n.ownerDocument).createTextNode(o),o[ao]=t,t.stateNode=o}return Vn(t),null;case 13:if(Zr(rn),o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(en&&gi!==null&&t.mode&1&&!(t.flags&128))Fb(),Xl(),t.flags|=98560,l=!1;else if(l=rh(t),o!==null&&o.dehydrated!==null){if(e===null){if(!l)throw Error(bt(318));if(l=t.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(bt(317));l[ao]=t}else Xl(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Vn(t),l=!1}else Hi!==null&&(m_(Hi),Hi=null),l=!0;if(!l)return t.flags&65536?t:null}return t.flags&128?(t.lanes=n,t):(o=o!==null,o!==(e!==null&&e.memoizedState!==null)&&o&&(t.child.flags|=8192,t.mode&1&&(e===null||rn.current&1?Tn===0&&(Tn=3):c0())),t.updateQueue!==null&&(t.flags|=4),Vn(t),null);case 4:return Zl(),a_(e,t),e===null&&Rf(t.stateNode.containerInfo),Vn(t),null;case 10:return H_(t.type._context),Vn(t),null;case 17:return li(t.type)&&Ih(),Vn(t),null;case 19:if(Zr(rn),l=t.memoizedState,l===null)return Vn(t),null;if(o=(t.flags&128)!==0,f=l.rendering,f===null)if(o)hf(l,!1);else{if(Tn!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(f=Bh(e),f!==null){for(t.flags|=128,hf(l,!1),o=f.updateQueue,o!==null&&(t.updateQueue=o,t.flags|=4),t.subtreeFlags=0,o=n,n=t.child;n!==null;)l=n,e=o,l.flags&=14680066,f=l.alternate,f===null?(l.childLanes=0,l.lanes=e,l.child=null,l.subtreeFlags=0,l.memoizedProps=null,l.memoizedState=null,l.updateQueue=null,l.dependencies=null,l.stateNode=null):(l.childLanes=f.childLanes,l.lanes=f.lanes,l.child=f.child,l.subtreeFlags=0,l.deletions=null,l.memoizedProps=f.memoizedProps,l.memoizedState=f.memoizedState,l.updateQueue=f.updateQueue,l.type=f.type,e=f.dependencies,l.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return Kr(rn,rn.current&1|2),t.child}e=e.sibling}l.tail!==null&&fn()>eu&&(t.flags|=128,o=!0,hf(l,!1),t.lanes=4194304)}else{if(!o)if(e=Bh(f),e!==null){if(t.flags|=128,o=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),hf(l,!0),l.tail===null&&l.tailMode==="hidden"&&!f.alternate&&!en)return Vn(t),null}else 2*fn()-l.renderingStartTime>eu&&n!==1073741824&&(t.flags|=128,o=!0,hf(l,!1),t.lanes=4194304);l.isBackwards?(f.sibling=t.child,t.child=f):(n=l.last,n!==null?n.sibling=f:t.child=f,l.last=f)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=fn(),t.sibling=null,n=rn.current,Kr(rn,o?n&1|2:n&1),t):(Vn(t),null);case 22:case 23:return u0(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?mi&1073741824&&(Vn(t),t.subtreeFlags&6&&(t.flags|=8192)):Vn(t),null;case 24:return null;case 25:return null}throw Error(bt(156,t.tag))}function jk(e,t){switch(V_(t),t.tag){case 1:return li(t.type)&&Ih(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Zl(),Zr(ai),Zr(Gn),Z_(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Y_(t),null;case 13:if(Zr(rn),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(bt(340));Xl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Zr(rn),null;case 4:return Zl(),null;case 10:return H_(t.type._context),null;case 22:case 23:return u0(),null;case 24:return null;default:return null}}var oh=!1,Wn=!1,Uk=typeof WeakSet=="function"?WeakSet:Set,jt=null;function Nl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(o){cn(e,t,o)}else n.current=null}function l_(e,t,n){try{n()}catch(o){cn(e,t,o)}}var Xv=!1;function Vk(e,t){if(Gg=Ch,e=vb(),j_(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var o=n.getSelection&&n.getSelection();if(o&&o.rangeCount!==0){n=o.anchorNode;var a=o.anchorOffset,l=o.focusNode;o=o.focusOffset;try{n.nodeType,l.nodeType}catch{n=null;break e}var f=0,_=-1,h=-1,g=0,M=0,w=e,C=null;t:for(;;){for(var k;w!==n||a!==0&&w.nodeType!==3||(_=f+a),w!==l||o!==0&&w.nodeType!==3||(h=f+o),w.nodeType===3&&(f+=w.nodeValue.length),(k=w.firstChild)!==null;)C=w,w=k;for(;;){if(w===e)break t;if(C===n&&++g===a&&(_=f),C===l&&++M===o&&(h=f),(k=w.nextSibling)!==null)break;w=C,C=w.parentNode}w=k}n=_===-1||h===-1?null:{start:_,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for(qg={focusedElem:e,selectionRange:n},Ch=!1,jt=t;jt!==null;)if(t=jt,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,jt=e;else for(;jt!==null;){t=jt;try{var z=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(z!==null){var S=z.memoizedProps,P=z.memoizedState,y=t.stateNode,x=y.getSnapshotBeforeUpdate(t.elementType===t.type?S:Gi(t.type,S),P);y.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var I=t.stateNode.containerInfo;I.nodeType===1?I.textContent="":I.nodeType===9&&I.documentElement&&I.removeChild(I.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(bt(163))}}catch(U){cn(t,t.return,U)}if(e=t.sibling,e!==null){e.return=t.return,jt=e;break}jt=t.return}return z=Xv,Xv=!1,z}function Ef(e,t,n){var o=t.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var a=o=o.next;do{if((a.tag&e)===e){var l=a.destroy;a.destroy=void 0,l!==void 0&&l_(t,n,l)}a=a.next}while(a!==o)}}function om(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var o=n.create;n.destroy=o()}n=n.next}while(n!==t)}}function u_(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function g2(e){var t=e.alternate;t!==null&&(e.alternate=null,g2(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ao],delete t[Nf],delete t[Qg],delete t[kk],delete t[Sk])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function _2(e){return e.tag===5||e.tag===3||e.tag===4}function Yv(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||_2(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function c_(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ah));else if(o!==4&&(e=e.child,e!==null))for(c_(e,t,n),e=e.sibling;e!==null;)c_(e,t,n),e=e.sibling}function d_(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(d_(e,t,n),e=e.sibling;e!==null;)d_(e,t,n),e=e.sibling}var On=null,qi=!1;function os(e,t,n){for(n=n.child;n!==null;)y2(e,t,n),n=n.sibling}function y2(e,t,n){if(lo&&typeof lo.onCommitFiberUnmount=="function")try{lo.onCommitFiberUnmount(Yh,n)}catch{}switch(n.tag){case 5:Wn||Nl(n,t);case 6:var o=On,a=qi;On=null,os(e,t,n),On=o,qi=a,On!==null&&(qi?(e=On,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):On.removeChild(n.stateNode));break;case 18:On!==null&&(qi?(e=On,n=n.stateNode,e.nodeType===8?pg(e.parentNode,n):e.nodeType===1&&pg(e,n),Of(e)):pg(On,n.stateNode));break;case 4:o=On,a=qi,On=n.stateNode.containerInfo,qi=!0,os(e,t,n),On=o,qi=a;break;case 0:case 11:case 14:case 15:if(!Wn&&(o=n.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var l=a,f=l.destroy;l=l.tag,f!==void 0&&(l&2||l&4)&&l_(n,t,f),a=a.next}while(a!==o)}os(e,t,n);break;case 1:if(!Wn&&(Nl(n,t),o=n.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=n.memoizedProps,o.state=n.memoizedState,o.componentWillUnmount()}catch(_){cn(n,t,_)}os(e,t,n);break;case 21:os(e,t,n);break;case 22:n.mode&1?(Wn=(o=Wn)||n.memoizedState!==null,os(e,t,n),Wn=o):os(e,t,n);break;default:os(e,t,n)}}function Zv(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Uk),t.forEach(function(o){var a=Zk.bind(null,e,o);n.has(o)||(n.add(o),o.then(a,a))})}}function Wi(e,t){var n=t.deletions;if(n!==null)for(var o=0;o<n.length;o++){var a=n[o];try{var l=e,f=t,_=f;e:for(;_!==null;){switch(_.tag){case 5:On=_.stateNode,qi=!1;break e;case 3:On=_.stateNode.containerInfo,qi=!0;break e;case 4:On=_.stateNode.containerInfo,qi=!0;break e}_=_.return}if(On===null)throw Error(bt(160));y2(l,f,a),On=null,qi=!1;var h=a.alternate;h!==null&&(h.return=null),a.return=null}catch(g){cn(a,t,g)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)w2(t,e),t=t.sibling}function w2(e,t){var n=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Wi(t,e),io(e),o&4){try{Ef(3,e,e.return),om(3,e)}catch(S){cn(e,e.return,S)}try{Ef(5,e,e.return)}catch(S){cn(e,e.return,S)}}break;case 1:Wi(t,e),io(e),o&512&&n!==null&&Nl(n,n.return);break;case 5:if(Wi(t,e),io(e),o&512&&n!==null&&Nl(n,n.return),e.flags&32){var a=e.stateNode;try{Af(a,"")}catch(S){cn(e,e.return,S)}}if(o&4&&(a=e.stateNode,a!=null)){var l=e.memoizedProps,f=n!==null?n.memoizedProps:l,_=e.type,h=e.updateQueue;if(e.updateQueue=null,h!==null)try{_==="input"&&l.type==="radio"&&l.name!=null&&j1(a,l),Og(_,f);var g=Og(_,l);for(f=0;f<h.length;f+=2){var M=h[f],w=h[f+1];M==="style"?q1(a,w):M==="dangerouslySetInnerHTML"?W1(a,w):M==="children"?Af(a,w):C_(a,M,w,g)}switch(_){case"input":$g(a,l);break;case"textarea":U1(a,l);break;case"select":var C=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!l.multiple;var k=l.value;k!=null?Ul(a,!!l.multiple,k,!1):C!==!!l.multiple&&(l.defaultValue!=null?Ul(a,!!l.multiple,l.defaultValue,!0):Ul(a,!!l.multiple,l.multiple?[]:"",!1))}a[Nf]=l}catch(S){cn(e,e.return,S)}}break;case 6:if(Wi(t,e),io(e),o&4){if(e.stateNode===null)throw Error(bt(162));a=e.stateNode,l=e.memoizedProps;try{a.nodeValue=l}catch(S){cn(e,e.return,S)}}break;case 3:if(Wi(t,e),io(e),o&4&&n!==null&&n.memoizedState.isDehydrated)try{Of(t.containerInfo)}catch(S){cn(e,e.return,S)}break;case 4:Wi(t,e),io(e);break;case 13:Wi(t,e),io(e),a=e.child,a.flags&8192&&(l=a.memoizedState!==null,a.stateNode.isHidden=l,!l||a.alternate!==null&&a.alternate.memoizedState!==null||(a0=fn())),o&4&&Zv(e);break;case 22:if(M=n!==null&&n.memoizedState!==null,e.mode&1?(Wn=(g=Wn)||M,Wi(t,e),Wn=g):Wi(t,e),io(e),o&8192){if(g=e.memoizedState!==null,(e.stateNode.isHidden=g)&&!M&&e.mode&1)for(jt=e,M=e.child;M!==null;){for(w=jt=M;jt!==null;){switch(C=jt,k=C.child,C.tag){case 0:case 11:case 14:case 15:Ef(4,C,C.return);break;case 1:Nl(C,C.return);var z=C.stateNode;if(typeof z.componentWillUnmount=="function"){o=C,n=C.return;try{t=o,z.props=t.memoizedProps,z.state=t.memoizedState,z.componentWillUnmount()}catch(S){cn(o,n,S)}}break;case 5:Nl(C,C.return);break;case 22:if(C.memoizedState!==null){e1(w);continue}}k!==null?(k.return=C,jt=k):e1(w)}M=M.sibling}e:for(M=null,w=e;;){if(w.tag===5){if(M===null){M=w;try{a=w.stateNode,g?(l=a.style,typeof l.setProperty=="function"?l.setProperty("display","none","important"):l.display="none"):(_=w.stateNode,h=w.memoizedProps.style,f=h!=null&&h.hasOwnProperty("display")?h.display:null,_.style.display=G1("display",f))}catch(S){cn(e,e.return,S)}}}else if(w.tag===6){if(M===null)try{w.stateNode.nodeValue=g?"":w.memoizedProps}catch(S){cn(e,e.return,S)}}else if((w.tag!==22&&w.tag!==23||w.memoizedState===null||w===e)&&w.child!==null){w.child.return=w,w=w.child;continue}if(w===e)break e;for(;w.sibling===null;){if(w.return===null||w.return===e)break e;M===w&&(M=null),w=w.return}M===w&&(M=null),w.sibling.return=w.return,w=w.sibling}}break;case 19:Wi(t,e),io(e),o&4&&Zv(e);break;case 21:break;default:Wi(t,e),io(e)}}function io(e){var t=e.flags;if(t&2){try{e:{for(var n=e.return;n!==null;){if(_2(n)){var o=n;break e}n=n.return}throw Error(bt(160))}switch(o.tag){case 5:var a=o.stateNode;o.flags&32&&(Af(a,""),o.flags&=-33);var l=Yv(e);d_(e,l,a);break;case 3:case 4:var f=o.stateNode.containerInfo,_=Yv(e);c_(e,_,f);break;default:throw Error(bt(161))}}catch(h){cn(e,e.return,h)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Wk(e,t,n){jt=e,v2(e)}function v2(e,t,n){for(var o=(e.mode&1)!==0;jt!==null;){var a=jt,l=a.child;if(a.tag===22&&o){var f=a.memoizedState!==null||oh;if(!f){var _=a.alternate,h=_!==null&&_.memoizedState!==null||Wn;_=oh;var g=Wn;if(oh=f,(Wn=h)&&!g)for(jt=a;jt!==null;)f=jt,h=f.child,f.tag===22&&f.memoizedState!==null?t1(a):h!==null?(h.return=f,jt=h):t1(a);for(;l!==null;)jt=l,v2(l),l=l.sibling;jt=a,oh=_,Wn=g}Jv(e)}else a.subtreeFlags&8772&&l!==null?(l.return=a,jt=l):Jv(e)}}function Jv(e){for(;jt!==null;){var t=jt;if(t.flags&8772){var n=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:Wn||om(5,t);break;case 1:var o=t.stateNode;if(t.flags&4&&!Wn)if(n===null)o.componentDidMount();else{var a=t.elementType===t.type?n.memoizedProps:Gi(t.type,n.memoizedProps);o.componentDidUpdate(a,n.memoizedState,o.__reactInternalSnapshotBeforeUpdate)}var l=t.updateQueue;l!==null&&Lv(t,l,o);break;case 3:var f=t.updateQueue;if(f!==null){if(n=null,t.child!==null)switch(t.child.tag){case 5:n=t.child.stateNode;break;case 1:n=t.child.stateNode}Lv(t,f,n)}break;case 5:var _=t.stateNode;if(n===null&&t.flags&4){n=_;var h=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":h.autoFocus&&n.focus();break;case"img":h.src&&(n.src=h.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var g=t.alternate;if(g!==null){var M=g.memoizedState;if(M!==null){var w=M.dehydrated;w!==null&&Of(w)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(bt(163))}Wn||t.flags&512&&u_(t)}catch(C){cn(t,t.return,C)}}if(t===e){jt=null;break}if(n=t.sibling,n!==null){n.return=t.return,jt=n;break}jt=t.return}}function e1(e){for(;jt!==null;){var t=jt;if(t===e){jt=null;break}var n=t.sibling;if(n!==null){n.return=t.return,jt=n;break}jt=t.return}}function t1(e){for(;jt!==null;){var t=jt;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{om(4,t)}catch(h){cn(t,n,h)}break;case 1:var o=t.stateNode;if(typeof o.componentDidMount=="function"){var a=t.return;try{o.componentDidMount()}catch(h){cn(t,a,h)}}var l=t.return;try{u_(t)}catch(h){cn(t,l,h)}break;case 5:var f=t.return;try{u_(t)}catch(h){cn(t,f,h)}}}catch(h){cn(t,t.return,h)}if(t===e){jt=null;break}var _=t.sibling;if(_!==null){_.return=t.return,jt=_;break}jt=t.return}}var Gk=Math.ceil,Uh=zo.ReactCurrentDispatcher,o0=zo.ReactCurrentOwner,zi=zo.ReactCurrentBatchConfig,Ir=0,Pn=null,hn=null,Dn=0,mi=0,jl=Ms(0),Tn=0,qf=null,aa=0,sm=0,s0=0,Cf=null,oi=null,a0=0,eu=1/0,To=null,Vh=!1,f_=null,_s=null,sh=!1,ds=null,Wh=0,Pf=0,p_=null,wh=-1,vh=0;function ei(){return Ir&6?fn():wh!==-1?wh:wh=fn()}function ys(e){return e.mode&1?Ir&2&&Dn!==0?Dn&-Dn:Ck.transition!==null?(vh===0&&(vh=ib()),vh):(e=Rr,e!==0||(e=window.event,e=e===void 0?16:db(e.type)),e):1}function Qi(e,t,n,o){if(50<Pf)throw Pf=0,p_=null,Error(bt(185));Qf(e,n,o),(!(Ir&2)||e!==Pn)&&(e===Pn&&(!(Ir&2)&&(sm|=n),Tn===4&&us(e,Dn)),ui(e,o),n===1&&Ir===0&&!(t.mode&1)&&(eu=fn()+500,rm&&Ts()))}function ui(e,t){var n=e.callbackNode;CT(e,t);var o=Eh(e,e===Pn?Dn:0);if(o===0)n!==null&&cv(n),e.callbackNode=null,e.callbackPriority=0;else if(t=o&-o,e.callbackPriority!==t){if(n!=null&&cv(n),t===1)e.tag===0?Ek(r1.bind(null,e)):$b(r1.bind(null,e)),Mk(function(){!(Ir&6)&&Ts()}),n=null;else{switch(ob(o)){case 1:n=F_;break;case 4:n=rb;break;case 16:n=Sh;break;case 536870912:n=nb;break;default:n=Sh}n=C2(n,b2.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function b2(e,t){if(wh=-1,vh=0,Ir&6)throw Error(bt(327));var n=e.callbackNode;if(Hl()&&e.callbackNode!==n)return null;var o=Eh(e,e===Pn?Dn:0);if(o===0)return null;if(o&30||o&e.expiredLanes||t)t=Gh(e,o);else{t=o;var a=Ir;Ir|=2;var l=M2();(Pn!==e||Dn!==t)&&(To=null,eu=fn()+500,ra(e,t));do try{Kk();break}catch(_){x2(e,_)}while(!0);q_(),Uh.current=l,Ir=a,hn!==null?t=0:(Pn=null,Dn=0,t=Tn)}if(t!==0){if(t===2&&(a=Ng(e),a!==0&&(o=a,t=h_(e,a))),t===1)throw n=qf,ra(e,0),us(e,o),ui(e,fn()),n;if(t===6)us(e,o);else{if(a=e.current.alternate,!(o&30)&&!qk(a)&&(t=Gh(e,o),t===2&&(l=Ng(e),l!==0&&(o=l,t=h_(e,l))),t===1))throw n=qf,ra(e,0),us(e,o),ui(e,fn()),n;switch(e.finishedWork=a,e.finishedLanes=o,t){case 0:case 1:throw Error(bt(345));case 2:Ys(e,oi,To);break;case 3:if(us(e,o),(o&130023424)===o&&(t=a0+500-fn(),10<t)){if(Eh(e,0)!==0)break;if(a=e.suspendedLanes,(a&o)!==o){ei(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=Kg(Ys.bind(null,e,oi,To),t);break}Ys(e,oi,To);break;case 4:if(us(e,o),(o&4194240)===o)break;for(t=e.eventTimes,a=-1;0<o;){var f=31-Ki(o);l=1<<f,f=t[f],f>a&&(a=f),o&=~l}if(o=a,o=fn()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*Gk(o/1960))-o,10<o){e.timeoutHandle=Kg(Ys.bind(null,e,oi,To),o);break}Ys(e,oi,To);break;case 5:Ys(e,oi,To);break;default:throw Error(bt(329))}}}return ui(e,fn()),e.callbackNode===n?b2.bind(null,e):null}function h_(e,t){var n=Cf;return e.current.memoizedState.isDehydrated&&(ra(e,t).flags|=256),e=Gh(e,t),e!==2&&(t=oi,oi=n,t!==null&&m_(t)),e}function m_(e){oi===null?oi=e:oi.push.apply(oi,e)}function qk(e){for(var t=e;;){if(t.flags&16384){var n=t.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var o=0;o<n.length;o++){var a=n[o],l=a.getSnapshot;a=a.value;try{if(!Xi(l(),a))return!1}catch{return!1}}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function us(e,t){for(t&=~s0,t&=~sm,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-Ki(t),o=1<<n;e[n]=-1,t&=~o}}function r1(e){if(Ir&6)throw Error(bt(327));Hl();var t=Eh(e,0);if(!(t&1))return ui(e,fn()),null;var n=Gh(e,t);if(e.tag!==0&&n===2){var o=Ng(e);o!==0&&(t=o,n=h_(e,o))}if(n===1)throw n=qf,ra(e,0),us(e,t),ui(e,fn()),n;if(n===6)throw Error(bt(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Ys(e,oi,To),ui(e,fn()),null}function l0(e,t){var n=Ir;Ir|=1;try{return e(t)}finally{Ir=n,Ir===0&&(eu=fn()+500,rm&&Ts())}}function la(e){ds!==null&&ds.tag===0&&!(Ir&6)&&Hl();var t=Ir;Ir|=1;var n=zi.transition,o=Rr;try{if(zi.transition=null,Rr=1,e)return e()}finally{Rr=o,zi.transition=n,Ir=t,!(Ir&6)&&Ts()}}function u0(){mi=jl.current,Zr(jl)}function ra(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(n!==-1&&(e.timeoutHandle=-1,xk(n)),hn!==null)for(n=hn.return;n!==null;){var o=n;switch(V_(o),o.tag){case 1:o=o.type.childContextTypes,o!=null&&Ih();break;case 3:Zl(),Zr(ai),Zr(Gn),Z_();break;case 5:Y_(o);break;case 4:Zl();break;case 13:Zr(rn);break;case 19:Zr(rn);break;case 10:H_(o.type._context);break;case 22:case 23:u0()}n=n.return}if(Pn=e,hn=e=ws(e.current,null),Dn=mi=t,Tn=0,qf=null,s0=sm=aa=0,oi=Cf=null,ea!==null){for(t=0;t<ea.length;t++)if(n=ea[t],o=n.interleaved,o!==null){n.interleaved=null;var a=o.next,l=n.pending;if(l!==null){var f=l.next;l.next=a,o.next=f}n.pending=o}ea=null}return e}function x2(e,t){do{var n=hn;try{if(q_(),gh.current=jh,Nh){for(var o=nn.memoizedState;o!==null;){var a=o.queue;a!==null&&(a.pending=null),o=o.next}Nh=!1}if(sa=0,Cn=Mn=nn=null,Sf=!1,Vf=0,o0.current=null,n===null||n.return===null){Tn=1,qf=t,hn=null;break}e:{var l=e,f=n.return,_=n,h=t;if(t=Dn,_.flags|=32768,h!==null&&typeof h=="object"&&typeof h.then=="function"){var g=h,M=_,w=M.tag;if(!(M.mode&1)&&(w===0||w===11||w===15)){var C=M.alternate;C?(M.updateQueue=C.updateQueue,M.memoizedState=C.memoizedState,M.lanes=C.lanes):(M.updateQueue=null,M.memoizedState=null)}var k=Vv(f);if(k!==null){k.flags&=-257,Wv(k,f,_,l,t),k.mode&1&&Uv(l,g,t),t=k,h=g;var z=t.updateQueue;if(z===null){var S=new Set;S.add(h),t.updateQueue=S}else z.add(h);break e}else{if(!(t&1)){Uv(l,g,t),c0();break e}h=Error(bt(426))}}else if(en&&_.mode&1){var P=Vv(f);if(P!==null){!(P.flags&65536)&&(P.flags|=256),Wv(P,f,_,l,t),W_(Jl(h,_));break e}}l=h=Jl(h,_),Tn!==4&&(Tn=2),Cf===null?Cf=[l]:Cf.push(l),l=f;do{switch(l.tag){case 3:l.flags|=65536,t&=-t,l.lanes|=t;var y=o2(l,h,t);Dv(l,y);break e;case 1:_=h;var x=l.type,I=l.stateNode;if(!(l.flags&128)&&(typeof x.getDerivedStateFromError=="function"||I!==null&&typeof I.componentDidCatch=="function"&&(_s===null||!_s.has(I)))){l.flags|=65536,t&=-t,l.lanes|=t;var U=s2(l,_,t);Dv(l,U);break e}}l=l.return}while(l!==null)}k2(n)}catch(O){t=O,hn===n&&n!==null&&(hn=n=n.return);continue}break}while(!0)}function M2(){var e=Uh.current;return Uh.current=jh,e===null?jh:e}function c0(){(Tn===0||Tn===3||Tn===2)&&(Tn=4),Pn===null||!(aa&268435455)&&!(sm&268435455)||us(Pn,Dn)}function Gh(e,t){var n=Ir;Ir|=2;var o=M2();(Pn!==e||Dn!==t)&&(To=null,ra(e,t));do try{Hk();break}catch(a){x2(e,a)}while(!0);if(q_(),Ir=n,Uh.current=o,hn!==null)throw Error(bt(261));return Pn=null,Dn=0,Tn}function Hk(){for(;hn!==null;)T2(hn)}function Kk(){for(;hn!==null&&!wT();)T2(hn)}function T2(e){var t=E2(e.alternate,e,mi);e.memoizedProps=e.pendingProps,t===null?k2(e):hn=t,o0.current=null}function k2(e){var t=e;do{var n=t.alternate;if(e=t.return,t.flags&32768){if(n=jk(n,t),n!==null){n.flags&=32767,hn=n;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Tn=6,hn=null;return}}else if(n=Nk(n,t,mi),n!==null){hn=n;return}if(t=t.sibling,t!==null){hn=t;return}hn=t=e}while(t!==null);Tn===0&&(Tn=5)}function Ys(e,t,n){var o=Rr,a=zi.transition;try{zi.transition=null,Rr=1,Qk(e,t,n,o)}finally{zi.transition=a,Rr=o}return null}function Qk(e,t,n,o){do Hl();while(ds!==null);if(Ir&6)throw Error(bt(327));n=e.finishedWork;var a=e.finishedLanes;if(n===null)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(bt(177));e.callbackNode=null,e.callbackPriority=0;var l=n.lanes|n.childLanes;if(PT(e,l),e===Pn&&(hn=Pn=null,Dn=0),!(n.subtreeFlags&2064)&&!(n.flags&2064)||sh||(sh=!0,C2(Sh,function(){return Hl(),null})),l=(n.flags&15990)!==0,n.subtreeFlags&15990||l){l=zi.transition,zi.transition=null;var f=Rr;Rr=1;var _=Ir;Ir|=4,o0.current=null,Vk(e,n),w2(n,e),mk(qg),Ch=!!Gg,qg=Gg=null,e.current=n,Wk(n),vT(),Ir=_,Rr=f,zi.transition=l}else e.current=n;if(sh&&(sh=!1,ds=e,Wh=a),l=e.pendingLanes,l===0&&(_s=null),MT(n.stateNode),ui(e,fn()),t!==null)for(o=e.onRecoverableError,n=0;n<t.length;n++)a=t[n],o(a.value,{componentStack:a.stack,digest:a.digest});if(Vh)throw Vh=!1,e=f_,f_=null,e;return Wh&1&&e.tag!==0&&Hl(),l=e.pendingLanes,l&1?e===p_?Pf++:(Pf=0,p_=e):Pf=0,Ts(),null}function Hl(){if(ds!==null){var e=ob(Wh),t=zi.transition,n=Rr;try{if(zi.transition=null,Rr=16>e?16:e,ds===null)var o=!1;else{if(e=ds,ds=null,Wh=0,Ir&6)throw Error(bt(331));var a=Ir;for(Ir|=4,jt=e.current;jt!==null;){var l=jt,f=l.child;if(jt.flags&16){var _=l.deletions;if(_!==null){for(var h=0;h<_.length;h++){var g=_[h];for(jt=g;jt!==null;){var M=jt;switch(M.tag){case 0:case 11:case 15:Ef(8,M,l)}var w=M.child;if(w!==null)w.return=M,jt=w;else for(;jt!==null;){M=jt;var C=M.sibling,k=M.return;if(g2(M),M===g){jt=null;break}if(C!==null){C.return=k,jt=C;break}jt=k}}}var z=l.alternate;if(z!==null){var S=z.child;if(S!==null){z.child=null;do{var P=S.sibling;S.sibling=null,S=P}while(S!==null)}}jt=l}}if(l.subtreeFlags&2064&&f!==null)f.return=l,jt=f;else e:for(;jt!==null;){if(l=jt,l.flags&2048)switch(l.tag){case 0:case 11:case 15:Ef(9,l,l.return)}var y=l.sibling;if(y!==null){y.return=l.return,jt=y;break e}jt=l.return}}var x=e.current;for(jt=x;jt!==null;){f=jt;var I=f.child;if(f.subtreeFlags&2064&&I!==null)I.return=f,jt=I;else e:for(f=x;jt!==null;){if(_=jt,_.flags&2048)try{switch(_.tag){case 0:case 11:case 15:om(9,_)}}catch(O){cn(_,_.return,O)}if(_===f){jt=null;break e}var U=_.sibling;if(U!==null){U.return=_.return,jt=U;break e}jt=_.return}}if(Ir=a,Ts(),lo&&typeof lo.onPostCommitFiberRoot=="function")try{lo.onPostCommitFiberRoot(Yh,e)}catch{}o=!0}return o}finally{Rr=n,zi.transition=t}}return!1}function n1(e,t,n){t=Jl(n,t),t=o2(e,t,1),e=gs(e,t,1),t=ei(),e!==null&&(Qf(e,1,t),ui(e,t))}function cn(e,t,n){if(e.tag===3)n1(e,e,n);else for(;t!==null;){if(t.tag===3){n1(t,e,n);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(_s===null||!_s.has(o))){e=Jl(n,e),e=s2(t,e,1),t=gs(t,e,1),e=ei(),t!==null&&(Qf(t,1,e),ui(t,e));break}}t=t.return}}function Xk(e,t,n){var o=e.pingCache;o!==null&&o.delete(t),t=ei(),e.pingedLanes|=e.suspendedLanes&n,Pn===e&&(Dn&n)===n&&(Tn===4||Tn===3&&(Dn&130023424)===Dn&&500>fn()-a0?ra(e,0):s0|=n),ui(e,t)}function S2(e,t){t===0&&(e.mode&1?(t=Xp,Xp<<=1,!(Xp&130023424)&&(Xp=4194304)):t=1);var n=ei();e=Io(e,t),e!==null&&(Qf(e,t,n),ui(e,n))}function Yk(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),S2(e,n)}function Zk(e,t){var n=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(bt(314))}o!==null&&o.delete(t),S2(e,n)}var E2;E2=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ai.current)si=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return si=!1,Bk(e,t,n);si=!!(e.flags&131072)}else si=!1,en&&t.flags&1048576&&Ab(t,Oh,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;yh(e,t),e=t.pendingProps;var a=Ql(t,Gn.current);ql(t,n),a=e0(null,t,o,e,a,n);var l=t0();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,li(o)?(l=!0,Fh(t)):l=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Q_(t),a.updater=im,t.stateNode=a,a._reactInternals=t,t_(t,o,e,n),t=i_(null,t,o,!0,l,n)):(t.tag=0,en&&l&&U_(t),Jn(null,t,a,n),t=t.child),t;case 16:o=t.elementType;e:{switch(yh(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=eS(o),e=Gi(o,e),a){case 0:t=n_(null,t,o,e,n);break e;case 1:t=Hv(null,t,o,e,n);break e;case 11:t=Gv(null,t,o,e,n);break e;case 14:t=qv(null,t,o,Gi(o.type,e),n);break e}throw Error(bt(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),n_(e,t,o,a,n);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),Hv(e,t,o,a,n);case 3:e:{if(c2(t),e===null)throw Error(bt(387));o=t.pendingProps,l=t.memoizedState,a=l.element,Lb(e,t),Rh(t,o,null,n);var f=t.memoizedState;if(o=f.element,l.isDehydrated)if(l={element:o,isDehydrated:!1,cache:f.cache,pendingSuspenseBoundaries:f.pendingSuspenseBoundaries,transitions:f.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){a=Jl(Error(bt(423)),t),t=Kv(e,t,o,n,a);break e}else if(o!==a){a=Jl(Error(bt(424)),t),t=Kv(e,t,o,n,a);break e}else for(gi=ms(t.stateNode.containerInfo.firstChild),_i=t,en=!0,Hi=null,n=Ob(t,null,o,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Xl(),o===a){t=Fo(e,t,n);break e}Jn(e,t,o,n)}t=t.child}return t;case 5:return Rb(t),e===null&&Zg(t),o=t.type,a=t.pendingProps,l=e!==null?e.memoizedProps:null,f=a.children,Hg(o,a)?f=null:l!==null&&Hg(o,l)&&(t.flags|=32),u2(e,t),Jn(e,t,f,n),t.child;case 6:return e===null&&Zg(t),null;case 13:return d2(e,t,n);case 4:return X_(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=Yl(t,null,o,n):Jn(e,t,o,n),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),Gv(e,t,o,a,n);case 7:return Jn(e,t,t.pendingProps,n),t.child;case 8:return Jn(e,t,t.pendingProps.children,n),t.child;case 12:return Jn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,l=t.memoizedProps,f=a.value,Kr(Dh,o._currentValue),o._currentValue=f,l!==null)if(Xi(l.value,f)){if(l.children===a.children&&!ai.current){t=Fo(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var _=l.dependencies;if(_!==null){f=l.child;for(var h=_.firstContext;h!==null;){if(h.context===o){if(l.tag===1){h=Po(-1,n&-n),h.tag=2;var g=l.updateQueue;if(g!==null){g=g.shared;var M=g.pending;M===null?h.next=h:(h.next=M.next,M.next=h),g.pending=h}}l.lanes|=n,h=l.alternate,h!==null&&(h.lanes|=n),Jg(l.return,n,t),_.lanes|=n;break}h=h.next}}else if(l.tag===10)f=l.type===t.type?null:l.child;else if(l.tag===18){if(f=l.return,f===null)throw Error(bt(341));f.lanes|=n,_=f.alternate,_!==null&&(_.lanes|=n),Jg(f,n,t),f=l.sibling}else f=l.child;if(f!==null)f.return=l;else for(f=l;f!==null;){if(f===t){f=null;break}if(l=f.sibling,l!==null){l.return=f.return,f=l;break}f=f.return}l=f}Jn(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,ql(t,n),a=Oi(a),o=o(a),t.flags|=1,Jn(e,t,o,n),t.child;case 14:return o=t.type,a=Gi(o,t.pendingProps),a=Gi(o.type,a),qv(e,t,o,a,n);case 15:return a2(e,t,t.type,t.pendingProps,n);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),yh(e,t),t.tag=1,li(o)?(e=!0,Fh(t)):e=!1,ql(t,n),i2(t,o,a),t_(t,o,a,n),i_(null,t,o,!0,e,n);case 19:return f2(e,t,n);case 22:return l2(e,t,n)}throw Error(bt(156,t.tag))};function C2(e,t){return tb(e,t)}function Jk(e,t,n,o){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Fi(e,t,n,o){return new Jk(e,t,n,o)}function d0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function eS(e){if(typeof e=="function")return d0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===$_)return 11;if(e===A_)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Fi(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function bh(e,t,n,o,a,l){var f=2;if(o=e,typeof e=="function")d0(e)&&(f=1);else if(typeof e=="string")f=5;else e:switch(e){case Al:return na(n.children,a,l,t);case P_:f=8,a|=8;break;case kg:return e=Fi(12,n,t,a|2),e.elementType=kg,e.lanes=l,e;case Sg:return e=Fi(13,n,t,a),e.elementType=Sg,e.lanes=l,e;case Eg:return e=Fi(19,n,t,a),e.elementType=Eg,e.lanes=l,e;case R1:return am(n,a,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D1:f=10;break e;case L1:f=9;break e;case $_:f=11;break e;case A_:f=14;break e;case ss:f=16,o=null;break e}throw Error(bt(130,e==null?e:typeof e,""))}return t=Fi(f,n,t,a),t.elementType=e,t.type=o,t.lanes=l,t}function na(e,t,n,o){return e=Fi(7,e,o,t),e.lanes=n,e}function am(e,t,n,o){return e=Fi(22,e,o,t),e.elementType=R1,e.lanes=n,e.stateNode={isHidden:!1},e}function bg(e,t,n){return e=Fi(6,e,null,t),e.lanes=n,e}function xg(e,t,n){return t=Fi(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tS(e,t,n,o,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=rg(0),this.expirationTimes=rg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=rg(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function f0(e,t,n,o,a,l,f,_,h){return e=new tS(e,t,n,_,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=Fi(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:o,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Q_(l),e}function rS(e,t,n){var o=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:$l,key:o==null?null:""+o,children:e,containerInfo:t,implementation:n}}function P2(e){if(!e)return bs;e=e._reactInternals;e:{if(ca(e)!==e||e.tag!==1)throw Error(bt(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(li(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(bt(171))}if(e.tag===1){var n=e.type;if(li(n))return Pb(e,n,t)}return t}function $2(e,t,n,o,a,l,f,_,h){return e=f0(n,o,!0,e,a,l,f,_,h),e.context=P2(null),n=e.current,o=ei(),a=ys(n),l=Po(o,a),l.callback=t??null,gs(n,l,a),e.current.lanes=a,Qf(e,a,o),ui(e,o),e}function lm(e,t,n,o){var a=t.current,l=ei(),f=ys(a);return n=P2(n),t.context===null?t.context=n:t.pendingContext=n,t=Po(l,f),t.payload={element:e},o=o===void 0?null:o,o!==null&&(t.callback=o),e=gs(a,t,f),e!==null&&(Qi(e,a,f,l),mh(e,a,f)),f}function qh(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function i1(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function p0(e,t){i1(e,t),(e=e.alternate)&&i1(e,t)}function nS(){return null}var A2=typeof reportError=="function"?reportError:function(e){console.error(e)};function h0(e){this._internalRoot=e}um.prototype.render=h0.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(bt(409));lm(e,t,null,null)};um.prototype.unmount=h0.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;la(function(){lm(null,e,null,null)}),t[Ao]=null}};function um(e){this._internalRoot=e}um.prototype.unstable_scheduleHydration=function(e){if(e){var t=lb();e={blockedOn:null,target:e,priority:t};for(var n=0;n<ls.length&&t!==0&&t<ls[n].priority;n++);ls.splice(n,0,e),n===0&&cb(e)}};function m0(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function cm(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function o1(){}function iS(e,t,n,o,a){if(a){if(typeof o=="function"){var l=o;o=function(){var g=qh(f);l.call(g)}}var f=$2(t,o,e,0,null,!1,!1,"",o1);return e._reactRootContainer=f,e[Ao]=f.current,Rf(e.nodeType===8?e.parentNode:e),la(),f}for(;a=e.lastChild;)e.removeChild(a);if(typeof o=="function"){var _=o;o=function(){var g=qh(h);_.call(g)}}var h=f0(e,0,!1,null,null,!1,!1,"",o1);return e._reactRootContainer=h,e[Ao]=h.current,Rf(e.nodeType===8?e.parentNode:e),la(function(){lm(t,h,n,o)}),h}function dm(e,t,n,o,a){var l=n._reactRootContainer;if(l){var f=l;if(typeof a=="function"){var _=a;a=function(){var h=qh(f);_.call(h)}}lm(t,f,e,a)}else f=iS(n,t,e,a,o);return qh(f)}sb=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=yf(t.pendingLanes);n!==0&&(z_(t,n|1),ui(t,fn()),!(Ir&6)&&(eu=fn()+500,Ts()))}break;case 13:la(function(){var o=Io(e,1);if(o!==null){var a=ei();Qi(o,e,1,a)}}),p0(e,1)}};O_=function(e){if(e.tag===13){var t=Io(e,134217728);if(t!==null){var n=ei();Qi(t,e,134217728,n)}p0(e,134217728)}};ab=function(e){if(e.tag===13){var t=ys(e),n=Io(e,t);if(n!==null){var o=ei();Qi(n,e,t,o)}p0(e,t)}};lb=function(){return Rr};ub=function(e,t){var n=Rr;try{return Rr=e,t()}finally{Rr=n}};Lg=function(e,t,n){switch(t){case"input":if($g(e,n),t=n.name,n.type==="radio"&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var o=n[t];if(o!==e&&o.form===e.form){var a=tm(o);if(!a)throw Error(bt(90));N1(o),$g(o,a)}}}break;case"textarea":U1(e,n);break;case"select":t=n.value,t!=null&&Ul(e,!!n.multiple,t,!1)}};Q1=l0;X1=la;var oS={usingClientEntryPoint:!1,Events:[Yf,Ol,tm,H1,K1,l0]},mf={findFiberByHostInstance:Js,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},sS={bundleType:mf.bundleType,version:mf.version,rendererPackageName:mf.rendererPackageName,rendererConfig:mf.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:zo.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=J1(e),e===null?null:e.stateNode},findFiberByHostInstance:mf.findFiberByHostInstance||nS,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var ah=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!ah.isDisabled&&ah.supportsFiber)try{Yh=ah.inject(sS),lo=ah}catch{}}wi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=oS;wi.createPortal=function(e,t){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!m0(t))throw Error(bt(200));return rS(e,t,null,n)};wi.createRoot=function(e,t){if(!m0(e))throw Error(bt(299));var n=!1,o="",a=A2;return t!=null&&(t.unstable_strictMode===!0&&(n=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onRecoverableError!==void 0&&(a=t.onRecoverableError)),t=f0(e,1,!1,null,null,n,!1,o,a),e[Ao]=t.current,Rf(e.nodeType===8?e.parentNode:e),new h0(t)};wi.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(bt(188)):(e=Object.keys(e).join(","),Error(bt(268,e)));return e=J1(t),e=e===null?null:e.stateNode,e};wi.flushSync=function(e){return la(e)};wi.hydrate=function(e,t,n){if(!cm(t))throw Error(bt(200));return dm(null,e,t,!0,n)};wi.hydrateRoot=function(e,t,n){if(!m0(e))throw Error(bt(405));var o=n!=null&&n.hydratedSources||null,a=!1,l="",f=A2;if(n!=null&&(n.unstable_strictMode===!0&&(a=!0),n.identifierPrefix!==void 0&&(l=n.identifierPrefix),n.onRecoverableError!==void 0&&(f=n.onRecoverableError)),t=$2(t,null,e,1,n??null,a,!1,l,f),e[Ao]=t.current,Rf(e),o)for(e=0;e<o.length;e++)n=o[e],a=n._getVersion,a=a(n._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[n,a]:t.mutableSourceEagerHydrationData.push(n,a);return new um(t)};wi.render=function(e,t,n){if(!cm(t))throw Error(bt(200));return dm(null,e,t,!1,n)};wi.unmountComponentAtNode=function(e){if(!cm(e))throw Error(bt(40));return e._reactRootContainer?(la(function(){dm(null,null,e,!1,function(){e._reactRootContainer=null,e[Ao]=null})}),!0):!1};wi.unstable_batchedUpdates=l0;wi.unstable_renderSubtreeIntoContainer=function(e,t,n,o){if(!cm(n))throw Error(bt(200));if(e==null||e._reactInternals===void 0)throw Error(bt(38));return dm(e,t,n,!1,o)};wi.version="18.3.1-next-f1338f8080-20240426";function I2(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(I2)}catch(e){console.error(e)}}I2(),I1.exports=wi;var aS=I1.exports,F2,s1=aS;F2=s1.createRoot,s1.hydrateRoot;var z2={exports:{}},lS="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",uS=lS,cS=uS;function O2(){}function D2(){}D2.resetWarningCache=O2;var dS=function(){function e(o,a,l,f,_,h){if(h!==cS){var g=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw g.name="Invariant Violation",g}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:D2,resetWarningCache:O2};return n.PropTypes=n,n};z2.exports=dS();var fS=z2.exports;const Ur=b_(fS);function iu(e,t,n,o){function a(l){return l instanceof n?l:new n(function(f){f(l)})}return new(n||(n=Promise))(function(l,f){function _(M){try{g(o.next(M))}catch(w){f(w)}}function h(M){try{g(o.throw(M))}catch(w){f(w)}}function g(M){M.done?l(M.value):a(M.value).then(_,h)}g((o=o.apply(e,t||[])).next())})}function ou(e,t){var n={label:0,sent:function(){if(l[0]&1)throw l[1];return l[1]},trys:[],ops:[]},o,a,l,f=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return f.next=_(0),f.throw=_(1),f.return=_(2),typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function _(g){return function(M){return h([g,M])}}function h(g){if(o)throw new TypeError("Generator is already executing.");for(;f&&(f=0,g[0]&&(n=0)),n;)try{if(o=1,a&&(l=g[0]&2?a.return:g[0]?a.throw||((l=a.return)&&l.call(a),0):a.next)&&!(l=l.call(a,g[1])).done)return l;switch(a=0,l&&(g=[g[0]&2,l.value]),g[0]){case 0:case 1:l=g;break;case 4:return n.label++,{value:g[1],done:!1};case 5:n.label++,a=g[1],g=[0];continue;case 7:g=n.ops.pop(),n.trys.pop();continue;default:if(l=n.trys,!(l=l.length>0&&l[l.length-1])&&(g[0]===6||g[0]===2)){n=0;continue}if(g[0]===3&&(!l||g[1]>l[0]&&g[1]<l[3])){n.label=g[1];break}if(g[0]===6&&n.label<l[1]){n.label=l[1],l=g;break}if(l&&n.label<l[2]){n.label=l[2],n.ops.push(g);break}l[2]&&n.ops.pop(),n.trys.pop();continue}g=t.call(e,n)}catch(M){g=[6,M],a=0}finally{o=l=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}}function a1(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var o=n.call(e),a,l=[],f;try{for(;(t===void 0||t-- >0)&&!(a=o.next()).done;)l.push(a.value)}catch(_){f={error:_}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(f)throw f.error}}return l}function l1(e,t,n){if(n||arguments.length===2)for(var o=0,a=t.length,l;o<a;o++)(l||!(o in t))&&(l||(l=Array.prototype.slice.call(t,0,o)),l[o]=t[o]);return e.concat(l||Array.prototype.slice.call(t))}var pS=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Jf(e,t){var n=hS(e);if(typeof n.path!="string"){var o=e.webkitRelativePath;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof o=="string"&&o.length>0?o:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function hS(e){var t=e.name,n=t&&t.lastIndexOf(".")!==-1;if(n&&!e.type){var o=t.split(".").pop().toLowerCase(),a=pS.get(o);a&&Object.defineProperty(e,"type",{value:a,writable:!1,configurable:!1,enumerable:!0})}return e}var mS=[".DS_Store","Thumbs.db"];function gS(e){return iu(this,void 0,void 0,function(){return ou(this,function(t){return Hh(e)&&_S(e.dataTransfer)?[2,bS(e.dataTransfer,e.type)]:yS(e)?[2,wS(e)]:Array.isArray(e)&&e.every(function(n){return"getFile"in n&&typeof n.getFile=="function"})?[2,vS(e)]:[2,[]]})})}function _S(e){return Hh(e)}function yS(e){return Hh(e)&&Hh(e.target)}function Hh(e){return typeof e=="object"&&e!==null}function wS(e){return g_(e.target.files).map(function(t){return Jf(t)})}function vS(e){return iu(this,void 0,void 0,function(){var t;return ou(this,function(n){switch(n.label){case 0:return[4,Promise.all(e.map(function(o){return o.getFile()}))];case 1:return t=n.sent(),[2,t.map(function(o){return Jf(o)})]}})})}function bS(e,t){return iu(this,void 0,void 0,function(){var n,o;return ou(this,function(a){switch(a.label){case 0:return e.items?(n=g_(e.items).filter(function(l){return l.kind==="file"}),t!=="drop"?[2,n]:[4,Promise.all(n.map(xS))]):[3,2];case 1:return o=a.sent(),[2,u1(L2(o))];case 2:return[2,u1(g_(e.files).map(function(l){return Jf(l)}))]}})})}function u1(e){return e.filter(function(t){return mS.indexOf(t.name)===-1})}function g_(e){if(e===null)return[];for(var t=[],n=0;n<e.length;n++){var o=e[n];t.push(o)}return t}function xS(e){if(typeof e.webkitGetAsEntry!="function")return c1(e);var t=e.webkitGetAsEntry();return t&&t.isDirectory?R2(t):c1(e)}function L2(e){return e.reduce(function(t,n){return l1(l1([],a1(t),!1),a1(Array.isArray(n)?L2(n):[n]),!1)},[])}function c1(e){var t=e.getAsFile();if(!t)return Promise.reject("".concat(e," is not a File"));var n=Jf(t);return Promise.resolve(n)}function MS(e){return iu(this,void 0,void 0,function(){return ou(this,function(t){return[2,e.isDirectory?R2(e):TS(e)]})})}function R2(e){var t=e.createReader();return new Promise(function(n,o){var a=[];function l(){var f=this;t.readEntries(function(_){return iu(f,void 0,void 0,function(){var h,g,M;return ou(this,function(w){switch(w.label){case 0:if(_.length)return[3,5];w.label=1;case 1:return w.trys.push([1,3,,4]),[4,Promise.all(a)];case 2:return h=w.sent(),n(h),[3,4];case 3:return g=w.sent(),o(g),[3,4];case 4:return[3,6];case 5:M=Promise.all(_.map(MS)),a.push(M),l(),w.label=6;case 6:return[2]}})})},function(_){o(_)})}l()})}function TS(e){return iu(this,void 0,void 0,function(){return ou(this,function(t){return[2,new Promise(function(n,o){e.file(function(a){var l=Jf(a,e.fullPath);n(l)},function(a){o(a)})})]})})}var kS=function(e,t){if(e&&t){var n=Array.isArray(t)?t:t.split(","),o=e.name||"",a=(e.type||"").toLowerCase(),l=a.replace(/\/.*$/,"");return n.some(function(f){var _=f.trim().toLowerCase();return _.charAt(0)==="."?o.toLowerCase().endsWith(_):_.endsWith("/*")?l===_.replace(/\/.*$/,""):a===_})}return!0};function d1(e){return CS(e)||ES(e)||N2(e)||SS()}function SS(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ES(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function CS(e){if(Array.isArray(e))return __(e)}function f1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,o)}return n}function p1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?f1(Object(n),!0).forEach(function(o){B2(e,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f1(Object(n)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(n,o))})}return e}function B2(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hf(e,t){return AS(e)||$S(e,t)||N2(e,t)||PS()}function PS(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N2(e,t){if(e){if(typeof e=="string")return __(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return __(e,t)}}function __(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=e[n];return o}function $S(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var o=[],a=!0,l=!1,f,_;try{for(n=n.call(e);!(a=(f=n.next()).done)&&(o.push(f.value),!(t&&o.length===t));a=!0);}catch(h){l=!0,_=h}finally{try{!a&&n.return!=null&&n.return()}finally{if(l)throw _}}return o}}function AS(e){if(Array.isArray(e))return e}var IS="file-invalid-type",FS="file-too-large",zS="file-too-small",OS="too-many-files",DS=function(t){t=Array.isArray(t)&&t.length===1?t[0]:t;var n=Array.isArray(t)?"one of ".concat(t.join(", ")):t;return{code:IS,message:"File type must be ".concat(n)}},h1=function(t){return{code:FS,message:"File is larger than ".concat(t," ").concat(t===1?"byte":"bytes")}},m1=function(t){return{code:zS,message:"File is smaller than ".concat(t," ").concat(t===1?"byte":"bytes")}},LS={code:OS,message:"Too many files"};function j2(e,t){var n=e.type==="application/x-moz-file"||kS(e,t);return[n,n?null:DS(t)]}function U2(e,t,n){if(Zs(e.size))if(Zs(t)&&Zs(n)){if(e.size>n)return[!1,h1(n)];if(e.size<t)return[!1,m1(t)]}else{if(Zs(t)&&e.size<t)return[!1,m1(t)];if(Zs(n)&&e.size>n)return[!1,h1(n)]}return[!0,null]}function Zs(e){return e!=null}function RS(e){var t=e.files,n=e.accept,o=e.minSize,a=e.maxSize,l=e.multiple,f=e.maxFiles,_=e.validator;return!l&&t.length>1||l&&f>=1&&t.length>f?!1:t.every(function(h){var g=j2(h,n),M=Hf(g,1),w=M[0],C=U2(h,o,a),k=Hf(C,1),z=k[0],S=_?_(h):null;return w&&z&&!S})}function Kh(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function lh(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,function(t){return t==="Files"||t==="application/x-moz-file"}):!!e.target&&!!e.target.files}function g1(e){e.preventDefault()}function BS(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function NS(e){return e.indexOf("Edge/")!==-1}function jS(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return BS(e)||NS(e)}function oo(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(o){for(var a=arguments.length,l=new Array(a>1?a-1:0),f=1;f<a;f++)l[f-1]=arguments[f];return t.some(function(_){return!Kh(o)&&_&&_.apply(void 0,[o].concat(l)),Kh(o)})}}function US(){return"showOpenFilePicker"in window}function VS(e){if(Zs(e)){var t=Object.entries(e).filter(function(n){var o=Hf(n,2),a=o[0],l=o[1],f=!0;return V2(a)||(console.warn('Skipped "'.concat(a,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),f=!1),(!Array.isArray(l)||!l.every(W2))&&(console.warn('Skipped "'.concat(a,'" because an invalid file extension was provided.')),f=!1),f}).reduce(function(n,o){var a=Hf(o,2),l=a[0],f=a[1];return p1(p1({},n),{},B2({},l,f))},{});return[{description:"Files",accept:t}]}return e}function WS(e){if(Zs(e))return Object.entries(e).reduce(function(t,n){var o=Hf(n,2),a=o[0],l=o[1];return[].concat(d1(t),[a],d1(l))},[]).filter(function(t){return V2(t)||W2(t)}).join(",")}function GS(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function qS(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function V2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function W2(e){return/^.*\.[\w]+$/.test(e)}var HS=["children"],KS=["open"],QS=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],XS=["refKey","onChange","onClick"];function YS(e){return eE(e)||JS(e)||G2(e)||ZS()}function ZS(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function JS(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function eE(e){if(Array.isArray(e))return y_(e)}function Mg(e,t){return nE(e)||rE(e,t)||G2(e,t)||tE()}function tE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function G2(e,t){if(e){if(typeof e=="string")return y_(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return y_(e,t)}}function y_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=e[n];return o}function rE(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var o=[],a=!0,l=!1,f,_;try{for(n=n.call(e);!(a=(f=n.next()).done)&&(o.push(f.value),!(t&&o.length===t));a=!0);}catch(h){l=!0,_=h}finally{try{!a&&n.return!=null&&n.return()}finally{if(l)throw _}}return o}}function nE(e){if(Array.isArray(e))return e}function _1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,o)}return n}function tn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_1(Object(n),!0).forEach(function(o){w_(e,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_1(Object(n)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(n,o))})}return e}function w_(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Qh(e,t){if(e==null)return{};var n=iE(e,t),o,a;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(a=0;a<l.length;a++)o=l[a],!(t.indexOf(o)>=0)&&Object.prototype.propertyIsEnumerable.call(e,o)&&(n[o]=e[o])}return n}function iE(e,t){if(e==null)return{};var n={},o=Object.keys(e),a,l;for(l=0;l<o.length;l++)a=o[l],!(t.indexOf(a)>=0)&&(n[a]=e[a]);return n}var g0=hr.forwardRef(function(e,t){var n=e.children,o=Qh(e,HS),a=H2(o),l=a.open,f=Qh(a,KS);return hr.useImperativeHandle(t,function(){return{open:l}},[l]),XM.createElement(hr.Fragment,null,n(tn(tn({},f),{},{open:l})))});g0.displayName="Dropzone";var q2={disabled:!1,getFilesFromEvent:gS,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};g0.defaultProps=q2;g0.propTypes={children:Ur.func,accept:Ur.objectOf(Ur.arrayOf(Ur.string)),multiple:Ur.bool,preventDropOnDocument:Ur.bool,noClick:Ur.bool,noKeyboard:Ur.bool,noDrag:Ur.bool,noDragEventsBubbling:Ur.bool,minSize:Ur.number,maxSize:Ur.number,maxFiles:Ur.number,disabled:Ur.bool,getFilesFromEvent:Ur.func,onFileDialogCancel:Ur.func,onFileDialogOpen:Ur.func,useFsAccessApi:Ur.bool,autoFocus:Ur.bool,onDragEnter:Ur.func,onDragLeave:Ur.func,onDragOver:Ur.func,onDrop:Ur.func,onDropAccepted:Ur.func,onDropRejected:Ur.func,onError:Ur.func,validator:Ur.func};var v_={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function H2(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=tn(tn({},q2),e),n=t.accept,o=t.disabled,a=t.getFilesFromEvent,l=t.maxSize,f=t.minSize,_=t.multiple,h=t.maxFiles,g=t.onDragEnter,M=t.onDragLeave,w=t.onDragOver,C=t.onDrop,k=t.onDropAccepted,z=t.onDropRejected,S=t.onFileDialogCancel,P=t.onFileDialogOpen,y=t.useFsAccessApi,x=t.autoFocus,I=t.preventDropOnDocument,U=t.noClick,O=t.noKeyboard,N=t.noDrag,j=t.noDragEventsBubbling,D=t.onError,Y=t.validator,de=hr.useMemo(function(){return WS(n)},[n]),Ce=hr.useMemo(function(){return VS(n)},[n]),ee=hr.useMemo(function(){return typeof P=="function"?P:y1},[P]),ye=hr.useMemo(function(){return typeof S=="function"?S:y1},[S]),R=hr.useRef(null),Me=hr.useRef(null),Qe=hr.useReducer(oE,v_),ge=Mg(Qe,2),Q=ge[0],ae=ge[1],Se=Q.isFocused,X=Q.isFileDialogActive,me=hr.useRef(typeof window<"u"&&window.isSecureContext&&y&&US()),Ke=function(){!me.current&&X&&setTimeout(function(){if(Me.current){var ke=Me.current.files;ke.length||(ae({type:"closeDialog"}),ye())}},300)};hr.useEffect(function(){return window.addEventListener("focus",Ke,!1),function(){window.removeEventListener("focus",Ke,!1)}},[Me,X,ye,me]);var De=hr.useRef([]),Be=function(ke){R.current&&R.current.contains(ke.target)||(ke.preventDefault(),De.current=[])};hr.useEffect(function(){return I&&(document.addEventListener("dragover",g1,!1),document.addEventListener("drop",Be,!1)),function(){I&&(document.removeEventListener("dragover",g1),document.removeEventListener("drop",Be))}},[R,I]),hr.useEffect(function(){return!o&&x&&R.current&&R.current.focus(),function(){}},[R,x,o]);var We=hr.useCallback(function(le){D?D(le):console.error(le)},[D]),ot=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le),De.current=[].concat(YS(De.current),[le.target]),lh(le)&&Promise.resolve(a(le)).then(function(ke){if(!(Kh(le)&&!j)){var Ne=ke.length,ut=Ne>0&&RS({files:ke,accept:de,minSize:f,maxSize:l,multiple:_,maxFiles:h,validator:Y}),Je=Ne>0&&!ut;ae({isDragAccept:ut,isDragReject:Je,isDragActive:!0,type:"setDraggedFiles"}),g&&g(le)}}).catch(function(ke){return We(ke)})},[a,g,We,j,de,f,l,_,h,Y]),dt=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le);var ke=lh(le);if(ke&&le.dataTransfer)try{le.dataTransfer.dropEffect="copy"}catch{}return ke&&w&&w(le),!1},[w,j]),Ge=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le);var ke=De.current.filter(function(ut){return R.current&&R.current.contains(ut)}),Ne=ke.indexOf(le.target);Ne!==-1&&ke.splice(Ne,1),De.current=ke,!(ke.length>0)&&(ae({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),lh(le)&&M&&M(le))},[R,M,j]),Te=hr.useCallback(function(le,ke){var Ne=[],ut=[];le.forEach(function(Je){var Ve=j2(Je,de),Z=Mg(Ve,2),ve=Z[0],Re=Z[1],He=U2(Je,f,l),Xe=Mg(He,2),rt=Xe[0],ft=Xe[1],ht=Y?Y(Je):null;if(ve&&rt&&!ht)Ne.push(Je);else{var Mt=[Re,ft];ht&&(Mt=Mt.concat(ht)),ut.push({file:Je,errors:Mt.filter(function(wt){return wt})})}}),(!_&&Ne.length>1||_&&h>=1&&Ne.length>h)&&(Ne.forEach(function(Je){ut.push({file:Je,errors:[LS]})}),Ne.splice(0)),ae({acceptedFiles:Ne,fileRejections:ut,type:"setFiles"}),C&&C(Ne,ut,ke),ut.length>0&&z&&z(ut,ke),Ne.length>0&&k&&k(Ne,ke)},[ae,_,de,f,l,h,C,k,z,Y]),je=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le),De.current=[],lh(le)&&Promise.resolve(a(le)).then(function(ke){Kh(le)&&!j||Te(ke,le)}).catch(function(ke){return We(ke)}),ae({type:"reset"})},[a,Te,We,j]),Ye=hr.useCallback(function(){if(me.current){ae({type:"openDialog"}),ee();var le={multiple:_,types:Ce};window.showOpenFilePicker(le).then(function(ke){return a(ke)}).then(function(ke){Te(ke,null),ae({type:"closeDialog"})}).catch(function(ke){GS(ke)?(ye(ke),ae({type:"closeDialog"})):qS(ke)?(me.current=!1,Me.current?(Me.current.value=null,Me.current.click()):We(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):We(ke)});return}Me.current&&(ae({type:"openDialog"}),ee(),Me.current.value=null,Me.current.click())},[ae,ee,ye,y,Te,We,Ce,_]),tt=hr.useCallback(function(le){!R.current||!R.current.isEqualNode(le.target)||(le.key===" "||le.key==="Enter"||le.keyCode===32||le.keyCode===13)&&(le.preventDefault(),Ye())},[R,Ye]),A=hr.useCallback(function(){ae({type:"focus"})},[]),Ae=hr.useCallback(function(){ae({type:"blur"})},[]),$e=hr.useCallback(function(){U||(jS()?setTimeout(Ye,0):Ye())},[U,Ye]),se=function(ke){return o?null:ke},te=function(ke){return O?null:se(ke)},we=function(ke){return N?null:se(ke)},B=function(ke){j&&ke.stopPropagation()},J=hr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,ut=le.role,Je=le.onKeyDown,Ve=le.onFocus,Z=le.onBlur,ve=le.onClick,Re=le.onDragEnter,He=le.onDragOver,Xe=le.onDragLeave,rt=le.onDrop,ft=Qh(le,QS);return tn(tn(w_({onKeyDown:te(oo(Je,tt)),onFocus:te(oo(Ve,A)),onBlur:te(oo(Z,Ae)),onClick:se(oo(ve,$e)),onDragEnter:we(oo(Re,ot)),onDragOver:we(oo(He,dt)),onDragLeave:we(oo(Xe,Ge)),onDrop:we(oo(rt,je)),role:typeof ut=="string"&&ut!==""?ut:"presentation"},Ne,R),!o&&!O?{tabIndex:0}:{}),ft)}},[R,tt,A,Ae,$e,ot,dt,Ge,je,O,N,o]),L=hr.useCallback(function(le){le.stopPropagation()},[]),ue=hr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,ut=le.onChange,Je=le.onClick,Ve=Qh(le,XS),Z=w_({accept:de,multiple:_,type:"file",style:{display:"none"},onChange:se(oo(ut,je)),onClick:se(oo(Je,L)),tabIndex:-1},Ne,Me);return tn(tn({},Z),Ve)}},[Me,n,_,je,o]);return tn(tn({},Q),{},{isFocused:Se&&!o,getRootProps:J,getInputProps:ue,rootRef:R,inputRef:Me,open:se(Ye)})}function oE(e,t){switch(t.type){case"focus":return tn(tn({},e),{},{isFocused:!0});case"blur":return tn(tn({},e),{},{isFocused:!1});case"openDialog":return tn(tn({},v_),{},{isFileDialogActive:!0});case"closeDialog":return tn(tn({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return tn(tn({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return tn(tn({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return tn({},v_);default:return e}}function y1(){}var Mo={},sE={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(e,t,n)=>{e.exports=n.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,t,n)=>{n.r(t),n.d(t,{Environment:()=>Ae,Interpreter:()=>$e,Template:()=>we,parse:()=>Se,tokenize:()=>w});var o=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),a=Object.freeze({set:o.Set,for:o.For,in:o.In,is:o.Is,if:o.If,else:o.Else,endif:o.EndIf,elif:o.ElseIf,endfor:o.EndFor,and:o.And,or:o.Or,not:o.Not,"not in":o.NotIn,macro:o.Macro,endmacro:o.EndMacro,true:o.BooleanLiteral,false:o.BooleanLiteral,True:o.BooleanLiteral,False:o.BooleanLiteral}),l=class{constructor(B,J){this.value=B,this.type=J}};function f(B){return/\w/.test(B)}function _(B){return/[0-9]/.test(B)}var h=[["{%",o.OpenStatement],["%}",o.CloseStatement],["{{",o.OpenExpression],["}}",o.CloseExpression],["(",o.OpenParen],[")",o.CloseParen],["{",o.OpenCurlyBracket],["}",o.CloseCurlyBracket],["[",o.OpenSquareBracket],["]",o.CloseSquareBracket],[",",o.Comma],[".",o.Dot],[":",o.Colon],["|",o.Pipe],["<=",o.ComparisonBinaryOperator],[">=",o.ComparisonBinaryOperator],["==",o.ComparisonBinaryOperator],["!=",o.ComparisonBinaryOperator],["<",o.ComparisonBinaryOperator],[">",o.ComparisonBinaryOperator],["+",o.AdditiveBinaryOperator],["-",o.AdditiveBinaryOperator],["*",o.MultiplicativeBinaryOperator],["/",o.MultiplicativeBinaryOperator],["%",o.MultiplicativeBinaryOperator],["=",o.Equals]],g=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(B,J={}){return B.endsWith(` +`)&&(B=B.slice(0,-1)),B=B.replace(/{#.*?#}/gs,"{##}"),J.lstrip_blocks&&(B=B.replace(/^[ \t]*({[#%])/gm,"$1")),J.trim_blocks&&(B=B.replace(/([#%]})\n/g,"$1")),B.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function w(B,J={}){var Ne,ut,Je;const L=[],ue=M(B,J);let le=0;const ke=Ve=>{let Z="";for(;Ve(ue[le]);){if(ue[le]==="\\"){if(++le,le>=ue.length)throw new SyntaxError("Unexpected end of input");const ve=ue[le++],Re=g.get(ve);if(Re===void 0)throw new SyntaxError(`Unexpected escaped character: ${ve}`);Z+=Re;continue}if(Z+=ue[le++],le>=ue.length)throw new SyntaxError("Unexpected end of input")}return Z};e:for(;le<ue.length;){const Ve=(Ne=L.at(-1))==null?void 0:Ne.type;if(Ve===void 0||Ve===o.CloseStatement||Ve===o.CloseExpression){let ve="";for(;le<ue.length&&!(ue[le]==="{"&&(ue[le+1]==="%"||ue[le+1]==="{"));)ve+=ue[le++];if(ve.length>0){L.push(new l(ve,o.Text));continue}}ke(ve=>/\s/.test(ve));const Z=ue[le];if(Z==="-"||Z==="+"){const ve=(ut=L.at(-1))==null?void 0:ut.type;if(ve===o.Text||ve===void 0)throw new SyntaxError(`Unexpected character: ${Z}`);switch(ve){case o.Identifier:case o.NumericLiteral:case o.BooleanLiteral:case o.StringLiteral:case o.CloseParen:case o.CloseSquareBracket:break;default:{++le;const Re=ke(_);L.push(new l(`${Z}${Re}`,Re.length>0?o.NumericLiteral:o.UnaryOperator));continue}}}for(const[ve,Re]of h)if(ue.slice(le,le+ve.length)===ve){L.push(new l(ve,Re)),le+=ve.length;continue e}if(Z==="'"||Z==='"'){++le;const ve=ke(Re=>Re!==Z);L.push(new l(ve,o.StringLiteral)),++le;continue}if(_(Z)){const ve=ke(_);L.push(new l(ve,o.NumericLiteral));continue}if(f(Z)){const ve=ke(f),Re=Object.hasOwn(a,ve)?a[ve]:o.Identifier;Re===o.In&&((Je=L.at(-1))==null?void 0:Je.type)===o.Not?(L.pop(),L.push(new l("not in",o.NotIn))):L.push(new l(ve,Re));continue}throw new SyntaxError(`Unexpected character: ${Z}`)}return L}var C=class{constructor(){qe(this,"type","Statement")}},k=class extends C{constructor(J){super();qe(this,"type","Program");this.body=J}},z=class extends C{constructor(J,L,ue){super();qe(this,"type","If");this.test=J,this.body=L,this.alternate=ue}},S=class extends C{constructor(J,L,ue,le){super();qe(this,"type","For");this.loopvar=J,this.iterable=L,this.body=ue,this.defaultBlock=le}},P=class extends C{constructor(J,L){super();qe(this,"type","Set");this.assignee=J,this.value=L}},y=class extends C{constructor(J,L,ue){super();qe(this,"type","Macro");this.name=J,this.args=L,this.body=ue}},x=class extends C{constructor(){super(...arguments);qe(this,"type","Expression")}},I=class extends x{constructor(J,L,ue){super();qe(this,"type","MemberExpression");this.object=J,this.property=L,this.computed=ue}},U=class extends x{constructor(J,L){super();qe(this,"type","CallExpression");this.callee=J,this.args=L}},O=class extends x{constructor(J){super();qe(this,"type","Identifier");this.value=J}},N=class extends x{constructor(J){super();qe(this,"type","Literal");this.value=J}},j=class extends N{constructor(){super(...arguments);qe(this,"type","NumericLiteral")}},D=class extends N{constructor(){super(...arguments);qe(this,"type","StringLiteral")}},Y=class extends N{constructor(){super(...arguments);qe(this,"type","BooleanLiteral")}},de=class extends N{constructor(){super(...arguments);qe(this,"type","ArrayLiteral")}},Ce=class extends N{constructor(){super(...arguments);qe(this,"type","TupleLiteral")}},ee=class extends N{constructor(){super(...arguments);qe(this,"type","ObjectLiteral")}},ye=class extends x{constructor(J,L,ue){super();qe(this,"type","BinaryExpression");this.operator=J,this.left=L,this.right=ue}},R=class extends x{constructor(J,L){super();qe(this,"type","FilterExpression");this.operand=J,this.filter=L}},Me=class extends x{constructor(J,L){super();qe(this,"type","SelectExpression");this.iterable=J,this.test=L}},Qe=class extends x{constructor(J,L,ue){super();qe(this,"type","TestExpression");this.operand=J,this.negate=L,this.test=ue}},ge=class extends x{constructor(J,L){super();qe(this,"type","UnaryExpression");this.operator=J,this.argument=L}},Q=class extends x{constructor(J=void 0,L=void 0,ue=void 0){super();qe(this,"type","SliceExpression");this.start=J,this.stop=L,this.step=ue}},ae=class extends x{constructor(J,L){super();qe(this,"type","KeywordArgumentExpression");this.key=J,this.value=L}};function Se(B){const J=new k([]);let L=0;function ue(mt,Pt){const Bt=B[L++];if(!Bt||Bt.type!==mt)throw new Error(`Parser Error: ${Pt}. ${Bt.type} !== ${mt}.`);return Bt}function le(){switch(B[L].type){case o.Text:return ut();case o.OpenStatement:return Je();case o.OpenExpression:return Ve();default:throw new SyntaxError(`Unexpected token type: ${B[L].type}`)}}function ke(...mt){return L+mt.length<=B.length&&mt.some((Pt,Bt)=>Pt!==B[L+Bt].type)}function Ne(...mt){return L+mt.length<=B.length&&mt.every((Pt,Bt)=>Pt===B[L+Bt].type)}function ut(){return new D(ue(o.Text,"Expected text token").value)}function Je(){ue(o.OpenStatement,"Expected opening statement token");let mt;switch(B[L].type){case o.Set:++L,mt=Z(),ue(o.CloseStatement,"Expected closing statement token");break;case o.If:++L,mt=ve(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndIf,"Expected endif token"),ue(o.CloseStatement,"Expected %} token");break;case o.Macro:++L,mt=Re(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndMacro,"Expected endmacro token"),ue(o.CloseStatement,"Expected %} token");break;case o.For:++L,mt=Xe(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndFor,"Expected endfor token"),ue(o.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${B[L].type}`)}return mt}function Ve(){ue(o.OpenExpression,"Expected opening expression token");const mt=rt();return ue(o.CloseExpression,"Expected closing expression token"),mt}function Z(){const mt=rt();if(Ne(o.Equals)){++L;const Pt=Z();return new P(mt,Pt)}return mt}function ve(){var sn,Li,bi,Nr,mn,Wr,ci,Fr;const mt=rt();ue(o.CloseStatement,"Expected closing statement token");const Pt=[],Bt=[];for(;!(((sn=B[L])==null?void 0:sn.type)===o.OpenStatement&&(((Li=B[L+1])==null?void 0:Li.type)===o.ElseIf||((bi=B[L+1])==null?void 0:bi.type)===o.Else||((Nr=B[L+1])==null?void 0:Nr.type)===o.EndIf));)Pt.push(le());if(((mn=B[L])==null?void 0:mn.type)===o.OpenStatement&&((Wr=B[L+1])==null?void 0:Wr.type)!==o.EndIf)if(++L,Ne(o.ElseIf))ue(o.ElseIf,"Expected elseif token"),Bt.push(ve());else for(ue(o.Else,"Expected else token"),ue(o.CloseStatement,"Expected closing statement token");!(((ci=B[L])==null?void 0:ci.type)===o.OpenStatement&&((Fr=B[L+1])==null?void 0:Fr.type)===o.EndIf);)Bt.push(le());return new z(mt,Pt,Bt)}function Re(){const mt=Cr();if(mt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Pt=Ut();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndMacro);)Bt.push(le());return new y(mt,Pt,Bt)}function He(mt=!1){const Pt=mt?Cr:rt,Bt=[Pt()],sn=Ne(o.Comma);for(;sn&&(++L,Bt.push(Pt()),!!Ne(o.Comma)););return sn?new Ce(Bt):Bt[0]}function Xe(){const mt=He(!0);if(!(mt instanceof O||mt instanceof Ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${mt.type} instead`);ue(o.In,"Expected `in` keyword following loop variable");const Pt=rt();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndFor)&&ke(o.OpenStatement,o.Else);)Bt.push(le());const sn=[];if(Ne(o.OpenStatement,o.Else))for(++L,++L,ue(o.CloseStatement,"Expected closing statement token");ke(o.OpenStatement,o.EndFor);)sn.push(le());return new S(mt,Pt,Bt,sn)}function rt(){return ft()}function ft(){const mt=ht();if(Ne(o.If)){++L;const Pt=ht();if(Ne(o.Else)){++L;const Bt=ht();return new z(Pt,[mt],[Bt])}else return new Me(mt,Pt)}return mt}function ht(){let mt=Mt();for(;Ne(o.Or);){const Pt=B[L];++L;const Bt=Mt();mt=new ye(Pt,mt,Bt)}return mt}function Mt(){let mt=wt();for(;Ne(o.And);){const Pt=B[L];++L;const Bt=wt();mt=new ye(Pt,mt,Bt)}return mt}function wt(){let mt;for(;Ne(o.Not);){const Pt=B[L];++L;const Bt=wt();mt=new ge(Pt,Bt)}return mt??St()}function St(){let mt=Rt();for(;Ne(o.ComparisonBinaryOperator)||Ne(o.In)||Ne(o.NotIn);){const Pt=B[L];++L;const Bt=Rt();mt=new ye(Pt,mt,Bt)}return mt}function Rt(){let mt=qt();for(;Ne(o.AdditiveBinaryOperator);){const Pt=B[L];++L;const Bt=qt();mt=new ye(Pt,mt,Bt)}return mt}function at(){const mt=Jt();return Ne(o.OpenParen)?Ot(mt):mt}function Ot(mt){let Pt=new U(mt,Ut());return Ne(o.OpenParen)&&(Pt=Ot(Pt)),Pt}function Ut(){ue(o.OpenParen,"Expected opening parenthesis for arguments list");const mt=Kt();return ue(o.CloseParen,"Expected closing parenthesis for arguments list"),mt}function Kt(){const mt=[];for(;!Ne(o.CloseParen);){let Pt=rt();if(Ne(o.Equals)){if(++L,!(Pt instanceof O))throw new SyntaxError("Expected identifier for keyword argument");const Bt=rt();Pt=new ae(Pt,Bt)}mt.push(Pt),Ne(o.Comma)&&++L}return mt}function Qt(){const mt=[];let Pt=!1;for(;!Ne(o.CloseSquareBracket);)Ne(o.Colon)?(mt.push(void 0),++L,Pt=!0):(mt.push(rt()),Ne(o.Colon)&&(++L,Pt=!0));if(mt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Pt){if(mt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Q(...mt)}return mt[0]}function Jt(){let mt=Cr();for(;Ne(o.Dot)||Ne(o.OpenSquareBracket);){const Pt=B[L];++L;let Bt;const sn=Pt.type!==o.Dot;if(sn)Bt=Qt(),ue(o.CloseSquareBracket,"Expected closing square bracket");else if(Bt=Cr(),Bt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");mt=new I(mt,Bt,sn)}return mt}function qt(){let mt=Er();for(;Ne(o.MultiplicativeBinaryOperator);){const Pt=B[L];++L;const Bt=Er();mt=new ye(Pt,mt,Bt)}return mt}function Er(){let mt=Qr();for(;Ne(o.Is);){++L;const Pt=Ne(o.Not);Pt&&++L;let Bt=Cr();if(Bt instanceof Y&&(Bt=new O(Bt.value.toString())),!(Bt instanceof O))throw new SyntaxError("Expected identifier for the test");mt=new Qe(mt,Pt,Bt)}return mt}function Qr(){let mt=at();for(;Ne(o.Pipe);){++L;let Pt=Cr();if(!(Pt instanceof O))throw new SyntaxError("Expected identifier for the filter");Ne(o.OpenParen)&&(Pt=Ot(Pt)),mt=new R(mt,Pt)}return mt}function Cr(){const mt=B[L];switch(mt.type){case o.NumericLiteral:return++L,new j(Number(mt.value));case o.StringLiteral:return++L,new D(mt.value);case o.BooleanLiteral:return++L,new Y(mt.value.toLowerCase()==="true");case o.Identifier:return++L,new O(mt.value);case o.OpenParen:{++L;const Pt=He();if(B[L].type!==o.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${B[L].type} instead`);return++L,Pt}case o.OpenSquareBracket:{++L;const Pt=[];for(;!Ne(o.CloseSquareBracket);)Pt.push(rt()),Ne(o.Comma)&&++L;return++L,new de(Pt)}case o.OpenCurlyBracket:{++L;const Pt=new Map;for(;!Ne(o.CloseCurlyBracket);){const Bt=rt();ue(o.Colon,"Expected colon between key and value in object literal");const sn=rt();Pt.set(Bt,sn),Ne(o.Comma)&&++L}return++L,new ee(Pt)}default:throw new SyntaxError(`Unexpected token: ${mt.type}`)}}for(;L<B.length;)J.body.push(le());return J}function X(B,J,L=1){J===void 0&&(J=B,B=0);const ue=[];for(let le=B;le<J;le+=L)ue.push(le);return ue}function me(B,J,L,ue=1){const le=Math.sign(ue);le>=0?(J=(J??(J=0))<0?Math.max(B.length+J,0):Math.min(J,B.length),L=(L??(L=B.length))<0?Math.max(B.length+L,0):Math.min(L,B.length)):(J=(J??(J=B.length-1))<0?Math.max(B.length+J,-1):Math.min(J,B.length-1),L=(L??(L=-1))<-1?Math.max(B.length+L,-1):Math.min(L,B.length-1));const ke=[];for(let Ne=J;le*Ne<le*L;Ne+=ue)ke.push(B[Ne]);return ke}function Ke(B){return B.replace(/\b\w/g,J=>J.toUpperCase())}var De=class{constructor(B=void 0){qe(this,"type","RuntimeValue");qe(this,"value");qe(this,"builtins",new Map);this.value=B}__bool__(){return new ot(!!this.value)}},Be=class extends De{constructor(){super(...arguments);qe(this,"type","NumericValue")}},We=class extends De{constructor(){super(...arguments);qe(this,"type","StringValue");qe(this,"builtins",new Map([["upper",new Ye(()=>new We(this.value.toUpperCase()))],["lower",new Ye(()=>new We(this.value.toLowerCase()))],["strip",new Ye(()=>new We(this.value.trim()))],["title",new Ye(()=>new We(Ke(this.value)))],["length",new Be(this.value.length)]]))}},ot=class extends De{constructor(){super(...arguments);qe(this,"type","BooleanValue")}},dt=class extends De{constructor(){super(...arguments);qe(this,"type","ObjectValue");qe(this,"builtins",new Map([["get",new Ye(([J,L])=>{if(!(J instanceof We))throw new Error(`Object key must be a string: got ${J.type}`);return this.value.get(J.value)??L??new tt})],["items",new Ye(()=>new Te(Array.from(this.value.entries()).map(([J,L])=>new Te([new We(J),L]))))]]))}__bool__(){return new ot(this.value.size>0)}},Ge=class extends dt{constructor(){super(...arguments);qe(this,"type","KeywordArgumentsValue")}},Te=class extends De{constructor(){super(...arguments);qe(this,"type","ArrayValue");qe(this,"builtins",new Map([["length",new Be(this.value.length)]]))}__bool__(){return new ot(this.value.length>0)}},je=class extends Te{constructor(){super(...arguments);qe(this,"type","TupleValue")}},Ye=class extends De{constructor(){super(...arguments);qe(this,"type","FunctionValue")}},tt=class extends De{constructor(){super(...arguments);qe(this,"type","NullValue")}},A=class extends De{constructor(){super(...arguments);qe(this,"type","UndefinedValue")}},Ae=class{constructor(B){qe(this,"variables",new Map([["namespace",new Ye(B=>{if(B.length===0)return new dt(new Map);if(B.length!==1||!(B[0]instanceof dt))throw new Error("`namespace` expects either zero arguments or a single object argument");return B[0]})]]));qe(this,"tests",new Map([["boolean",B=>B.type==="BooleanValue"],["callable",B=>B instanceof Ye],["odd",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${B.type}`);return B.value%2!==0}],["even",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${B.type}`);return B.value%2===0}],["false",B=>B.type==="BooleanValue"&&!B.value],["true",B=>B.type==="BooleanValue"&&B.value],["string",B=>B.type==="StringValue"],["number",B=>B.type==="NumericValue"],["integer",B=>B.type==="NumericValue"&&Number.isInteger(B.value)],["iterable",B=>B instanceof Te||B instanceof We],["lower",B=>{const J=B.value;return B.type==="StringValue"&&J===J.toLowerCase()}],["upper",B=>{const J=B.value;return B.type==="StringValue"&&J===J.toUpperCase()}],["none",B=>B.type==="NullValue"],["defined",B=>B.type!=="UndefinedValue"],["undefined",B=>B.type==="UndefinedValue"],["equalto",(B,J)=>B.value===J.value],["eq",(B,J)=>B.value===J.value]]));this.parent=B}set(B,J){return this.declareVariable(B,se(J))}declareVariable(B,J){if(this.variables.has(B))throw new SyntaxError(`Variable already declared: ${B}`);return this.variables.set(B,J),J}setVariable(B,J){return this.variables.set(B,J),J}resolve(B){if(this.variables.has(B))return this;if(this.parent)return this.parent.resolve(B);throw new Error(`Unknown variable: ${B}`)}lookupVariable(B){try{return this.resolve(B).variables.get(B)??new A}catch{return new A}}},$e=class{constructor(B){qe(this,"global");this.global=B??new Ae}run(B){return this.evaluate(B,this.global)}evaluateBinaryExpression(B,J){const L=this.evaluate(B.left,J);switch(B.operator.value){case"and":return L.__bool__().value?this.evaluate(B.right,J):L;case"or":return L.__bool__().value?L:this.evaluate(B.right,J)}const ue=this.evaluate(B.right,J);switch(B.operator.value){case"==":return new ot(L.value==ue.value);case"!=":return new ot(L.value!=ue.value)}if(L instanceof A||ue instanceof A)throw new Error("Cannot perform operation on undefined values");if(L instanceof tt||ue instanceof tt)throw new Error("Cannot perform operation on null values");if(L instanceof Be&&ue instanceof Be)switch(B.operator.value){case"+":return new Be(L.value+ue.value);case"-":return new Be(L.value-ue.value);case"*":return new Be(L.value*ue.value);case"/":return new Be(L.value/ue.value);case"%":return new Be(L.value%ue.value);case"<":return new ot(L.value<ue.value);case">":return new ot(L.value>ue.value);case">=":return new ot(L.value>=ue.value);case"<=":return new ot(L.value<=ue.value)}else if(L instanceof Te&&ue instanceof Te)switch(B.operator.value){case"+":return new Te(L.value.concat(ue.value))}else if(ue instanceof Te){const le=ue.value.find(ke=>ke.value===L.value)!==void 0;switch(B.operator.value){case"in":return new ot(le);case"not in":return new ot(!le)}}if(L instanceof We||ue instanceof We)switch(B.operator.value){case"+":return new We(L.value.toString()+ue.value.toString())}if(L instanceof We&&ue instanceof We)switch(B.operator.value){case"in":return new ot(ue.value.includes(L.value));case"not in":return new ot(!ue.value.includes(L.value))}if(L instanceof We&&ue instanceof dt)switch(B.operator.value){case"in":return new ot(ue.value.has(L.value));case"not in":return new ot(!ue.value.has(L.value))}throw new SyntaxError(`Unknown operator "${B.operator.value}" between ${L.type} and ${ue.type}`)}evaluateArguments(B,J){const L=[],ue=new Map;for(const le of B)if(le.type==="KeywordArgumentExpression"){const ke=le;ue.set(ke.key.value,this.evaluate(ke.value,J))}else{if(ue.size>0)throw new Error("Positional arguments must come before keyword arguments");L.push(this.evaluate(le,J))}return[L,ue]}evaluateFilterExpression(B,J){const L=this.evaluate(B.operand,J);if(B.filter.type==="Identifier"){const ue=B.filter;if(ue.value==="tojson")return new We(te(L));if(L instanceof Te)switch(ue.value){case"list":return L;case"first":return L.value[0];case"last":return L.value[L.value.length-1];case"length":return new Be(L.value.length);case"reverse":return new Te(L.value.reverse());case"sort":return new Te(L.value.sort((le,ke)=>{if(le.type!==ke.type)throw new Error(`Cannot compare different types: ${le.type} and ${ke.type}`);switch(le.type){case"NumericValue":return le.value-ke.value;case"StringValue":return le.value.localeCompare(ke.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${ue.value}`)}else if(L instanceof We)switch(ue.value){case"length":return new Be(L.value.length);case"upper":return new We(L.value.toUpperCase());case"lower":return new We(L.value.toLowerCase());case"title":return new We(Ke(L.value));case"capitalize":return new We(L.value.charAt(0).toUpperCase()+L.value.slice(1));case"trim":return new We(L.value.trim());case"indent":return new We(L.value.split(` +`).map((le,ke)=>ke===0||le.length===0?le:" "+le).join(` +`));case"string":return L;default:throw new Error(`Unknown StringValue filter: ${ue.value}`)}else if(L instanceof Be)switch(ue.value){case"abs":return new Be(Math.abs(L.value));default:throw new Error(`Unknown NumericValue filter: ${ue.value}`)}else if(L instanceof dt)switch(ue.value){case"items":return new Te(Array.from(L.value.entries()).map(([le,ke])=>new Te([new We(le),ke])));case"length":return new Be(L.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ue.value}`)}throw new Error(`Cannot apply filter "${ue.value}" to type: ${L.type}`)}else if(B.filter.type==="CallExpression"){const ue=B.filter;if(ue.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ue.callee.type}`);const le=ue.callee.value;if(le==="tojson"){const[,ke]=this.evaluateArguments(ue.args,J),Ne=ke.get("indent")??new tt;if(!(Ne instanceof Be||Ne instanceof tt))throw new Error("If set, indent must be a number");return new We(te(L,Ne.value))}if(L instanceof Te){switch(le){case"selectattr":{if(L.value.some(Z=>!(Z instanceof dt)))throw new Error("`selectattr` can only be applied to array of objects");if(ue.args.some(Z=>Z.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[ke,Ne,ut]=ue.args.map(Z=>this.evaluate(Z,J));let Je;if(Ne){const Z=J.tests.get(Ne.value);if(!Z)throw new Error(`Unknown test: ${Ne.value}`);Je=Z}else Je=(...Z)=>Z[0].__bool__().value;const Ve=L.value.filter(Z=>{const ve=Z.value.get(ke.value);return ve?Je(ve,ut):!1});return new Te(Ve)}case"map":{const[,ke]=this.evaluateArguments(ue.args,J);if(ke.has("attribute")){const Ne=ke.get("attribute");if(!(Ne instanceof We))throw new Error("attribute must be a string");const ut=ke.get("default"),Je=L.value.map(Ve=>{if(!(Ve instanceof dt))throw new Error("items in map must be an object");return Ve.value.get(Ne.value)??ut??new A});return new Te(Je)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(L instanceof We){switch(le){case"indent":{const[ke,Ne]=this.evaluateArguments(ue.args,J),ut=ke.at(0)??Ne.get("width")??new Be(4);if(!(ut instanceof Be))throw new Error("width must be a number");const Je=ke.at(1)??Ne.get("first")??new ot(!1),Ve=ke.at(2)??Ne.get("blank")??new ot(!1),Z=L.value.split(` +`),ve=" ".repeat(ut.value),Re=Z.map((He,Xe)=>!Je.value&&Xe===0||!Ve.value&&He.length===0?He:ve+He);return new We(Re.join(` +`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${L.type}`)}throw new Error(`Unknown filter: ${B.filter.type}`)}evaluateTestExpression(B,J){const L=this.evaluate(B.operand,J),ue=J.tests.get(B.test.value);if(!ue)throw new Error(`Unknown test: ${B.test.value}`);const le=ue(L);return new ot(B.negate?!le:le)}evaluateUnaryExpression(B,J){const L=this.evaluate(B.argument,J);switch(B.operator.value){case"not":return new ot(!L.value);default:throw new SyntaxError(`Unknown operator: ${B.operator.value}`)}}evalProgram(B,J){return this.evaluateBlock(B.body,J)}evaluateBlock(B,J){let L="";for(const ue of B){const le=this.evaluate(ue,J);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(L+=le.value)}return new We(L)}evaluateIdentifier(B,J){return J.lookupVariable(B.value)}evaluateCallExpression(B,J){const[L,ue]=this.evaluateArguments(B.args,J);ue.size>0&&L.push(new Ge(ue));const le=this.evaluate(B.callee,J);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(L,J)}evaluateSliceExpression(B,J,L){if(!(B instanceof Te||B instanceof We))throw new Error("Slice object must be an array or string");const ue=this.evaluate(J.start,L),le=this.evaluate(J.stop,L),ke=this.evaluate(J.step,L);if(!(ue instanceof Be||ue instanceof A))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof Be||le instanceof A))throw new Error("Slice stop must be numeric or undefined");if(!(ke instanceof Be||ke instanceof A))throw new Error("Slice step must be numeric or undefined");return B instanceof Te?new Te(me(B.value,ue.value,le.value,ke.value)):new We(me(Array.from(B.value),ue.value,le.value,ke.value).join(""))}evaluateMemberExpression(B,J){const L=this.evaluate(B.object,J);let ue;if(B.computed){if(B.property.type==="SliceExpression")return this.evaluateSliceExpression(L,B.property,J);ue=this.evaluate(B.property,J)}else ue=new We(B.property.value);let le;if(L instanceof dt){if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=L.value.get(ue.value)??L.builtins.get(ue.value)}else if(L instanceof Te||L instanceof We)if(ue instanceof Be)le=L.value.at(ue.value),L instanceof We&&(le=new We(L.value.at(ue.value)));else if(ue instanceof We)le=L.builtins.get(ue.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ue.type}`);else{if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=L.builtins.get(ue.value)}return le instanceof De?le:new A}evaluateSet(B,J){const L=this.evaluate(B.value,J);if(B.assignee.type==="Identifier"){const ue=B.assignee.value;J.setVariable(ue,L)}else if(B.assignee.type==="MemberExpression"){const ue=B.assignee,le=this.evaluate(ue.object,J);if(!(le instanceof dt))throw new Error("Cannot assign to member of non-object");if(ue.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(ue.property.value,L)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(B.assignee)}`);return new tt}evaluateIf(B,J){const L=this.evaluate(B.test,J);return this.evaluateBlock(L.__bool__().value?B.body:B.alternate,J)}evaluateFor(B,J){const L=new Ae(J);let ue,le;if(B.iterable.type==="SelectExpression"){const Ve=B.iterable;le=this.evaluate(Ve.iterable,L),ue=Ve.test}else le=this.evaluate(B.iterable,L);if(!(le instanceof Te))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ke=[],Ne=[];for(let Ve=0;Ve<le.value.length;++Ve){const Z=new Ae(L),ve=le.value[Ve];let Re;if(B.loopvar.type==="Identifier")Re=He=>He.setVariable(B.loopvar.value,ve);else if(B.loopvar.type==="TupleLiteral"){const He=B.loopvar;if(ve.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ve.type}`);const Xe=ve;if(He.value.length!==Xe.value.length)throw new Error(`Too ${He.value.length>Xe.value.length?"few":"many"} items to unpack`);Re=rt=>{for(let ft=0;ft<He.value.length;++ft){if(He.value[ft].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${He.value[ft].type}`);rt.setVariable(He.value[ft].value,Xe.value[ft])}}}else throw new Error(`Invalid loop variable(s): ${B.loopvar.type}`);ue&&(Re(Z),!this.evaluate(ue,Z).__bool__().value)||(ke.push(ve),Ne.push(Re))}let ut="",Je=!0;for(let Ve=0;Ve<ke.length;++Ve){const Z=new Map([["index",new Be(Ve+1)],["index0",new Be(Ve)],["revindex",new Be(ke.length-Ve)],["revindex0",new Be(ke.length-Ve-1)],["first",new ot(Ve===0)],["last",new ot(Ve===ke.length-1)],["length",new Be(ke.length)],["previtem",Ve>0?ke[Ve-1]:new A],["nextitem",Ve<ke.length-1?ke[Ve+1]:new A]]);L.setVariable("loop",new dt(Z)),Ne[Ve](L);const ve=this.evaluateBlock(B.body,L);ut+=ve.value,Je=!1}if(Je){const Ve=this.evaluateBlock(B.defaultBlock,L);ut+=Ve.value}return new We(ut)}evaluateMacro(B,J){return J.setVariable(B.name.value,new Ye((L,ue)=>{var Ne;const le=new Ae(ue);L=L.slice();let ke;((Ne=L.at(-1))==null?void 0:Ne.type)==="KeywordArgumentsValue"&&(ke=L.pop());for(let ut=0;ut<B.args.length;++ut){const Je=B.args[ut],Ve=L[ut];if(Je.type==="Identifier"){const Z=Je;if(!Ve)throw new Error(`Missing positional argument: ${Z.value}`);le.setVariable(Z.value,Ve)}else if(Je.type==="KeywordArgumentExpression"){const Z=Je,ve=Ve??(ke==null?void 0:ke.value.get(Z.key.value))??this.evaluate(Z.value,le);le.setVariable(Z.key.value,ve)}else throw new Error(`Unknown argument type: ${Je.type}`)}return this.evaluateBlock(B.body,le)})),new tt}evaluate(B,J){if(B===void 0)return new A;switch(B.type){case"Program":return this.evalProgram(B,J);case"Set":return this.evaluateSet(B,J);case"If":return this.evaluateIf(B,J);case"For":return this.evaluateFor(B,J);case"Macro":return this.evaluateMacro(B,J);case"NumericLiteral":return new Be(Number(B.value));case"StringLiteral":return new We(B.value);case"BooleanLiteral":return new ot(B.value);case"ArrayLiteral":return new Te(B.value.map(L=>this.evaluate(L,J)));case"TupleLiteral":return new je(B.value.map(L=>this.evaluate(L,J)));case"ObjectLiteral":{const L=new Map;for(const[ue,le]of B.value){const ke=this.evaluate(ue,J);if(!(ke instanceof We))throw new Error(`Object keys must be strings: got ${ke.type}`);L.set(ke.value,this.evaluate(le,J))}return new dt(L)}case"Identifier":return this.evaluateIdentifier(B,J);case"CallExpression":return this.evaluateCallExpression(B,J);case"MemberExpression":return this.evaluateMemberExpression(B,J);case"UnaryExpression":return this.evaluateUnaryExpression(B,J);case"BinaryExpression":return this.evaluateBinaryExpression(B,J);case"FilterExpression":return this.evaluateFilterExpression(B,J);case"TestExpression":return this.evaluateTestExpression(B,J);default:throw new SyntaxError(`Unknown node type: ${B.type}`)}}};function se(B){switch(typeof B){case"number":return new Be(B);case"string":return new We(B);case"boolean":return new ot(B);case"undefined":return new A;case"object":return B===null?new tt:Array.isArray(B)?new Te(B.map(se)):new dt(new Map(Object.entries(B).map(([J,L])=>[J,se(L)])));case"function":return new Ye((J,L)=>{const ue=B(...J.map(le=>le.value))??null;return se(ue)});default:throw new Error(`Cannot convert to runtime value: ${B}`)}}function te(B,J,L){const ue=L??0;switch(B.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(B.value);case"ArrayValue":case"ObjectValue":{const le=J?" ".repeat(J):"",ke=` +`+le.repeat(ue),Ne=ke+le;if(B.type==="ArrayValue"){const ut=B.value.map(Je=>te(Je,J,ue+1));return J?`[${Ne}${ut.join(`,${Ne}`)}${ke}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(B.value.entries()).map(([Je,Ve])=>{const Z=`"${Je}": ${te(Ve,J,ue+1)}`;return J?`${Ne}${Z}`:Z});return J?`{${ut.join(",")}${ke}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${B.type}`)}}var we=class{constructor(B){qe(this,"parsed");const J=w(B,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Se(J)}render(B){const J=new Ae;J.set("false",!1),J.set("true",!0),J.set("raise_exception",le=>{throw new Error(le)}),J.set("range",X);for(const[le,ke]of Object.entries(B))J.set(le,ke);return new $e(J).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>l,resolveBackendAndExecutionProviders:()=>_});const o=new Map,a=[],l=(h,g,M)=>{if(g&&typeof g.init=="function"&&typeof g.createInferenceSessionHandler=="function"){const w=o.get(h);if(w===void 0)o.set(h,{backend:g,priority:M});else{if(w.priority>M)return;if(w.priority===M&&w.backend!==g)throw new Error(`cannot register backend "${h}" using priority ${M}`)}if(M>=0){const C=a.indexOf(h);C!==-1&&a.splice(C,1);for(let k=0;k<a.length;k++)if(o.get(a[k]).priority<=M){a.splice(k,0,h);return}a.push(h)}return}throw new TypeError("not a valid backend")},f=async h=>{const g=o.get(h);if(!g)return"backend not found.";if(g.initialized)return g.backend;if(g.aborted)return g.error;{const M=!!g.initPromise;try{return M||(g.initPromise=g.backend.init(h)),await g.initPromise,g.initialized=!0,g.backend}catch(w){return M||(g.error=`${w}`,g.aborted=!0),g.error}finally{delete g.initPromise}}},_=async h=>{const g=h.executionProviders||[],M=g.map(P=>typeof P=="string"?P:P.name),w=M.length===0?a:M;let C;const k=[],z=new Set;for(const P of w){const y=await f(P);typeof y=="string"?k.push({name:P,err:y}):(C||(C=y),C===y&&z.add(P))}if(!C)throw new Error(`no available backend found. ERR: ${k.map(P=>`[${P.name}] ${P.err}`).join(", ")}`);for(const{name:P,err:y}of k)M.includes(P)&&console.warn(`removing requested execution provider "${P}" from session options because it is not available: ${y}`);const S=g.filter(P=>z.has(typeof P=="string"?P:P.name));return[C,new Proxy(h,{get:(P,y)=>y==="executionProviders"?S:Reflect.get(P,y)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>o.registerBackend});var o=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,t,n)=>{n.r(t),n.d(t,{env:()=>l});var o=n("./node_modules/onnxruntime-common/dist/esm/version.js");let a="warning";const l={wasm:{},webgl:{},webgpu:{},versions:{common:o.version},set logLevel(f){if(f!==void 0){if(typeof f!="string"||["verbose","info","warning","error","fatal"].indexOf(f)===-1)throw new Error(`Unsupported logging level: ${f}`);a=f}},get logLevel(){return a}};Object.defineProperty(l,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,n)=>{n.r(t),n.d(t,{env:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=o.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>l.InferenceSession,TRACE:()=>_.TRACE,TRACE_FUNC_BEGIN:()=>_.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>_.TRACE_FUNC_END,Tensor:()=>f.Tensor,TrainingSession:()=>h.TrainingSession,env:()=>a.env,registerBackend:()=>o.registerBackend});var o=n("./node_modules/onnxruntime-common/dist/esm/backend.js"),a=n("./node_modules/onnxruntime-common/dist/esm/env.js"),l=n("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),f=n("./node_modules/onnxruntime-common/dist/esm/tensor.js");n("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),n("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var _=n("./node_modules/onnxruntime-common/dist/esm/trace.js");n("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),n("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var h=n("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>f});var o=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor.js"),l=n("./node_modules/onnxruntime-common/dist/esm/trace.js");class f{constructor(h){this.handler=h}async run(h,g,M){(0,l.TRACE_FUNC_BEGIN)();const w={};let C={};if(typeof h!="object"||h===null||h instanceof a.Tensor||Array.isArray(h))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let k=!0;if(typeof g=="object"){if(g===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(g instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(g)){if(g.length===0)throw new TypeError("'fetches' cannot be an empty array.");k=!1;for(const P of g){if(typeof P!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(P)===-1)throw new RangeError(`'fetches' contains invalid output name: ${P}.`);w[P]=null}if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let P=!1;const y=Object.getOwnPropertyNames(g);for(const x of this.outputNames)if(y.indexOf(x)!==-1){const I=g[x];(I===null||I instanceof a.Tensor)&&(P=!0,k=!1,w[x]=I)}if(P){if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else C=g}}else if(typeof g<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const P of this.inputNames)if(typeof h[P]>"u")throw new Error(`input '${P}' is missing in 'feeds'.`);if(k)for(const P of this.outputNames)w[P]=null;const z=await this.handler.run(h,w,C),S={};for(const P in z)if(Object.hasOwnProperty.call(z,P)){const y=z[P];y instanceof a.Tensor?S[P]=y:S[P]=new a.Tensor(y.type,y.data,y.dims)}return(0,l.TRACE_FUNC_END)(),S}async release(){return this.handler.dispose()}static async create(h,g,M,w){(0,l.TRACE_FUNC_BEGIN)();let C,k={};if(typeof h=="string"){if(C=h,typeof g=="object"&&g!==null)k=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(h instanceof Uint8Array){if(C=h,typeof g=="object"&&g!==null)k=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(h instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&h instanceof SharedArrayBuffer){const y=h;let x=0,I=h.byteLength;if(typeof g=="object"&&g!==null)k=g;else if(typeof g=="number"){if(x=g,!Number.isSafeInteger(x))throw new RangeError("'byteOffset' must be an integer.");if(x<0||x>=y.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${y.byteLength}).`);if(I=h.byteLength-x,typeof M=="number"){if(I=M,!Number.isSafeInteger(I))throw new RangeError("'byteLength' must be an integer.");if(I<=0||x+I>y.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${y.byteLength-x}].`);if(typeof w=="object"&&w!==null)k=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof g<"u")throw new TypeError("'options' must be an object.");C=new Uint8Array(y,x,I)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[z,S]=await(0,o.resolveBackendAndExecutionProviders)(k),P=await z.createInferenceSessionHandler(C,S);return(0,l.TRACE_FUNC_END)(),new f(P)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const a=o.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,t,n)=>{n.r(t),n.d(t,{tensorToDataURL:()=>o,tensorToImageData:()=>a});const o=(l,f)=>{const _=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_.width=l.dims[3],_.height=l.dims[2];const h=_.getContext("2d");if(h!=null){let g,M;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[3]):(g=l.dims[3],M=l.dims[2]);const w=(f==null?void 0:f.format)!==void 0?f.format:"RGB",C=f==null?void 0:f.norm;let k,z;C===void 0||C.mean===void 0?k=[255,255,255,255]:typeof C.mean=="number"?k=[C.mean,C.mean,C.mean,C.mean]:(k=[C.mean[0],C.mean[1],C.mean[2],0],C.mean[3]!==void 0&&(k[3]=C.mean[3])),C===void 0||C.bias===void 0?z=[0,0,0,0]:typeof C.bias=="number"?z=[C.bias,C.bias,C.bias,C.bias]:(z=[C.bias[0],C.bias[1],C.bias[2],0],C.bias[3]!==void 0&&(z[3]=C.bias[3]));const S=M*g;let P=0,y=S,x=S*2,I=-1;w==="RGBA"?(P=0,y=S,x=S*2,I=S*3):w==="RGB"?(P=0,y=S,x=S*2):w==="RBG"&&(P=0,x=S,y=S*2);for(let U=0;U<M;U++)for(let O=0;O<g;O++){const N=(l.data[P++]-z[0])*k[0],j=(l.data[y++]-z[1])*k[1],D=(l.data[x++]-z[2])*k[2],Y=I===-1?255:(l.data[I++]-z[3])*k[3];h.fillStyle="rgba("+N+","+j+","+D+","+Y+")",h.fillRect(O,U,1,1)}if("toDataURL"in _)return _.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},a=(l,f)=>{const _=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let h;if(_!=null){let g,M,w;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[1],w=l.dims[3]):(g=l.dims[3],M=l.dims[2],w=l.dims[1]);const C=f!==void 0&&f.format!==void 0?f.format:"RGB",k=f==null?void 0:f.norm;let z,S;k===void 0||k.mean===void 0?z=[255,255,255,255]:typeof k.mean=="number"?z=[k.mean,k.mean,k.mean,k.mean]:(z=[k.mean[0],k.mean[1],k.mean[2],255],k.mean[3]!==void 0&&(z[3]=k.mean[3])),k===void 0||k.bias===void 0?S=[0,0,0,0]:typeof k.bias=="number"?S=[k.bias,k.bias,k.bias,k.bias]:(S=[k.bias[0],k.bias[1],k.bias[2],0],k.bias[3]!==void 0&&(S[3]=k.bias[3]));const P=M*g;if(f!==void 0&&(f.format!==void 0&&w===4&&f.format!=="RGBA"||w===3&&f.format!=="RGB"&&f.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const y=4;let x=0,I=1,U=2,O=3,N=0,j=P,D=P*2,Y=-1;C==="RGBA"?(N=0,j=P,D=P*2,Y=P*3):C==="RGB"?(N=0,j=P,D=P*2):C==="RBG"&&(N=0,D=P,j=P*2),h=_.createImageData(g,M);for(let de=0;de<M*g;x+=y,I+=y,U+=y,O+=y,de++)h.data[x]=(l.data[N++]-S[0])*z[0],h.data[I]=(l.data[j++]-S[1])*z[1],h.data[U]=(l.data[D++]-S[2])*z[2],h.data[O]=Y===-1?255:(l.data[Y++]-S[3])*z[3]}else throw new Error("Can not access image data");return h}},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,t,n)=>{n.r(t),n.d(t,{bufferToTensor:()=>a,tensorFromGpuBuffer:()=>_,tensorFromImage:()=>l,tensorFromPinnedBuffer:()=>h,tensorFromTexture:()=>f});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=(g,M)=>{if(g===void 0)throw new Error("Image buffer must be defined");if(M.height===void 0||M.width===void 0)throw new Error("Image height and width must be defined");if(M.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:w,width:C}=M,k=M.norm??{mean:255,bias:0};let z,S;typeof k.mean=="number"?z=[k.mean,k.mean,k.mean,k.mean]:z=[k.mean[0],k.mean[1],k.mean[2],k.mean[3]??255],typeof k.bias=="number"?S=[k.bias,k.bias,k.bias,k.bias]:S=[k.bias[0],k.bias[1],k.bias[2],k.bias[3]??0];const P=M.format!==void 0?M.format:"RGBA",y=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",x=w*C,I=y==="RGBA"?new Float32Array(x*4):new Float32Array(x*3);let U=4,O=0,N=1,j=2,D=3,Y=0,de=x,Ce=x*2,ee=-1;P==="RGB"&&(U=3,O=0,N=1,j=2,D=-1),y==="RGBA"?ee=x*3:y==="RBG"?(Y=0,Ce=x,de=x*2):y==="BGR"&&(Ce=0,de=x,Y=x*2);for(let R=0;R<x;R++,O+=U,j+=U,N+=U,D+=U)I[Y++]=(g[O]+S[0])/z[0],I[de++]=(g[N]+S[1])/z[1],I[Ce++]=(g[j]+S[2])/z[2],ee!==-1&&D!==-1&&(I[ee++]=(g[D]+S[3])/z[3]);return y==="RGBA"?new o.Tensor("float32",I,[1,4,w,C]):new o.Tensor("float32",I,[1,3,w,C])},l=async(g,M)=>{const w=typeof HTMLImageElement<"u"&&g instanceof HTMLImageElement,C=typeof ImageData<"u"&&g instanceof ImageData,k=typeof ImageBitmap<"u"&&g instanceof ImageBitmap,z=typeof g=="string";let S,P=M??{};const y=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},x=I=>I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?I.getContext("2d"):null;if(w){const I=y();I.width=g.width,I.height=g.height;const U=x(I);if(U!=null){let O=g.height,N=g.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(O=M.resizedHeight,N=M.resizedWidth),M!==void 0){if(P=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");P.tensorFormat="RGBA",P.height=O,P.width=N}else P.tensorFormat="RGBA",P.height=O,P.width=N;U.drawImage(g,0,0),S=U.getImageData(0,0,N,O).data}else throw new Error("Can not access image data")}else if(C){let I,U;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(I=M.resizedHeight,U=M.resizedWidth):(I=g.height,U=g.width),M!==void 0&&(P=M),P.format="RGBA",P.height=I,P.width=U,M!==void 0){const O=y();O.width=U,O.height=I;const N=x(O);if(N!=null)N.putImageData(g,0,0),S=N.getImageData(0,0,U,I).data;else throw new Error("Can not access image data")}else S=g.data}else if(k){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const I=y();I.width=g.width,I.height=g.height;const U=x(I);if(U!=null){const O=g.height,N=g.width;return U.drawImage(g,0,0,N,O),S=U.getImageData(0,0,N,O).data,P.height=O,P.width=N,a(S,P)}else throw new Error("Can not access image data")}else{if(z)return new Promise((I,U)=>{const O=y(),N=x(O);if(!g||!N)return U();const j=new Image;j.crossOrigin="Anonymous",j.src=g,j.onload=()=>{O.width=j.width,O.height=j.height,N.drawImage(j,0,0,O.width,O.height);const D=N.getImageData(0,0,O.width,O.height);P.height=O.height,P.width=O.width,I(a(D.data,P))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(S!==void 0)return a(S,P);throw new Error("Input data provided is not supported - aborted tensor creation")},f=(g,M)=>{const{width:w,height:C,download:k,dispose:z}=M,S=[1,C,w,4];return new o.Tensor({location:"texture",type:"float32",texture:g,dims:S,download:k,dispose:z})},_=(g,M)=>{const{dataType:w,dims:C,download:k,dispose:z}=M;return new o.Tensor({location:"gpu-buffer",type:w??"float32",gpuBuffer:g,dims:C,download:k,dispose:z})},h=(g,M,w)=>new o.Tensor({location:"cpu-pinned",type:g,data:M,dims:w??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,t,n)=>{n.r(t),n.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>a,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>o,checkTypedArray:()=>f});const o=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),a=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let l=!1;const f=()=>{if(!l){l=!0;const _=typeof BigInt64Array<"u"&&BigInt64Array.from,h=typeof BigUint64Array<"u"&&BigUint64Array.from,g=typeof Float16Array<"u"&&Float16Array.from;_&&(o.set("int64",BigInt64Array),a.set(BigInt64Array,"int64")),h&&(o.set("uint64",BigUint64Array),a.set(BigUint64Array,"uint64")),g?(o.set("float16",Float16Array),a.set(Float16Array,"float16")):o.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>_});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),l=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),f=n("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class _{constructor(g,M,w){(0,l.checkTypedArray)();let C,k;if(typeof g=="object"&&"location"in g)switch(this.dataLocation=g.location,C=g.type,k=g.dims,g.location){case"cpu-pinned":{const S=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(C);if(!S)throw new TypeError(`unsupported type "${C}" to create tensor from pinned buffer`);if(!(g.data instanceof S))throw new TypeError(`buffer should be of type ${S.name}`);this.cpuData=g.data;break}case"texture":{if(C!=="float32")throw new TypeError(`unsupported type "${C}" to create tensor from texture`);this.gpuTextureData=g.texture,this.downloader=g.download,this.disposer=g.dispose;break}case"gpu-buffer":{if(C!=="float32"&&C!=="float16"&&C!=="int32"&&C!=="int64"&&C!=="uint32"&&C!=="uint8"&&C!=="bool")throw new TypeError(`unsupported type "${C}" to create tensor from gpu buffer`);this.gpuBufferData=g.gpuBuffer,this.downloader=g.download,this.disposer=g.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let S,P;if(typeof g=="string")if(C=g,P=w,g==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");S=M}else{const y=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(g);if(y===void 0)throw new TypeError(`Unsupported tensor type: ${g}.`);if(Array.isArray(M)){if(g==="float16"&&y===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");g==="uint64"||g==="int64"?S=y.from(M,BigInt):S=y.from(M)}else if(M instanceof y)S=M;else throw new TypeError(`A ${C} tensor's data must be type of ${y}`)}else if(P=M,Array.isArray(g)){if(g.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const y=typeof g[0];if(y==="string")C="string",S=g;else if(y==="boolean")C="bool",S=Uint8Array.from(g);else throw new TypeError(`Invalid element type of data array: ${y}.`)}else{const y=l.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(g.constructor);if(y===void 0)throw new TypeError(`Unsupported type for tensor data: ${g.constructor}.`);C=y,S=g}if(P===void 0)P=[S.length];else if(!Array.isArray(P))throw new TypeError("A tensor's dims must be a number array");k=P,this.cpuData=S,this.dataLocation="cpu"}const z=(0,f.calculateSize)(k);if(this.cpuData&&z!==this.cpuData.length)throw new Error(`Tensor's size(${z}) does not match data length(${this.cpuData.length}).`);this.type=C,this.dims=k,this.size=z}static async fromImage(g,M){return(0,a.tensorFromImage)(g,M)}static fromTexture(g,M){return(0,a.tensorFromTexture)(g,M)}static fromGpuBuffer(g,M){return(0,a.tensorFromGpuBuffer)(g,M)}static fromPinnedBuffer(g,M,w){return(0,a.tensorFromPinnedBuffer)(g,M,w)}toDataURL(g){return(0,o.tensorToDataURL)(this,g)}toImageData(g){return(0,o.tensorToImageData)(this,g)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(g){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const M=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=M,g&&this.disposer&&(this.disposer(),this.disposer=void 0),M}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(g){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,f.tensorReshape)(this,g)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,t,n)=>{n.r(t),n.d(t,{calculateSize:()=>a,tensorReshape:()=>l});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=f=>{let _=1;for(let h=0;h<f.length;h++){const g=f[h];if(typeof g!="number"||!Number.isSafeInteger(g))throw new TypeError(`dims[${h}] must be an integer, got: ${g}`);if(g<0)throw new RangeError(`dims[${h}] must be a non-negative integer, got: ${g}`);_*=g}return _},l=(f,_)=>{switch(f.location){case"cpu":return new o.Tensor(f.type,f.data,_);case"cpu-pinned":return new o.Tensor({location:"cpu-pinned",data:f.data,type:f.type,dims:_});case"texture":return new o.Tensor({location:"texture",texture:f.texture,type:f.type,dims:_});case"gpu-buffer":return new o.Tensor({location:"gpu-buffer",gpuBuffer:f.gpuBuffer,type:f.type,dims:_});default:throw new Error(`tensorReshape: tensor location ${f.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=o.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,t,n)=>{n.r(t),n.d(t,{TRACE:()=>a,TRACE_FUNC_BEGIN:()=>f,TRACE_FUNC_END:()=>_});var o=n("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=(h,g)=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||console.timeStamp(`${h}::ORT::${g}`)},l=(h,g)=>{var C;const M=((C=new Error().stack)==null?void 0:C.split(/\r\n|\r|\n/g))||[];let w=!1;for(let k=0;k<M.length;k++){if(w&&!M[k].includes("TRACE_FUNC")){let z=`FUNC_${h}::${M[k].trim().split(" ")[1]}`;g&&(z+=`::${g}`),a("CPU",z);return}M[k].includes("TRACE_FUNC")&&(w=!0)}},f=h=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||l("BEGIN",h)},_=h=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||l("END",h)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>f});var o=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor.js");const l="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class f{constructor(h,g,M){this.handler=h,this.hasOptimizerModel=g,this.hasEvalModel=M}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(h,g){const M=h.evalModel||"",w=h.optimizerModel||"",C=g||{},[k,z]=await(0,o.resolveBackendAndExecutionProviders)(C);if(k.createTrainingSessionHandler){const S=await k.createTrainingSessionHandler(h.checkpointState,h.trainModel,M,w,z);return new f(S,!!h.optimizerModel,!!h.evalModel)}else throw new Error(l)}typeNarrowingForRunStep(h,g,M,w,C){const k={};let z={};if(typeof M!="object"||M===null||M instanceof a.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let S=!0;if(typeof w=="object"){if(w===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(w instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(w)){if(w.length===0)throw new TypeError("'fetches' cannot be an empty array.");S=!1;for(const P of w){if(typeof P!="string")throw new TypeError("'fetches' must be a string array or an object.");if(g.indexOf(P)===-1)throw new RangeError(`'fetches' contains invalid output name: ${P}.`);k[P]=null}if(typeof C=="object"&&C!==null)z=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else{let P=!1;const y=Object.getOwnPropertyNames(w);for(const x of g)if(y.indexOf(x)!==-1){const I=w[x];(I===null||I instanceof a.Tensor)&&(P=!0,S=!1,k[x]=I)}if(P){if(typeof C=="object"&&C!==null)z=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else z=w}}else if(typeof w<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const P of h)if(typeof M[P]>"u")throw new Error(`input '${P}' is missing in 'feeds'.`);if(S)for(const P of g)k[P]=null;return[k,z]}convertHandlerReturnTypeToMapOfTensors(h){const g={};for(const M in h)if(Object.hasOwnProperty.call(h,M)){const w=h[M];w instanceof a.Tensor?g[M]=w:g[M]=new a.Tensor(w.type,w.data,w.dims)}return g}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(h,g,M){const[w,C]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,h,g,M),k=await this.handler.runTrainStep(h,w,C);return this.convertHandlerReturnTypeToMapOfTensors(k)}async runOptimizerStep(h){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(h||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(h,g,M){if(this.hasEvalModel){const[w,C]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,h,g,M),k=await this.handler.runEvalStep(h,w,C);return this.convertHandlerReturnTypeToMapOfTensors(k)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(h=!0){return this.handler.getParametersSize(h)}async loadParametersBuffer(h,g=!0){const M=await this.getParametersSize(g);if(h.length!==4*M)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(h,g)}async getContiguousParameters(h=!0){return this.handler.getContiguousParameters(h)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const a=o.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,t,n)=>{n.r(t),n.d(t,{version:()=>o});const o="1.19.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>te,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>tt,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>ut,default:()=>gx,env:()=>D,registerBackend:()=>z});/*! + * ONNX Runtime Web v1.20.0-dev.20240821-009209e016 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var o=Object.defineProperty,a=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,f=Object.prototype.hasOwnProperty,_=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(i,s)=>(typeof require<"u"?require:i)[s]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),h=(r,i)=>()=>(r&&(i=r(r=0)),i),g=(r,i)=>{for(var s in i)o(r,s,{get:i[s],enumerable:!0})},M=(r,i,s,u)=>{if(i&&typeof i=="object"||typeof i=="function")for(let c of l(i))!f.call(r,c)&&c!==s&&o(r,c,{get:()=>i[c],enumerable:!(u=a(i,c))||u.enumerable});return r},w=r=>M(o({},"__esModule",{value:!0}),r),C,k,z,S,P,y=h(()=>{C=new Map,k=[],z=(r,i,s)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let u=C.get(r);if(u===void 0)C.set(r,{backend:i,priority:s});else{if(u.priority>s)return;if(u.priority===s&&u.backend!==i)throw new Error(`cannot register backend "${r}" using priority ${s}`)}if(s>=0){let c=k.indexOf(r);c!==-1&&k.splice(c,1);for(let p=0;p<k.length;p++)if(C.get(k[p]).priority<=s){k.splice(p,0,r);return}k.push(r)}return}throw new TypeError("not a valid backend")},S=async r=>{let i=C.get(r);if(!i)return"backend not found.";if(i.initialized)return i.backend;if(i.aborted)return i.error;{let s=!!i.initPromise;try{return s||(i.initPromise=i.backend.init(r)),await i.initPromise,i.initialized=!0,i.backend}catch(u){return s||(i.error=`${u}`,i.aborted=!0),i.error}finally{delete i.initPromise}}},P=async r=>{let i=r.executionProviders||[],s=i.map(T=>typeof T=="string"?T:T.name),u=s.length===0?k:s,c,p=[],d=new Set;for(let T of u){let E=await S(T);typeof E=="string"?p.push({name:T,err:E}):(c||(c=E),c===E&&d.add(T))}if(!c)throw new Error(`no available backend found. ERR: ${p.map(T=>`[${T.name}] ${T.err}`).join(", ")}`);for(let{name:T,err:E}of p)s.includes(T)&&console.warn(`removing requested execution provider "${T}" from session options because it is not available: ${E}`);let b=i.filter(T=>d.has(typeof T=="string"?T:T.name));return[c,new Proxy(r,{get:(T,E)=>E==="executionProviders"?b:Reflect.get(T,E)})]}}),x=h(()=>{y()}),I,U=h(()=>{I="1.20.0-dev.20240816-b2d603abda"}),O,N,j=h(()=>{U(),O="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:I},set logLevel(r){if(r!==void 0){if(typeof r!="string"||["verbose","info","warning","error","fatal"].indexOf(r)===-1)throw new Error(`Unsupported logging level: ${r}`);O=r}},get logLevel(){return O}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),D,Y=h(()=>{j(),D=N}),de,Ce,ee=h(()=>{de=(r,i)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=r.dims[3],s.height=r.dims[2];let u=s.getContext("2d");if(u!=null){let c,p;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=r.dims[2],p=r.dims[3]):(c=r.dims[3],p=r.dims[2]);let d=(i==null?void 0:i.format)!==void 0?i.format:"RGB",b=i==null?void 0:i.norm,T,E;b===void 0||b.mean===void 0?T=[255,255,255,255]:typeof b.mean=="number"?T=[b.mean,b.mean,b.mean,b.mean]:(T=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(T[3]=b.mean[3])),b===void 0||b.bias===void 0?E=[0,0,0,0]:typeof b.bias=="number"?E=[b.bias,b.bias,b.bias,b.bias]:(E=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(E[3]=b.bias[3]));let q=p*c,H=0,v=q,ne=q*2,re=-1;d==="RGBA"?(H=0,v=q,ne=q*2,re=q*3):d==="RGB"?(H=0,v=q,ne=q*2):d==="RBG"&&(H=0,ne=q,v=q*2);for(let ce=0;ce<p;ce++)for(let _e=0;_e<c;_e++){let be=(r.data[H++]-E[0])*T[0],he=(r.data[v++]-E[1])*T[1],Fe=(r.data[ne++]-E[2])*T[2],xe=re===-1?255:(r.data[re++]-E[3])*T[3];u.fillStyle="rgba("+be+","+he+","+Fe+","+xe+")",u.fillRect(_e,ce,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Ce=(r,i)=>{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),u;if(s!=null){let c,p,d;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=r.dims[2],p=r.dims[1],d=r.dims[3]):(c=r.dims[3],p=r.dims[2],d=r.dims[1]);let b=i!==void 0&&i.format!==void 0?i.format:"RGB",T=i==null?void 0:i.norm,E,q;T===void 0||T.mean===void 0?E=[255,255,255,255]:typeof T.mean=="number"?E=[T.mean,T.mean,T.mean,T.mean]:(E=[T.mean[0],T.mean[1],T.mean[2],255],T.mean[3]!==void 0&&(E[3]=T.mean[3])),T===void 0||T.bias===void 0?q=[0,0,0,0]:typeof T.bias=="number"?q=[T.bias,T.bias,T.bias,T.bias]:(q=[T.bias[0],T.bias[1],T.bias[2],0],T.bias[3]!==void 0&&(q[3]=T.bias[3]));let H=p*c;if(i!==void 0&&(i.format!==void 0&&d===4&&i.format!=="RGBA"||d===3&&i.format!=="RGB"&&i.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let v=4,ne=0,re=1,ce=2,_e=3,be=0,he=H,Fe=H*2,xe=-1;b==="RGBA"?(be=0,he=H,Fe=H*2,xe=H*3):b==="RGB"?(be=0,he=H,Fe=H*2):b==="RBG"&&(be=0,Fe=H,he=H*2),u=s.createImageData(c,p);for(let Ie=0;Ie<p*c;ne+=v,re+=v,ce+=v,_e+=v,Ie++)u.data[ne]=(r.data[be++]-q[0])*E[0],u.data[re]=(r.data[he++]-q[1])*E[1],u.data[ce]=(r.data[Fe++]-q[2])*E[2],u.data[_e]=xe===-1?255:(r.data[xe++]-q[3])*E[3]}else throw new Error("Can not access image data");return u}}),ye,R,Me,Qe,ge,Q=h(()=>{dt(),ye=(r,i)=>{if(r===void 0)throw new Error("Image buffer must be defined");if(i.height===void 0||i.width===void 0)throw new Error("Image height and width must be defined");if(i.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:u}=i,c=i.norm??{mean:255,bias:0},p,d;typeof c.mean=="number"?p=[c.mean,c.mean,c.mean,c.mean]:p=[c.mean[0],c.mean[1],c.mean[2],c.mean[3]??255],typeof c.bias=="number"?d=[c.bias,c.bias,c.bias,c.bias]:d=[c.bias[0],c.bias[1],c.bias[2],c.bias[3]??0];let b=i.format!==void 0?i.format:"RGBA",T=i.tensorFormat!==void 0&&i.tensorFormat!==void 0?i.tensorFormat:"RGB",E=s*u,q=T==="RGBA"?new Float32Array(E*4):new Float32Array(E*3),H=4,v=0,ne=1,re=2,ce=3,_e=0,be=E,he=E*2,Fe=-1;b==="RGB"&&(H=3,v=0,ne=1,re=2,ce=-1),T==="RGBA"?Fe=E*3:T==="RBG"?(_e=0,he=E,be=E*2):T==="BGR"&&(he=0,be=E,_e=E*2);for(let xe=0;xe<E;xe++,v+=H,re+=H,ne+=H,ce+=H)q[_e++]=(r[v]+d[0])/p[0],q[be++]=(r[ne]+d[1])/p[1],q[he++]=(r[re]+d[2])/p[2],Fe!==-1&&ce!==-1&&(q[Fe++]=(r[ce]+d[3])/p[3]);return T==="RGBA"?new ot("float32",q,[1,4,s,u]):new ot("float32",q,[1,3,s,u])},R=async(r,i)=>{let s=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,u=typeof ImageData<"u"&&r instanceof ImageData,c=typeof ImageBitmap<"u"&&r instanceof ImageBitmap,p=typeof r=="string",d,b=i??{},T=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},E=q=>q instanceof HTMLCanvasElement||q instanceof OffscreenCanvas?q.getContext("2d"):null;if(s){let q=T();q.width=r.width,q.height=r.height;let H=E(q);if(H!=null){let v=r.height,ne=r.width;if(i!==void 0&&i.resizedHeight!==void 0&&i.resizedWidth!==void 0&&(v=i.resizedHeight,ne=i.resizedWidth),i!==void 0){if(b=i,i.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");b.tensorFormat="RGBA",b.height=v,b.width=ne}else b.tensorFormat="RGBA",b.height=v,b.width=ne;H.drawImage(r,0,0),d=H.getImageData(0,0,ne,v).data}else throw new Error("Can not access image data")}else if(u){let q,H;if(i!==void 0&&i.resizedWidth!==void 0&&i.resizedHeight!==void 0?(q=i.resizedHeight,H=i.resizedWidth):(q=r.height,H=r.width),i!==void 0&&(b=i),b.format="RGBA",b.height=q,b.width=H,i!==void 0){let v=T();v.width=H,v.height=q;let ne=E(v);if(ne!=null)ne.putImageData(r,0,0),d=ne.getImageData(0,0,H,q).data;else throw new Error("Can not access image data")}else d=r.data}else if(c){if(i===void 0)throw new Error("Please provide image config with format for Imagebitmap");let q=T();q.width=r.width,q.height=r.height;let H=E(q);if(H!=null){let v=r.height,ne=r.width;return H.drawImage(r,0,0,ne,v),d=H.getImageData(0,0,ne,v).data,b.height=v,b.width=ne,ye(d,b)}else throw new Error("Can not access image data")}else{if(p)return new Promise((q,H)=>{let v=T(),ne=E(v);if(!r||!ne)return H();let re=new Image;re.crossOrigin="Anonymous",re.src=r,re.onload=()=>{v.width=re.width,v.height=re.height,ne.drawImage(re,0,0,v.width,v.height);let ce=ne.getImageData(0,0,v.width,v.height);b.height=v.height,b.width=v.width,q(ye(ce.data,b))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return ye(d,b);throw new Error("Input data provided is not supported - aborted tensor creation")},Me=(r,i)=>{let{width:s,height:u,download:c,dispose:p}=i,d=[1,u,s,4];return new ot({location:"texture",type:"float32",texture:r,dims:d,download:c,dispose:p})},Qe=(r,i)=>{let{dataType:s,dims:u,download:c,dispose:p}=i;return new ot({location:"gpu-buffer",type:s??"float32",gpuBuffer:r,dims:u,download:c,dispose:p})},ge=(r,i,s)=>new ot({location:"cpu-pinned",type:r,data:i,dims:s??[i.length]})}),ae,Se,X,me,Ke=h(()=>{ae=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),X=!1,me=()=>{if(!X){X=!0;let r=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;r&&(ae.set("int64",BigInt64Array),Se.set(BigInt64Array,"int64")),i&&(ae.set("uint64",BigUint64Array),Se.set(BigUint64Array,"uint64")),s?(ae.set("float16",Float16Array),Se.set(Float16Array,"float16")):ae.set("float16",Uint16Array)}}}),De,Be,We=h(()=>{dt(),De=r=>{let i=1;for(let s=0;s<r.length;s++){let u=r[s];if(typeof u!="number"||!Number.isSafeInteger(u))throw new TypeError(`dims[${s}] must be an integer, got: ${u}`);if(u<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${u}`);i*=u}return i},Be=(r,i)=>{switch(r.location){case"cpu":return new ot(r.type,r.data,i);case"cpu-pinned":return new ot({location:"cpu-pinned",data:r.data,type:r.type,dims:i});case"texture":return new ot({location:"texture",texture:r.texture,type:r.type,dims:i});case"gpu-buffer":return new ot({location:"gpu-buffer",gpuBuffer:r.gpuBuffer,type:r.type,dims:i});default:throw new Error(`tensorReshape: tensor location ${r.location} is not supported`)}}}),ot,dt=h(()=>{ee(),Q(),Ke(),We(),ot=class{constructor(r,i,s){me();let u,c;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,u=r.type,c=r.dims,r.location){case"cpu-pinned":{let d=ae.get(u);if(!d)throw new TypeError(`unsupported type "${u}" to create tensor from pinned buffer`);if(!(r.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=r.data;break}case"texture":{if(u!=="float32")throw new TypeError(`unsupported type "${u}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(u!=="float32"&&u!=="float16"&&u!=="int32"&&u!=="int64"&&u!=="uint32"&&u!=="uint8"&&u!=="bool")throw new TypeError(`unsupported type "${u}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,b;if(typeof r=="string")if(u=r,b=s,r==="string"){if(!Array.isArray(i))throw new TypeError("A string tensor's data must be a string array.");d=i}else{let T=ae.get(r);if(T===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(i)){if(r==="float16"&&T===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${T.name} as data.`);r==="uint64"||r==="int64"?d=T.from(i,BigInt):d=T.from(i)}else if(i instanceof T)d=i;else throw new TypeError(`A ${u} tensor's data must be type of ${T}`)}else if(b=i,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let T=typeof r[0];if(T==="string")u="string",d=r;else if(T==="boolean")u="bool",d=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${T}.`)}else{let T=Se.get(r.constructor);if(T===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);u=T,d=r}if(b===void 0)b=[d.length];else if(!Array.isArray(b))throw new TypeError("A tensor's dims must be a number array");c=b,this.cpuData=d,this.dataLocation="cpu"}let p=De(c);if(this.cpuData&&p!==this.cpuData.length&&!((u==="uint4"||u==="int4")&&Math.ceil(p/2)===this.cpuData.length))throw new Error(`Tensor's size(${p}) does not match data length(${this.cpuData.length}).`);this.type=u,this.dims=c,this.size=p}static async fromImage(r,i){return R(r,i)}static fromTexture(r,i){return Me(r,i)}static fromGpuBuffer(r,i){return Qe(r,i)}static fromPinnedBuffer(r,i,s){return ge(r,i,s)}toDataURL(r){return de(this,r)}toImageData(r){return Ce(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let i=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=i,r&&this.disposer&&(this.disposer(),this.disposer=void 0),i}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Be(this,r)}}}),Ge,Te=h(()=>{dt(),Ge=ot}),je,Ye,tt,A,Ae=h(()=>{j(),je=(r,i)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${r}::ORT::${i}`)},Ye=(r,i)=>{var c;let s=((c=new Error().stack)==null?void 0:c.split(/\r\n|\r|\n/g))||[],u=!1;for(let p=0;p<s.length;p++){if(u&&!s[p].includes("TRACE_FUNC")){let d=`FUNC_${r}::${s[p].trim().split(" ")[1]}`;i&&(d+=`::${i}`),je("CPU",d);return}s[p].includes("TRACE_FUNC")&&(u=!0)}},tt=r=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("BEGIN",r)},A=r=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("END",r)}}),$e,se=h(()=>{y(),Te(),Ae(),$e=class K2{constructor(i){this.handler=i}async run(i,s,u){tt();let c={},p={};if(typeof i!="object"||i===null||i instanceof Ge||Array.isArray(i))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof Ge)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let E of s){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);c[E]=null}if(typeof u=="object"&&u!==null)p=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else{let E=!1,q=Object.getOwnPropertyNames(s);for(let H of this.outputNames)if(q.indexOf(H)!==-1){let v=s[H];(v===null||v instanceof Ge)&&(E=!0,d=!1,c[H]=v)}if(E){if(typeof u=="object"&&u!==null)p=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else p=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let E of this.inputNames)if(typeof i[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(d)for(let E of this.outputNames)c[E]=null;let b=await this.handler.run(i,c,p),T={};for(let E in b)if(Object.hasOwnProperty.call(b,E)){let q=b[E];q instanceof Ge?T[E]=q:T[E]=new Ge(q.type,q.data,q.dims)}return A(),T}async release(){return this.handler.dispose()}static async create(i,s,u,c){tt();let p,d={};if(typeof i=="string"){if(p=i,typeof s=="object"&&s!==null)d=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(i instanceof Uint8Array){if(p=i,typeof s=="object"&&s!==null)d=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer){let q=i,H=0,v=i.byteLength;if(typeof s=="object"&&s!==null)d=s;else if(typeof s=="number"){if(H=s,!Number.isSafeInteger(H))throw new RangeError("'byteOffset' must be an integer.");if(H<0||H>=q.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${q.byteLength}).`);if(v=i.byteLength-H,typeof u=="number"){if(v=u,!Number.isSafeInteger(v))throw new RangeError("'byteLength' must be an integer.");if(v<=0||H+v>q.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${q.byteLength-H}].`);if(typeof c=="object"&&c!==null)d=c;else if(typeof c<"u")throw new TypeError("'options' must be an object.")}else if(typeof u<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");p=new Uint8Array(q,H,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[b,T]=await P(d),E=await b.createInferenceSessionHandler(p,T);return A(),new K2(E)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),te,we=h(()=>{se(),te=$e}),B=h(()=>{}),J=h(()=>{}),L=h(()=>{}),ue=h(()=>{}),le,ke,Ne=h(()=>{y(),Te(),le="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",ke=class Q2{constructor(i,s,u){this.handler=i,this.hasOptimizerModel=s,this.hasEvalModel=u}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(i,s){let u=i.evalModel||"",c=i.optimizerModel||"",p=s||{},[d,b]=await P(p);if(d.createTrainingSessionHandler){let T=await d.createTrainingSessionHandler(i.checkpointState,i.trainModel,u,c,b);return new Q2(T,!!i.optimizerModel,!!i.evalModel)}else throw new Error(le)}typeNarrowingForRunStep(i,s,u,c,p){let d={},b={};if(typeof u!="object"||u===null||u instanceof Ge||Array.isArray(u))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let T=!0;if(typeof c=="object"){if(c===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(c instanceof Ge)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(c)){if(c.length===0)throw new TypeError("'fetches' cannot be an empty array.");T=!1;for(let E of c){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(s.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);d[E]=null}if(typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else{let E=!1,q=Object.getOwnPropertyNames(c);for(let H of s)if(q.indexOf(H)!==-1){let v=c[H];(v===null||v instanceof Ge)&&(E=!0,T=!1,d[H]=v)}if(E){if(typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else b=c}}else if(typeof c<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let E of i)if(typeof u[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(T)for(let E of s)d[E]=null;return[d,b]}convertHandlerReturnTypeToMapOfTensors(i){let s={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let c=i[u];c instanceof Ge?s[u]=c:s[u]=new Ge(c.type,c.data,c.dims)}return s}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(i,s,u){let[c,p]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,i,s,u),d=await this.handler.runTrainStep(i,c,p);return this.convertHandlerReturnTypeToMapOfTensors(d)}async runOptimizerStep(i){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(i||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(i,s,u){if(this.hasEvalModel){let[c,p]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,i,s,u),d=await this.handler.runEvalStep(i,c,p);return this.convertHandlerReturnTypeToMapOfTensors(d)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(i=!0){return this.handler.getParametersSize(i)}async loadParametersBuffer(i,s=!0){let u=await this.getParametersSize(s);if(i.length!==4*u)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(i,s)}async getContiguousParameters(i=!0){return this.handler.getContiguousParameters(i)}async release(){return this.handler.dispose()}}}),ut,Je=h(()=>{Ne(),ut=ke}),Ve={};g(Ve,{InferenceSession:()=>te,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>tt,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>ut,env:()=>D,registerBackend:()=>z});var Z=h(()=>{x(),Y(),we(),Te(),B(),J(),Ae(),L(),ue(),Je()}),ve=h(()=>{}),Re={};g(Re,{default:()=>rt});var He,Xe,rt,ft=h(()=>{var r;by(),mn(),Qr(),He="ort-wasm-proxy-worker",Xe=((r=globalThis.self)==null?void 0:r.name)===He,Xe&&(self.onmessage=i=>{let{type:s,in:u}=i.data;try{switch(s){case"init-wasm":bi(u.wasm).then(()=>{wm(u).then(()=>{postMessage({type:s})},c=>{postMessage({type:s,err:c})})},c=>{postMessage({type:s,err:c})});break;case"init-ep":{let{epName:c,env:p}=u;vm(p,c).then(()=>{postMessage({type:s})},d=>{postMessage({type:s,err:d})});break}case"copy-from":{let{buffer:c}=u,p=Cp(c);postMessage({type:s,out:p});break}case"create":{let{model:c,options:p}=u;bm(c,p).then(d=>{postMessage({type:s,out:d})},d=>{postMessage({type:s,err:d})});break}case"release":xm(u),postMessage({type:s});break;case"run":{let{sessionId:c,inputIndices:p,inputs:d,outputIndices:b,options:T}=u;Tm(c,p,d,b,new Array(b.length).fill(null),T).then(E=>{E.some(q=>q[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:E},Sm([...d,...E]))},E=>{postMessage({type:s,err:E})});break}case"end-profiling":km(u),postMessage({type:s});break;default:}}catch(c){postMessage({type:s,err:c})}}),rt=Xe?null:i=>new Worker(i??at,{type:"module",name:He})}),ht={};g(ht,{default:()=>St});var Mt,wt,St,Rt=h(()=>{var r;wt=(Mt=import.meta.url,async function(i={}){function s(){return Sr.buffer!=tr.buffer&&In(),tr}function u(){return Sr.buffer!=tr.buffer&&In(),er}function c(){return Sr.buffer!=tr.buffer&&In(),pt}function p(){return Sr.buffer!=tr.buffer&&In(),zt}function d(){return Sr.buffer!=tr.buffer&&In(),ir}function b(){return Sr.buffer!=tr.buffer&&In(),Hr}function T(){return Sr.buffer!=tr.buffer&&In(),un}function E(){return Sr.buffer!=tr.buffer&&In(),Ap}var q,H,v=i,ne=new Promise((m,F)=>{q=m,H=F}),re=typeof window=="object",ce=typeof importScripts=="function",_e=ce&&self.name=="em-pthread";v.mountExternalData=(m,F)=>{m.startsWith("./")&&(m=m.substring(2)),(v.Ab||(v.Ab=new Map)).set(m,F)},v.unmountExternalData=()=>{delete v.Ab};var be=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let he=()=>{let m=(K,oe,pe)=>(...Le)=>{let lt=ro,yt=oe==null?void 0:oe();Le=K(...Le);let $t=oe==null?void 0:oe();return yt!==$t&&(K=$t,pe(yt),oe=pe=null),ro!=lt?new Promise((Nt,lr)=>{Vm={resolve:Nt,reject:lr}}):Le},F=K=>async(...oe)=>{var pe;try{if(v.zb)throw Error("Session already started");let Le=v.zb={Ub:oe[0],errors:[]},lt=await K(...oe);if(v.zb!==Le)throw Error("Session mismatch");(pe=v.Eb)==null||pe.flush();let yt=Le.errors;if(0<yt.length){let $t=await Promise.all(yt);if($t=$t.filter(Nt=>Nt),0<$t.length)throw Error($t.join(` +`))}return lt}finally{v.zb=null}};v._OrtCreateSession=m(v._OrtCreateSession,()=>v._OrtCreateSession,K=>v._OrtCreateSession=K),v._OrtRun=F(m(v._OrtRun,()=>v._OrtRun,K=>v._OrtRun=K)),v._OrtRunWithBinding=F(m(v._OrtRunWithBinding,()=>v._OrtRunWithBinding,K=>v._OrtRunWithBinding=K)),v._OrtBindInput=m(v._OrtBindInput,()=>v._OrtBindInput,K=>v._OrtBindInput=K),he=void 0};v.jsepInit=(m,F)=>{if(he==null||he(),m==="webgpu"){[v.Eb,v.Lb,v.Pb,v.Fb,v.Ob,v.hb,v.Qb,v.Sb,v.Mb,v.Nb,v.Rb]=F;let K=v.Eb;v.jsepRegisterBuffer=(oe,pe,Le,lt)=>K.registerBuffer(oe,pe,Le,lt),v.jsepGetBuffer=oe=>K.getBuffer(oe),v.jsepCreateDownloader=(oe,pe,Le)=>K.createDownloader(oe,pe,Le),v.jsepOnReleaseSession=oe=>{K.onReleaseSession(oe)},v.jsepOnRunStart=oe=>K.onRunStart(oe)}};var Fe,xe,Ie=Object.assign({},v),ct="./this.program",et=(m,F)=>{throw F},vt="";(re||ce)&&(ce?vt=self.location.href:typeof document<"u"&&document.currentScript&&(vt=document.currentScript.src),Mt&&(vt=Mt),vt=vt.startsWith("blob:")?"":vt.substr(0,vt.replace(/[?#].*/,"").lastIndexOf("/")+1),ce&&(xe=m=>{var F=new XMLHttpRequest;return F.open("GET",m,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),Fe=m=>Ry(m)?new Promise((F,K)=>{var oe=new XMLHttpRequest;oe.open("GET",m,!0),oe.responseType="arraybuffer",oe.onload=()=>{(oe.status==200||oe.status==0&&oe.response)&&K(oe.response),F(oe.status)},oe.onerror=F,oe.send(null)}):fetch(m,{credentials:"same-origin"}).then(F=>F.ok?F.arrayBuffer():Promise.reject(Error(F.status+" : "+F.url))));var Ft,Lt=console.log.bind(console),pr=console.error.bind(console),ar=Lt,nr=pr;if(Object.assign(v,Ie),Ie=null,_e){let m=function(F){try{var K=F.data,oe=K.cmd;if(oe==="load"){let pe=[];self.onmessage=Le=>pe.push(Le),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let Le of pe)m(Le);self.onmessage=m};for(let Le of K.handlers)v[Le]&&!v[Le].proxy||(v[Le]=(...lt)=>{postMessage({Db:"callHandler",Yb:Le,args:lt})},Le=="print"&&(ar=v[Le]),Le=="printErr"&&(nr=v[Le]));Sr=K.wasmMemory,In(),yr(K.wasmModule)}else if(oe==="run"){Hm(K.pthread_ptr,0,0,1,0,0),Nm(K.pthread_ptr),wx(),qy(),qr||(jw(),qr=!0);try{vx(K.start_routine,K.arg)}catch(pe){if(pe!="unwind")throw pe}}else oe==="cancel"?El()&&Vp(-1):K.target!=="setimmediate"&&(oe==="checkMailbox"?qr&&zp():oe&&(nr(`worker: received unknown command ${oe}`),nr(K)))}catch(pe){throw Uw(),pe}};var yr,qr=!1;nr=function(...F){F=F.join(" "),console.error(F)},self.alert=function(...F){postMessage({Db:"alert",text:F.join(" "),$b:El()})},v.instantiateWasm=(F,K)=>new Promise(oe=>{yr=pe=>{pe=new WebAssembly.Instance(pe,jy()),K(pe),oe()}}),self.onunhandledrejection=F=>{throw F.reason||F},self.onmessage=m}v.wasmBinary&&(Ft=v.wasmBinary);var Sr,jr,It,tr,er,pt,zt,ir,Hr,un,xn,Yn,Ap,hi=!1;function In(){var m=Sr.buffer;v.HEAP8=tr=new Int8Array(m),v.HEAP16=pt=new Int16Array(m),v.HEAPU8=er=new Uint8Array(m),v.HEAPU16=zt=new Uint16Array(m),v.HEAP32=ir=new Int32Array(m),v.HEAPU32=Hr=new Uint32Array(m),v.HEAPF32=un=new Float32Array(m),v.HEAPF64=Ap=new Float64Array(m),v.HEAP64=xn=new BigInt64Array(m),v.HEAPU64=Yn=new BigUint64Array(m)}if(!_e){if(!((Sr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof be))throw nr("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"),Error("bad memory");In()}var sf=[],Fn=[],Zn=[],Ci=0,es=null;function Ip(){if(--Ci==0&&es){var m=es;es=null,m()}}function kl(m){throw nr(m="Aborted("+m+")"),hi=!0,It=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),H(m),m}var Pm,Ly=m=>m.startsWith("data:application/octet-stream;base64,"),Ry=m=>m.startsWith("file://");function By(m){if(m==Pm&&Ft)return new Uint8Array(Ft);if(xe)return xe(m);throw"both async and sync fetching of the wasm failed"}function Ny(m,F,K){return function(oe){return Ft?Promise.resolve().then(()=>By(oe)):Fe(oe).then(pe=>new Uint8Array(pe),()=>By(oe))}(m).then(oe=>WebAssembly.instantiate(oe,F)).then(K,oe=>{nr(`failed to asynchronously prepare wasm: ${oe}`),kl(oe)})}function jy(){return{a:{L:yx,xa:_x,b:xx,Z:Xy,y:Jy,na:ew,V:rw,X:nw,oa:iw,la:ow,ea:sw,ka:aw,I:lw,W:uw,T:cw,ma:dw,U:fw,sa:Mx,B:Tx,O:kx,N:Ex,A:Px,r:$x,p:Ax,C:Ix,x:Bx,P:Nx,ra:jx,ha:Ux,R:Vx,_:Wx,E:Gx,ga:Nm,qa:qx,t:Hx,D:Xx,o:Yx,m:Jx,c:Rm,n:eM,k:nM,ya:iM,q:oM,g:sM,u:aM,l:lM,f:uM,i:cM,j:dM,h:fM,e:pM,ba:hM,ca:mM,da:gM,$:Ew,aa:Cw,ua:_M,d:yM,M:wM,F:vM,J:bM,v:xM,pa:MM,S:TM,s:$w,w:kM,K:SM,Q:EM,wa:CM,va:PM,ia:Fw,ja:zw,Y:zm,z:Ow,H:Dw,fa:Lw,G:Rw,a:Sr,ta:Fm}}}var $m={858772:(m,F,K,oe)=>{if(v===void 0||!v.Ab)return 1;if((m=jn(m>>>0)).startsWith("./")&&(m=m.substring(2)),!(m=v.Ab.get(m)))return 2;if(oe>>>=0,(F>>>=0)+(K>>>=0)>m.byteLength)return 3;try{return u().set(m.subarray(F,F+K),oe>>>0),0}catch{return 4}},859273:()=>{v.Mb()},859304:()=>{v.Nb()},859333:()=>{v.Rb()},859358:m=>v.Lb(m),859391:m=>v.Pb(m),859423:(m,F,K)=>{v.Fb(m,F,K,!0)},859462:(m,F,K)=>{v.Fb(m,F,K)},859495:()=>typeof wasmOffsetConverter<"u",859552:m=>{v.hb("Abs",m,void 0)},859603:m=>{v.hb("Neg",m,void 0)},859654:m=>{v.hb("Floor",m,void 0)},859707:m=>{v.hb("Ceil",m,void 0)},859759:m=>{v.hb("Reciprocal",m,void 0)},859817:m=>{v.hb("Sqrt",m,void 0)},859869:m=>{v.hb("Exp",m,void 0)},859920:m=>{v.hb("Erf",m,void 0)},859971:m=>{v.hb("Sigmoid",m,void 0)},860026:(m,F,K)=>{v.hb("HardSigmoid",m,{alpha:F,beta:K})},860105:m=>{v.hb("Log",m,void 0)},860156:m=>{v.hb("Sin",m,void 0)},860207:m=>{v.hb("Cos",m,void 0)},860258:m=>{v.hb("Tan",m,void 0)},860309:m=>{v.hb("Asin",m,void 0)},860361:m=>{v.hb("Acos",m,void 0)},860413:m=>{v.hb("Atan",m,void 0)},860465:m=>{v.hb("Sinh",m,void 0)},860517:m=>{v.hb("Cosh",m,void 0)},860569:m=>{v.hb("Asinh",m,void 0)},860622:m=>{v.hb("Acosh",m,void 0)},860675:m=>{v.hb("Atanh",m,void 0)},860728:m=>{v.hb("Tanh",m,void 0)},860780:m=>{v.hb("Not",m,void 0)},860831:(m,F,K)=>{v.hb("Clip",m,{min:F,max:K})},860900:m=>{v.hb("Clip",m,void 0)},860952:(m,F)=>{v.hb("Elu",m,{alpha:F})},861010:m=>{v.hb("Gelu",m,void 0)},861062:m=>{v.hb("Relu",m,void 0)},861114:(m,F)=>{v.hb("LeakyRelu",m,{alpha:F})},861178:(m,F)=>{v.hb("ThresholdedRelu",m,{alpha:F})},861248:(m,F)=>{v.hb("Cast",m,{to:F})},861306:m=>{v.hb("Add",m,void 0)},861357:m=>{v.hb("Sub",m,void 0)},861408:m=>{v.hb("Mul",m,void 0)},861459:m=>{v.hb("Div",m,void 0)},861510:m=>{v.hb("Pow",m,void 0)},861561:m=>{v.hb("Equal",m,void 0)},861614:m=>{v.hb("Greater",m,void 0)},861669:m=>{v.hb("GreaterOrEqual",m,void 0)},861731:m=>{v.hb("Less",m,void 0)},861783:m=>{v.hb("LessOrEqual",m,void 0)},861842:(m,F,K,oe,pe)=>{v.hb("ReduceMean",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862001:(m,F,K,oe,pe)=>{v.hb("ReduceMax",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862159:(m,F,K,oe,pe)=>{v.hb("ReduceMin",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862317:(m,F,K,oe,pe)=>{v.hb("ReduceProd",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862476:(m,F,K,oe,pe)=>{v.hb("ReduceSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862634:(m,F,K,oe,pe)=>{v.hb("ReduceL1",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862791:(m,F,K,oe,pe)=>{v.hb("ReduceL2",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862948:(m,F,K,oe,pe)=>{v.hb("ReduceLogSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},863109:(m,F,K,oe,pe)=>{v.hb("ReduceSumSquare",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},863273:(m,F,K,oe,pe)=>{v.hb("ReduceLogSumExp",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},863437:m=>{v.hb("Where",m,void 0)},863490:(m,F,K)=>{v.hb("Transpose",m,{perm:F?Array.from(d().subarray(F>>>0,K>>>0)):[]})},863598:(m,F,K,oe)=>{v.hb("DepthToSpace",m,{blocksize:F,mode:jn(K),format:oe?"NHWC":"NCHW"})},863731:(m,F,K,oe)=>{v.hb("DepthToSpace",m,{blocksize:F,mode:jn(K),format:oe?"NHWC":"NCHW"})},863864:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn,Cl)=>{v.hb("ConvTranspose",m,{format:$t?"NHWC":"NCHW",autoPad:F,dilations:[K],group:oe,kernelShape:[pe],pads:[Le,lt],strides:[yt],wIsConst:()=>!!s()[Nt>>>0],outputPadding:lr?Array.from(d().subarray(lr>>>0,Ar>>>0)):[],outputShape:Lr?Array.from(d().subarray(Lr>>>0,zn>>>0)):[],activation:jn(Cl)})},864265:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:oe,kernelShape:Array.from(d().subarray(pe>>>0,2+(pe>>>0)>>>0)),pads:Array.from(d().subarray(Le>>>0,4+(Le>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[$t>>>0],outputPadding:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],outputShape:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[],activation:jn(zn)})},864830:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn,Cl)=>{v.hb("ConvTranspose",m,{format:$t?"NHWC":"NCHW",autoPad:F,dilations:[K],group:oe,kernelShape:[pe],pads:[Le,lt],strides:[yt],wIsConst:()=>!!s()[Nt>>>0],outputPadding:lr?Array.from(d().subarray(lr>>>0,Ar>>>0)):[],outputShape:Lr?Array.from(d().subarray(Lr>>>0,zn>>>0)):[],activation:jn(Cl)})},865231:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:oe,kernelShape:Array.from(d().subarray(pe>>>0,2+(pe>>>0)>>>0)),pads:Array.from(d().subarray(Le>>>0,4+(Le>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[$t>>>0],outputPadding:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],outputShape:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[],activation:jn(zn)})},865796:(m,F)=>{v.hb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},865887:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("AveragePool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},866302:(m,F)=>{v.hb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},866393:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("AveragePool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},866808:(m,F)=>{v.hb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},866895:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("MaxPool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},867306:(m,F)=>{v.hb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},867393:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("MaxPool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},867804:(m,F,K,oe,pe)=>{v.hb("Gemm",m,{alpha:F,beta:K,transA:oe,transB:pe})},867908:m=>{v.hb("MatMul",m,void 0)},867962:(m,F,K,oe)=>{v.hb("ArgMax",m,{keepDims:!!F,selectLastIndex:!!K,axis:oe})},868070:(m,F,K,oe)=>{v.hb("ArgMin",m,{keepDims:!!F,selectLastIndex:!!K,axis:oe})},868178:(m,F)=>{v.hb("Softmax",m,{axis:F})},868241:(m,F)=>{v.hb("Concat",m,{axis:F})},868301:(m,F,K,oe,pe)=>{v.hb("Split",m,{axis:F,numOutputs:K,splitSizes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},868441:m=>{v.hb("Expand",m,void 0)},868495:(m,F)=>{v.hb("Gather",m,{axis:Number(F)})},868566:(m,F)=>{v.hb("GatherElements",m,{axis:Number(F)})},868645:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr)=>{v.hb("Resize",m,{antialias:F,axes:K?Array.from(d().subarray(K>>>0,oe>>>0)):[],coordinateTransformMode:jn(pe),cubicCoeffA:Le,excludeOutside:lt,extrapolationValue:yt,keepAspectRatioPolicy:jn($t),mode:jn(Nt),nearestMode:jn(lr)})},868991:(m,F,K,oe,pe,Le,lt)=>{v.hb("Slice",m,{starts:F?Array.from(d().subarray(F>>>0,K>>>0)):[],ends:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[],axes:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[]})},869207:m=>{v.hb("Tile",m,void 0)},869259:(m,F,K)=>{v.hb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},869373:(m,F,K)=>{v.hb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},869487:m=>{v.hb("Range",m,void 0)},869540:(m,F)=>{v.hb("Einsum",m,{equation:jn(F)})},869621:(m,F,K,oe,pe)=>{v.hb("Pad",m,{mode:F,value:K,pads:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},869748:(m,F,K,oe,pe,Le)=>{v.hb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!pe,trainingMode:!!oe,format:Le?"NHWC":"NCHW"})},869917:(m,F,K,oe,pe,Le)=>{v.hb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!pe,trainingMode:!!oe,format:Le?"NHWC":"NCHW"})},870086:(m,F,K)=>{v.hb("CumSum",m,{exclusive:Number(F),reverse:Number(K)})},870183:(m,F,K)=>{v.hb("DequantizeLinear",m,{axis:F,blockSize:K})},870273:(m,F,K,oe,pe,Le,lt,yt,$t)=>{v.hb("Attention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:oe,scale:pe,doRotary:Le,qkvHiddenSizes:lt?Array.from(d().subarray(Number(yt)>>>0,Number(yt)+lt>>>0)):[],pastPresentShareBuffer:!!$t})},870545:m=>{v.hb("BiasAdd",m,void 0)},870600:m=>{v.hb("BiasSplitGelu",m,void 0)},870661:m=>{v.hb("FastGelu",m,void 0)},870717:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn,Cl,IM)=>{v.hb("Conv",m,{format:Ar?"NHWC":"NCHW",auto_pad:F,dilations:K?Array.from(d().subarray(K>>>0,oe>>>0)):[],group:pe,kernel_shape:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],pads:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],strides:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],w_is_const:()=>!!s()[Lr>>>0],activation:jn(zn),activation_params:Cl?Array.from(T().subarray(Cl>>>0,IM>>>0)):[]})},871213:m=>{v.hb("Gelu",m,void 0)},871265:(m,F,K,oe)=>{v.hb("GroupQueryAttention",m,{numHeads:F,kvNumHeads:K,scale:oe})},871378:(m,F,K,oe)=>{v.hb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!oe})},871489:(m,F,K,oe)=>{v.hb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!oe})},871600:(m,F,K,oe,pe,Le)=>{v.hb("MatMulNBits",m,{k:F,n:K,accuracyLevel:oe,bits:pe,blockSize:Le})},871727:(m,F,K,oe,pe,Le)=>{v.hb("MultiHeadAttention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:oe,scale:pe,doRotary:Le})},871886:(m,F)=>{v.hb("QuickGelu",m,{alpha:F})},871950:(m,F,K,oe,pe)=>{v.hb("RotaryEmbedding",m,{interleaved:!!F,numHeads:K,rotaryEmbeddingDim:oe,scale:pe})},872089:(m,F,K)=>{v.hb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})},872191:m=>{v.Qb(m)},872225:(m,F)=>v.Sb(m,F,v.zb.Ub,v.zb.errors),872337:(m,F,K)=>{v.hb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})}};function _x(m,F,K){return bw(async()=>{await v.Ob(m,F,K)})}function yx(){return typeof wasmOffsetConverter<"u"}function Am(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}var Im=m=>{m.terminate(),m.onmessage=()=>{}},Uy=m=>{ts.length==0&&(Ky(),Hy(ts[0]));var F=ts.pop();if(!F)return 6;Qs.push(F),eo[m.sb]=F,F.sb=m.sb;var K={cmd:"run",start_routine:m.Vb,arg:m.Hb,pthread_ptr:m.sb};return F.postMessage(K,m.Wb),0},Ks=0,Jr=(m,F,...K)=>{for(var oe=2*K.length,pe=Xm(),Le=Qm(8*oe),lt=Le>>>3,yt=0;yt<K.length;yt++){var $t=K[yt];typeof $t=="bigint"?(xn[lt+2*yt]=1n,xn[lt+2*yt+1]=$t):(xn[lt+2*yt]=0n,E()[lt+2*yt+1>>>0]=$t)}return m=Vw(m,0,oe,Le,F),Wp(pe),m};function Fm(m){if(_e)return Jr(0,1,m);if(It=m,!(0<Ks)){for(var F of Qs)Im(F);for(F of ts)Im(F);ts=[],Qs=[],eo=[],hi=!0}et(m,new Am(m))}function Vy(m){if(_e)return Jr(1,0,m);zm(m)}var zm=m=>{if(It=m,_e)throw Vy(m),"unwind";Fm(m)},ts=[],Qs=[],Wy=[],eo={},Gy=m=>{var F=m.sb;delete eo[F],ts.push(m),Qs.splice(Qs.indexOf(m),1),m.sb=0,Km(F)};function qy(){Wy.forEach(m=>m())}var Hy=m=>new Promise(F=>{m.onmessage=pe=>{var Le=(pe=pe.data).cmd;if(pe.targetThread&&pe.targetThread!=El()){var lt=eo[pe.targetThread];lt?lt.postMessage(pe,pe.transferList):nr(`Internal error! Worker sent a message "${Le}" to target pthread ${pe.targetThread}, but that thread no longer exists!`)}else Le==="checkMailbox"?zp():Le==="spawnThread"?Uy(pe):Le==="cleanupThread"?Gy(eo[pe.thread]):Le==="killThread"?(pe=pe.thread,Le=eo[pe],delete eo[pe],Im(Le),Km(pe),Qs.splice(Qs.indexOf(Le),1),Le.sb=0):Le==="cancelThread"?eo[pe.thread].postMessage({cmd:"cancel"}):Le==="loaded"?(m.loaded=!0,F(m)):Le==="alert"?alert(`Thread ${pe.threadId}: ${pe.text}`):pe.target==="setimmediate"?m.postMessage(pe):Le==="callHandler"?v[pe.handler](...pe.args):Le&&nr(`worker sent an unknown command ${Le}`)},m.onerror=pe=>{throw nr(`worker sent an error! ${pe.filename}:${pe.lineno}: ${pe.message}`),pe};var K,oe=[];for(K of[])v.propertyIsEnumerable(K)&&oe.push(K);m.postMessage({cmd:"load",handlers:oe,wasmMemory:Sr,wasmModule:jr})});function Ky(){var m=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});ts.push(m)}var Fp=m=>{for(;0<m.length;)m.shift()(v)},wx=()=>{var m=El(),F=b()[m+52>>>2>>>0];m=b()[m+56>>>2>>>0],Gw(F,F-m),Wp(F)},vx=(m,F)=>{Ks=0,m=qw(m,F),0<Ks?It=m:Vp(m)};class bx{constructor(F){this.Bb=F-24}}function xx(m,F,K){var oe=new bx(m>>>=0);throw F>>>=0,K>>>=0,b()[oe.Bb+16>>>2>>>0]=0,b()[oe.Bb+4>>>2>>>0]=F,b()[oe.Bb+8>>>2>>>0]=K,m}function Qy(m,F,K,oe){return _e?Jr(2,1,m,F,K,oe):Xy(m,F,K,oe)}function Xy(m,F,K,oe){if(m>>>=0,F>>>=0,K>>>=0,oe>>>=0,be===void 0)return nr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var pe=[];return _e&&pe.length===0?Qy(m,F,K,oe):(m={Vb:K,sb:m,Hb:oe,Wb:pe},_e?(m.Db="spawnThread",postMessage(m,pe),0):Uy(m))}var Yy=typeof TextDecoder<"u"?new TextDecoder:void 0,Zy=(m,F,K)=>{var oe=(F>>>=0)+K;for(K=F;m[K]&&!(K>=oe);)++K;if(16<K-F&&m.buffer&&Yy)return Yy.decode(m.buffer instanceof be?m.slice(F,K):m.subarray(F,K));for(oe="";F<K;){var pe=m[F++];if(128&pe){var Le=63&m[F++];if((224&pe)==192)oe+=String.fromCharCode((31&pe)<<6|Le);else{var lt=63&m[F++];65536>(pe=(240&pe)==224?(15&pe)<<12|Le<<6|lt:(7&pe)<<18|Le<<12|lt<<6|63&m[F++])?oe+=String.fromCharCode(pe):(pe-=65536,oe+=String.fromCharCode(55296|pe>>10,56320|1023&pe))}}else oe+=String.fromCharCode(pe)}return oe},jn=(m,F)=>(m>>>=0)?Zy(u(),m,F):"";function Jy(m,F,K){return _e?Jr(3,1,m,F,K):0}function ew(m,F){if(_e)return Jr(4,1,m,F)}var tw=m=>{for(var F=0,K=0;K<m.length;++K){var oe=m.charCodeAt(K);127>=oe?F++:2047>=oe?F+=2:55296<=oe&&57343>=oe?(F+=4,++K):F+=3}return F},Sl=(m,F,K)=>{var oe=u();if(F>>>=0,0<K){var pe=F;K=F+K-1;for(var Le=0;Le<m.length;++Le){var lt=m.charCodeAt(Le);if(55296<=lt&&57343>=lt&&(lt=65536+((1023<)<<10)|1023&m.charCodeAt(++Le)),127>=lt){if(F>=K)break;oe[F++>>>0]=lt}else{if(2047>=lt){if(F+1>=K)break;oe[F++>>>0]=192|lt>>6}else{if(65535>=lt){if(F+2>=K)break;oe[F++>>>0]=224|lt>>12}else{if(F+3>=K)break;oe[F++>>>0]=240|lt>>18,oe[F++>>>0]=128|lt>>12&63}oe[F++>>>0]=128|lt>>6&63}oe[F++>>>0]=128|63<}}oe[F>>>0]=0,m=F-pe}else m=0;return m};function rw(m,F){if(_e)return Jr(5,1,m,F)}function nw(m,F,K){if(_e)return Jr(6,1,m,F,K)}function iw(m,F,K){return _e?Jr(7,1,m,F,K):0}function ow(m,F){if(_e)return Jr(8,1,m,F)}function sw(m,F,K){if(_e)return Jr(9,1,m,F,K)}function aw(m,F,K,oe){if(_e)return Jr(10,1,m,F,K,oe)}function lw(m,F,K,oe){if(_e)return Jr(11,1,m,F,K,oe)}function uw(m,F,K,oe){if(_e)return Jr(12,1,m,F,K,oe)}function cw(m){if(_e)return Jr(13,1,m)}function dw(m,F){if(_e)return Jr(14,1,m,F)}function fw(m,F,K){if(_e)return Jr(15,1,m,F,K)}var pw,rs,Mx=()=>{kl("")},to=m=>{for(var F="";u()[m>>>0];)F+=pw[u()[m++>>>0]];return F},Om={},Dm={};function bo(m,F,K={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(oe,pe,Le={}){var lt=pe.name;if(!oe)throw new rs(`type "${lt}" must have a positive integer typeid pointer`);if(Dm.hasOwnProperty(oe)){if(Le.Jb)return;throw new rs(`Cannot register type '${lt}' twice`)}Dm[oe]=pe,Om.hasOwnProperty(oe)&&(pe=Om[oe],delete Om[oe],pe.forEach(yt=>yt()))}(m,F,K)}var hw=(m,F,K)=>{switch(F){case 1:return K?oe=>s()[oe>>>0]:oe=>u()[oe>>>0];case 2:return K?oe=>c()[oe>>>1>>>0]:oe=>p()[oe>>>1>>>0];case 4:return K?oe=>d()[oe>>>2>>>0]:oe=>b()[oe>>>2>>>0];case 8:return K?oe=>xn[oe>>>3]:oe=>Yn[oe>>>3];default:throw new TypeError(`invalid integer width (${F}): ${m}`)}};function Tx(m,F,K){K>>>=0,bo(m>>>=0,{name:F=to(F>>>0),fromWireType:oe=>oe,toWireType:function(oe,pe){if(typeof pe!="bigint"&&typeof pe!="number")throw pe=pe===null?"null":(oe=typeof pe)=="object"||oe==="array"||oe==="function"?pe.toString():""+pe,new TypeError(`Cannot convert "${pe}" to ${this.name}`);return typeof pe=="number"&&(pe=BigInt(pe)),pe},argPackAdvance:ns,readValueFromPointer:hw(F,K,F.indexOf("u")==-1),yb:null})}var ns=8;function kx(m,F,K,oe){bo(m>>>=0,{name:F=to(F>>>0),fromWireType:function(pe){return!!pe},toWireType:function(pe,Le){return Le?K:oe},argPackAdvance:ns,readValueFromPointer:function(pe){return this.fromWireType(u()[pe>>>0])},yb:null})}var Lm=[],xo=[];function Rm(m){9<(m>>>=0)&&--xo[m+1]==0&&(xo[m]=void 0,Lm.push(m))}var Pi=m=>{if(!m)throw new rs("Cannot use deleted val. handle = "+m);return xo[m]},$i=m=>{switch(m){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let F=Lm.pop()||xo.length;return xo[F]=m,xo[F+1]=1,F}};function Bm(m){return this.fromWireType(b()[m>>>2>>>0])}var Sx={name:"emscripten::val",fromWireType:m=>{var F=Pi(m);return Rm(m),F},toWireType:(m,F)=>$i(F),argPackAdvance:ns,readValueFromPointer:Bm,yb:null};function Ex(m){return bo(m>>>0,Sx)}var Cx=(m,F)=>{switch(F){case 4:return function(K){return this.fromWireType(T()[K>>>2>>>0])};case 8:return function(K){return this.fromWireType(E()[K>>>3>>>0])};default:throw new TypeError(`invalid float width (${F}): ${m}`)}};function Px(m,F,K){K>>>=0,bo(m>>>=0,{name:F=to(F>>>0),fromWireType:oe=>oe,toWireType:(oe,pe)=>pe,argPackAdvance:ns,readValueFromPointer:Cx(F,K),yb:null})}function $x(m,F,K,oe,pe){if(m>>>=0,K>>>=0,F=to(F>>>0),pe===-1&&(pe=4294967295),pe=yt=>yt,oe===0){var Le=32-8*K;pe=yt=>yt<<Le>>>Le}var lt=F.includes("unsigned")?function(yt,$t){return $t>>>0}:function(yt,$t){return $t};bo(m,{name:F,fromWireType:pe,toWireType:lt,argPackAdvance:ns,readValueFromPointer:hw(F,K,oe!==0),yb:null})}function Ax(m,F,K){function oe(Le){var lt=b()[Le>>>2>>>0];return Le=b()[Le+4>>>2>>>0],new pe(s().buffer,Le,lt)}var pe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][F];bo(m>>>=0,{name:K=to(K>>>0),fromWireType:oe,argPackAdvance:ns,readValueFromPointer:oe},{Jb:!0})}function Ix(m,F){m>>>=0;var K=(F=to(F>>>0))==="std::string";bo(m,{name:F,fromWireType:function(oe){var pe=b()[oe>>>2>>>0],Le=oe+4;if(K)for(var lt=Le,yt=0;yt<=pe;++yt){var $t=Le+yt;if(yt==pe||u()[$t>>>0]==0){if(lt=jn(lt,$t-lt),Nt===void 0)var Nt=lt;else Nt+="\0",Nt+=lt;lt=$t+1}}else{for(Nt=Array(pe),yt=0;yt<pe;++yt)Nt[yt]=String.fromCharCode(u()[Le+yt>>>0]);Nt=Nt.join("")}return no(oe),Nt},toWireType:function(oe,pe){pe instanceof ArrayBuffer&&(pe=new Uint8Array(pe));var Le=typeof pe=="string";if(!(Le||pe instanceof Uint8Array||pe instanceof Uint8ClampedArray||pe instanceof Int8Array))throw new rs("Cannot pass non-string to std::string");var lt=K&&Le?tw(pe):pe.length,yt=Up(4+lt+1),$t=yt+4;if(b()[yt>>>2>>>0]=lt,K&&Le)Sl(pe,$t,lt+1);else if(Le)for(Le=0;Le<lt;++Le){var Nt=pe.charCodeAt(Le);if(255<Nt)throw no($t),new rs("String has UTF-16 code units that do not fit in 8 bits");u()[$t+Le>>>0]=Nt}else for(Le=0;Le<lt;++Le)u()[$t+Le>>>0]=pe[Le];return oe!==null&&oe.push(no,yt),yt},argPackAdvance:ns,readValueFromPointer:Bm,yb(oe){no(oe)}})}var mw=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Fx=(m,F)=>{for(var K=m>>1,oe=K+F/2;!(K>=oe)&&p()[K>>>0];)++K;if(32<(K<<=1)-m&&mw)return mw.decode(u().slice(m,K));for(K="",oe=0;!(oe>=F/2);++oe){var pe=c()[m+2*oe>>>1>>>0];if(pe==0)break;K+=String.fromCharCode(pe)}return K},zx=(m,F,K)=>{if(K??(K=2147483647),2>K)return 0;var oe=F;K=(K-=2)<2*m.length?K/2:m.length;for(var pe=0;pe<K;++pe){var Le=m.charCodeAt(pe);c()[F>>>1>>>0]=Le,F+=2}return c()[F>>>1>>>0]=0,F-oe},Ox=m=>2*m.length,Dx=(m,F)=>{for(var K=0,oe="";!(K>=F/4);){var pe=d()[m+4*K>>>2>>>0];if(pe==0)break;++K,65536<=pe?(pe-=65536,oe+=String.fromCharCode(55296|pe>>10,56320|1023&pe)):oe+=String.fromCharCode(pe)}return oe},Lx=(m,F,K)=>{if(F>>>=0,K??(K=2147483647),4>K)return 0;var oe=F;K=oe+K-4;for(var pe=0;pe<m.length;++pe){var Le=m.charCodeAt(pe);if(55296<=Le&&57343>=Le&&(Le=65536+((1023&Le)<<10)|1023&m.charCodeAt(++pe)),d()[F>>>2>>>0]=Le,(F+=4)+4>K)break}return d()[F>>>2>>>0]=0,F-oe},Rx=m=>{for(var F=0,K=0;K<m.length;++K){var oe=m.charCodeAt(K);55296<=oe&&57343>=oe&&++K,F+=4}return F};function Bx(m,F,K){if(m>>>=0,F>>>=0,K=to(K>>>=0),F===2)var oe=Fx,pe=zx,Le=Ox,lt=yt=>p()[yt>>>1>>>0];else F===4&&(oe=Dx,pe=Lx,Le=Rx,lt=yt=>b()[yt>>>2>>>0]);bo(m,{name:K,fromWireType:yt=>{for(var $t,Nt=b()[yt>>>2>>>0],lr=yt+4,Ar=0;Ar<=Nt;++Ar){var Lr=yt+4+Ar*F;Ar!=Nt&<(Lr)!=0||(lr=oe(lr,Lr-lr),$t===void 0?$t=lr:($t+="\0",$t+=lr),lr=Lr+F)}return no(yt),$t},toWireType:(yt,$t)=>{if(typeof $t!="string")throw new rs(`Cannot pass non-string to C++ string type ${K}`);var Nt=Le($t),lr=Up(4+Nt+F);return b()[lr>>>2>>>0]=Nt/F,pe($t,lr+4,Nt+F),yt!==null&&yt.push(no,lr),lr},argPackAdvance:ns,readValueFromPointer:Bm,yb(yt){no(yt)}})}function Nx(m,F){bo(m>>>=0,{Kb:!0,name:F=to(F>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var jx=()=>1;function Ux(m){Hm(m>>>0,!ce,1,!re,131072,!1),qy()}var gw=m=>{if(!hi)try{if(m(),!(0<Ks))try{_e?Vp(It):zm(It)}catch(F){F instanceof Am||F=="unwind"||et(1,F)}}catch(F){F instanceof Am||F=="unwind"||et(1,F)}};function Nm(m){m>>>=0,typeof Atomics.Xb=="function"&&(Atomics.Xb(d(),m>>>2,m).value.then(zp),m+=128,Atomics.store(d(),m>>>2,1))}var zp=()=>{var m=El();m&&(Nm(m),gw(Ww))};function Vx(m,F){(m>>>=0)==F>>>0?setTimeout(zp):_e?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=eo[m])&&m.postMessage({cmd:"checkMailbox"})}var jm=[];function Wx(m,F,K,oe,pe){for(F>>>=0,oe/=2,jm.length=oe,K=pe>>>0>>>3,pe=0;pe<oe;pe++)jm[pe]=xn[K+2*pe]?xn[K+2*pe+1]:E()[K+2*pe+1>>>0];return(F?$m[F]:AM[m])(...jm)}function Gx(m){m>>>=0,_e?postMessage({cmd:"cleanupThread",thread:m}):Gy(eo[m])}function qx(m){}var Um=(m,F)=>{var K=Dm[m];if(K===void 0)throw m=Nw(m),K=to(m),no(m),new rs(`${F} has unknown type ${K}`);return K},_w=(m,F,K)=>{var oe=[];return m=m.toWireType(oe,K),oe.length&&(b()[F>>>2>>>0]=$i(oe)),m};function Hx(m,F,K){return F>>>=0,K>>>=0,m=Pi(m>>>0),F=Um(F,"emval::as"),_w(F,K,m)}var Op=m=>{try{m()}catch(F){kl(F)}},is=0,ro=null,yw=0,Dp=[],ww={},vw={},Kx=0,Vm=null,Qx=[];function bw(m){return function(F){if(!hi){if(is===0){var K=!1,oe=!1;F((pe=0)=>{if(!hi&&(yw=pe,K=!0,oe)){is=2,Op(()=>Qw(ro)),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.resume(),pe=!1;try{var Le=function(){var $t=d()[ro+8>>>2>>>0];return $t=Ht[vw[$t]],--Ks,$t()}()}catch($t){Le=$t,pe=!0}var lt=!1;if(!ro){var yt=Vm;yt&&(Vm=null,(pe?yt.reject:yt.resolve)(Le),lt=!0)}if(pe&&!lt)throw Le}}),oe=!0,K||(is=1,ro=function(){var pe=Up(65548),Le=pe+12;b()[pe>>>2>>>0]=Le,b()[pe+4>>>2>>>0]=Le+65536,Le=Dp[0];var lt=ww[Le];return lt===void 0&&(lt=Kx++,ww[Le]=lt,vw[lt]=Le),Le=lt,d()[pe+8>>>2>>>0]=Le,pe}(),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.pause(),Op(()=>Hw(ro)))}else is===2?(is=0,Op(Xw),no(ro),ro=null,Qx.forEach(gw)):kl(`invalid state: ${is}`);return yw}}(F=>{m().then(F)})}function Xx(m){return m>>>=0,bw(()=>(m=Pi(m)).then($i))}var Lp=[];function Yx(m,F,K,oe){return K>>>=0,oe>>>=0,(m=Lp[m>>>0])(null,F=Pi(F>>>0),K,oe)}var Zx={},Rp=m=>{var F=Zx[m];return F===void 0?to(m):F};function Jx(m,F,K,oe,pe){return K>>>=0,oe>>>=0,pe>>>=0,(m=Lp[m>>>0])(F=Pi(F>>>0),F[K=Rp(K)],oe,pe)}var xw=()=>typeof globalThis=="object"?globalThis:Function("return this")();function eM(m){return(m>>>=0)==0?$i(xw()):(m=Rp(m),$i(xw()[m]))}var tM=m=>{var F=Lp.length;return Lp.push(m),F},rM=(m,F)=>{for(var K=Array(m),oe=0;oe<m;++oe)K[oe]=Um(b()[F+4*oe>>>2>>>0],"parameter "+oe);return K},Mw=(m,F)=>Object.defineProperty(F,"name",{value:m});function nM(m,F,K){var oe=(F=rM(m,F>>>0)).shift();m--;var pe=`return function (obj, func, destructorsRef, args) { +`,Le=0,lt=[];K===0&<.push("obj");for(var yt=["retType"],$t=[oe],Nt=0;Nt<m;++Nt)lt.push("arg"+Nt),yt.push("argType"+Nt),$t.push(F[Nt]),pe+=` var arg${Nt} = argType${Nt}.readValueFromPointer(args${Le?"+"+Le:""}); +`,Le+=F[Nt].argPackAdvance;return pe+=` var rv = ${K===1?"new func":"func.call"}(${lt.join(", ")}); +`,oe.Kb||(yt.push("emval_returnValue"),$t.push(_w),pe+=` return emval_returnValue(retType, destructorsRef, rv); +`),yt.push(pe+`}; +`),m=function(lr){var Ar=Function;if(!(Ar instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof Ar} which is not a function`);var Lr=Mw(Ar.name||"unknownFunctionName",function(){});return Lr.prototype=Ar.prototype,Lr=new Lr,(lr=Ar.apply(Lr,lr))instanceof Object?lr:Lr}(yt)(...$t),K=`methodCaller<(${F.map(lr=>lr.name).join(", ")}) => ${oe.name}>`,tM(Mw(K,m))}function iM(m){return m=Rp(m>>>0),$i(v[m])}function oM(m,F){return F>>>=0,m=Pi(m>>>0),F=Pi(F),$i(m[F])}function sM(m){9<(m>>>=0)&&(xo[m+1]+=1)}function aM(){return $i([])}function lM(m){m=Pi(m>>>0);for(var F=Array(m.length),K=0;K<m.length;K++)F[K]=m[K];return $i(F)}function uM(m){return $i(Rp(m>>>0))}function cM(){return $i({})}function dM(m){for(var F=Pi(m>>>=0);F.length;){var K=F.pop();F.pop()(K)}Rm(m)}function fM(m,F,K){F>>>=0,K>>>=0,m=Pi(m>>>0),F=Pi(F),K=Pi(K),m[F]=K}function pM(m,F){return F>>>=0,m=(m=Um(m>>>0,"_emval_take_value")).readValueFromPointer(F),$i(m)}function hM(m,F){m=-9007199254740992>m||9007199254740992<m?NaN:Number(m),F>>>=0,m=new Date(1e3*m),d()[F>>>2>>>0]=m.getUTCSeconds(),d()[F+4>>>2>>>0]=m.getUTCMinutes(),d()[F+8>>>2>>>0]=m.getUTCHours(),d()[F+12>>>2>>>0]=m.getUTCDate(),d()[F+16>>>2>>>0]=m.getUTCMonth(),d()[F+20>>>2>>>0]=m.getUTCFullYear()-1900,d()[F+24>>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,d()[F+28>>>2>>>0]=m}var Tw=m=>m%4==0&&(m%100!=0||m%400==0),kw=[0,31,60,91,121,152,182,213,244,274,305,335],Sw=[0,31,59,90,120,151,181,212,243,273,304,334];function mM(m,F){m=-9007199254740992>m||9007199254740992<m?NaN:Number(m),F>>>=0,m=new Date(1e3*m),d()[F>>>2>>>0]=m.getSeconds(),d()[F+4>>>2>>>0]=m.getMinutes(),d()[F+8>>>2>>>0]=m.getHours(),d()[F+12>>>2>>>0]=m.getDate(),d()[F+16>>>2>>>0]=m.getMonth(),d()[F+20>>>2>>>0]=m.getFullYear()-1900,d()[F+24>>>2>>>0]=m.getDay();var K=(Tw(m.getFullYear())?kw:Sw)[m.getMonth()]+m.getDate()-1|0;d()[F+28>>>2>>>0]=K,d()[F+36>>>2>>>0]=-60*m.getTimezoneOffset(),K=new Date(m.getFullYear(),6,1).getTimezoneOffset();var oe=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(K!=oe&&m.getTimezoneOffset()==Math.min(oe,K)),d()[F+32>>>2>>>0]=m}function gM(m){m>>>=0;var F=new Date(d()[m+20>>>2>>>0]+1900,d()[m+16>>>2>>>0],d()[m+12>>>2>>>0],d()[m+8>>>2>>>0],d()[m+4>>>2>>>0],d()[m>>>2>>>0],0),K=d()[m+32>>>2>>>0],oe=F.getTimezoneOffset(),pe=new Date(F.getFullYear(),6,1).getTimezoneOffset(),Le=new Date(F.getFullYear(),0,1).getTimezoneOffset(),lt=Math.min(Le,pe);return 0>K?d()[m+32>>>2>>>0]=+(pe!=Le&<==oe):0<K!=(lt==oe)&&(pe=Math.max(Le,pe),F.setTime(F.getTime()+6e4*((0<K?lt:pe)-oe))),d()[m+24>>>2>>>0]=F.getDay(),K=(Tw(F.getFullYear())?kw:Sw)[F.getMonth()]+F.getDate()-1|0,d()[m+28>>>2>>>0]=K,d()[m>>>2>>>0]=F.getSeconds(),d()[m+4>>>2>>>0]=F.getMinutes(),d()[m+8>>>2>>>0]=F.getHours(),d()[m+12>>>2>>>0]=F.getDate(),d()[m+16>>>2>>>0]=F.getMonth(),d()[m+20>>>2>>>0]=F.getYear(),m=F.getTime(),BigInt(isNaN(m)?-1:m/1e3)}function Ew(m,F,K,oe,pe,Le,lt){return _e?Jr(16,1,m,F,K,oe,pe,Le,lt):-52}function Cw(m,F,K,oe,pe,Le){if(_e)return Jr(17,1,m,F,K,oe,pe,Le)}function _M(m,F,K,oe){m>>>=0,F>>>=0,K>>>=0,oe>>>=0;var pe=new Date().getFullYear(),Le=new Date(pe,0,1),lt=new Date(pe,6,1);pe=Le.getTimezoneOffset();var yt=lt.getTimezoneOffset(),$t=Math.max(pe,yt);b()[m>>>2>>>0]=60*$t,d()[F>>>2>>>0]=+(pe!=yt),Le=(m=Nt=>Nt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(Le),lt=m(lt),yt<pe?(Sl(Le,K,17),Sl(lt,oe,17)):(Sl(Le,oe,17),Sl(lt,K,17))}var Wm=[],Pw=(m,F)=>{Wm.length=0;for(var K;K=u()[m++>>>0];){var oe=K!=105;F+=(oe&=K!=112)&&F%8?4:0,Wm.push(K==112?b()[F>>>2>>>0]:K==106?xn[F>>>3]:K==105?d()[F>>>2>>>0]:E()[F>>>3>>>0]),F+=oe?8:4}return Wm};function yM(m,F,K){return m>>>=0,F=Pw(F>>>0,K>>>0),$m[m](...F)}function wM(m,F,K){return m>>>=0,F=Pw(F>>>0,K>>>0),$m[m](...F)}var vM=()=>{},bM=()=>Date.now();function xM(m,F){return nr(jn(m>>>0,F>>>0))}var $w,MM=()=>{throw Ks+=1,"unwind"};function TM(){return 4294901760}$w=()=>performance.timeOrigin+performance.now();var kM=()=>navigator.hardwareConcurrency;function SM(){return kl("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function EM(m){m>>>=0;var F=u().length;if(m<=F||4294901760<m)return!1;for(var K=1;4>=K;K*=2){var oe=F*(1+.2/K);oe=Math.min(oe,m+100663296);var pe=Math;oe=Math.max(m,oe);e:{pe=(pe.min.call(pe,4294901760,oe+(65536-oe%65536)%65536)-Sr.buffer.byteLength+65535)/65536;try{Sr.grow(pe),In();var Le=1;break e}catch{}Le=void 0}if(Le)return!0}return!1}var Bp=()=>(kl("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),af={},Aw=m=>{m.forEach(F=>{Bp()})};function CM(){var m=Error().stack.toString().split(` +`);return m[0]=="Error"&&m.shift(),Aw(m),af.Gb=Bp(),af.Tb=m,af.Gb}function PM(m,F,K){if(m>>>=0,F>>>=0,af.Gb==m)var oe=af.Tb;else(oe=Error().stack.toString().split(` +`))[0]=="Error"&&oe.shift(),Aw(oe);for(var pe=3;oe[pe]&&Bp()!=m;)++pe;for(m=0;m<K&&oe[m+pe];++m)d()[F+4*m>>>2>>>0]=Bp();return m}var Gm,qm={},Iw=()=>{if(!Gm){var m,F={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:ct};for(m in qm)qm[m]===void 0?delete F[m]:F[m]=qm[m];var K=[];for(m in F)K.push(`${m}=${F[m]}`);Gm=K}return Gm};function Fw(m,F){if(_e)return Jr(18,1,m,F);m>>>=0,F>>>=0;var K=0;return Iw().forEach((oe,pe)=>{var Le=F+K;for(pe=b()[m+4*pe>>>2>>>0]=Le,Le=0;Le<oe.length;++Le)s()[pe++>>>0]=oe.charCodeAt(Le);s()[pe>>>0]=0,K+=oe.length+1}),0}function zw(m,F){if(_e)return Jr(19,1,m,F);m>>>=0,F>>>=0;var K=Iw();b()[m>>>2>>>0]=K.length;var oe=0;return K.forEach(pe=>oe+=pe.length+1),b()[F>>>2>>>0]=oe,0}function Ow(m){return _e?Jr(20,1,m):52}function Dw(m,F,K,oe){return _e?Jr(21,1,m,F,K,oe):52}function Lw(m,F,K,oe){return _e?Jr(22,1,m,F,K,oe):70}var $M=[null,[],[]];function Rw(m,F,K,oe){if(_e)return Jr(23,1,m,F,K,oe);F>>>=0,K>>>=0,oe>>>=0;for(var pe=0,Le=0;Le<K;Le++){var lt=b()[F>>>2>>>0],yt=b()[F+4>>>2>>>0];F+=8;for(var $t=0;$t<yt;$t++){var Nt=u()[lt+$t>>>0],lr=$M[m];Nt===0||Nt===10?((m===1?ar:nr)(Zy(lr,0)),lr.length=0):lr.push(Nt)}pe+=yt}return b()[oe>>>2>>>0]=pe,0}_e||function(){for(var m=v.numThreads-1;m--;)Ky();sf.unshift(()=>{Ci++,function(F){_e?F():Promise.all(ts.map(Hy)).then(F)}(()=>Ip())})}();for(var Bw=Array(256),Np=0;256>Np;++Np)Bw[Np]=String.fromCharCode(Np);pw=Bw,rs=v.BindingError=class extends Error{constructor(m){super(m),this.name="BindingError"}},v.InternalError=class extends Error{constructor(m){super(m),this.name="InternalError"}},xo.push(0,1,void 0,1,null,1,!0,1,!1,1),v.count_emval_handles=()=>xo.length/2-5-Lm.length;var AM=[Fm,Vy,Qy,Jy,ew,rw,nw,iw,ow,sw,aw,lw,uw,cw,dw,fw,Ew,Cw,Fw,zw,Ow,Dw,Lw,Rw],Ht=function(){function m(K,oe){return Ht=K.exports,Ht=function(){var pe=Ht,Le={};for(let[lt,yt]of Object.entries(pe))Le[lt]=typeof yt=="function"?(...$t)=>{Dp.push(lt);try{return yt(...$t)}finally{hi||(Dp.pop(),ro&&is===1&&Dp.length===0&&(is=0,Ks+=1,Op(Kw),typeof Fibers<"u"&&Fibers.ac()))}}:yt;return Le}(),Ht=function(){var pe=Ht,Le=yt=>$t=>yt($t)>>>0,lt=yt=>()=>yt()>>>0;return(pe=Object.assign({},pe)).Aa=Le(pe.Aa),pe.db=lt(pe.db),pe.eb=Le(pe.eb),pe.emscripten_main_runtime_thread_id=lt(pe.emscripten_main_runtime_thread_id),pe.qb=Le(pe.qb),pe.rb=lt(pe.rb),pe}(),Wy.push(Ht.gb),Fn.unshift(Ht.za),jr=oe,Ip(),Ht}var F=jy();if(Ci++,v.instantiateWasm)try{return v.instantiateWasm(F,m)}catch(K){nr(`Module.instantiateWasm callback failed with error: ${K}`),H(K)}return Pm||(Pm=v.locateFile?Ly("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":v.locateFile?v.locateFile("ort-wasm-simd-threaded.jsep.wasm",vt):vt+"ort-wasm-simd-threaded.jsep.wasm":new URL(n("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),n.b).href),function(K,oe){var pe=Pm;return Ft||typeof WebAssembly.instantiateStreaming!="function"||Ly(pe)||Ry(pe)||typeof fetch!="function"?Ny(pe,K,oe):fetch(pe,{credentials:"same-origin"}).then(Le=>WebAssembly.instantiateStreaming(Le,K).then(oe,function(lt){return nr(`wasm streaming compile failed: ${lt}`),nr("falling back to ArrayBuffer instantiation"),Ny(pe,K,oe)}))}(F,function(K){m(K.instance,K.module)}).catch(H),{}}(),Nw=m=>(Nw=Ht.Aa)(m),jw=()=>(jw=Ht.Ba)();v._OrtInit=(m,F)=>(v._OrtInit=Ht.Ca)(m,F),v._OrtGetLastError=(m,F)=>(v._OrtGetLastError=Ht.Da)(m,F),v._OrtCreateSessionOptions=(m,F,K,oe,pe,Le,lt,yt,$t,Nt)=>(v._OrtCreateSessionOptions=Ht.Ea)(m,F,K,oe,pe,Le,lt,yt,$t,Nt),v._OrtAppendExecutionProvider=(m,F)=>(v._OrtAppendExecutionProvider=Ht.Fa)(m,F),v._OrtAddFreeDimensionOverride=(m,F,K)=>(v._OrtAddFreeDimensionOverride=Ht.Ga)(m,F,K),v._OrtAddSessionConfigEntry=(m,F,K)=>(v._OrtAddSessionConfigEntry=Ht.Ha)(m,F,K),v._OrtReleaseSessionOptions=m=>(v._OrtReleaseSessionOptions=Ht.Ia)(m),v._OrtCreateSession=(m,F,K)=>(v._OrtCreateSession=Ht.Ja)(m,F,K),v._OrtReleaseSession=m=>(v._OrtReleaseSession=Ht.Ka)(m),v._OrtGetInputOutputCount=(m,F,K)=>(v._OrtGetInputOutputCount=Ht.La)(m,F,K),v._OrtGetInputName=(m,F)=>(v._OrtGetInputName=Ht.Ma)(m,F),v._OrtGetOutputName=(m,F)=>(v._OrtGetOutputName=Ht.Na)(m,F),v._OrtFree=m=>(v._OrtFree=Ht.Oa)(m),v._OrtCreateTensor=(m,F,K,oe,pe,Le)=>(v._OrtCreateTensor=Ht.Pa)(m,F,K,oe,pe,Le),v._OrtGetTensorData=(m,F,K,oe,pe)=>(v._OrtGetTensorData=Ht.Qa)(m,F,K,oe,pe),v._OrtReleaseTensor=m=>(v._OrtReleaseTensor=Ht.Ra)(m),v._OrtCreateRunOptions=(m,F,K,oe)=>(v._OrtCreateRunOptions=Ht.Sa)(m,F,K,oe),v._OrtAddRunConfigEntry=(m,F,K)=>(v._OrtAddRunConfigEntry=Ht.Ta)(m,F,K),v._OrtReleaseRunOptions=m=>(v._OrtReleaseRunOptions=Ht.Ua)(m),v._OrtCreateBinding=m=>(v._OrtCreateBinding=Ht.Va)(m),v._OrtBindInput=(m,F,K)=>(v._OrtBindInput=Ht.Wa)(m,F,K),v._OrtBindOutput=(m,F,K,oe)=>(v._OrtBindOutput=Ht.Xa)(m,F,K,oe),v._OrtClearBoundOutputs=m=>(v._OrtClearBoundOutputs=Ht.Ya)(m),v._OrtReleaseBinding=m=>(v._OrtReleaseBinding=Ht.Za)(m),v._OrtRunWithBinding=(m,F,K,oe,pe)=>(v._OrtRunWithBinding=Ht._a)(m,F,K,oe,pe),v._OrtRun=(m,F,K,oe,pe,Le,lt,yt)=>(v._OrtRun=Ht.$a)(m,F,K,oe,pe,Le,lt,yt),v._OrtEndProfiling=m=>(v._OrtEndProfiling=Ht.ab)(m),v._JsepOutput=(m,F,K)=>(v._JsepOutput=Ht.bb)(m,F,K),v._JsepGetNodeName=m=>(v._JsepGetNodeName=Ht.cb)(m);var jp,El=()=>(El=Ht.db)(),Up=v._malloc=m=>(Up=v._malloc=Ht.eb)(m),no=v._free=m=>(no=v._free=Ht.fb)(m),Hm=(m,F,K,oe,pe,Le)=>(Hm=Ht.ib)(m,F,K,oe,pe,Le),Uw=()=>(Uw=Ht.jb)(),Vw=(m,F,K,oe,pe)=>(Vw=Ht.kb)(m,F,K,oe,pe),Km=m=>(Km=Ht.lb)(m),Vp=m=>(Vp=Ht.mb)(m),Ww=()=>(Ww=Ht.nb)(),Gw=(m,F)=>(Gw=Ht.ob)(m,F),Wp=m=>(Wp=Ht.pb)(m),Qm=m=>(Qm=Ht.qb)(m),Xm=()=>(Xm=Ht.rb)(),qw=v.dynCall_ii=(m,F)=>(qw=v.dynCall_ii=Ht.tb)(m,F),Hw=m=>(Hw=Ht.ub)(m),Kw=()=>(Kw=Ht.vb)(),Qw=m=>(Qw=Ht.wb)(m),Xw=()=>(Xw=Ht.xb)();function Yw(){0<Ci||(_e?(q(v),_e||Fp(Fn),startWorker(v)):(Fp(sf),0<Ci||jp||(jp=!0,v.calledRun=!0,hi||(_e||Fp(Fn),q(v),_e||Fp(Zn)))))}return v.stackSave=()=>Xm(),v.stackRestore=m=>Wp(m),v.stackAlloc=m=>Qm(m),v.UTF8ToString=jn,v.stringToUTF8=Sl,v.lengthBytesUTF8=tw,es=function m(){jp||Yw(),jp||(es=m)},Yw(),ne}),St=wt,((r=globalThis.self)==null?void 0:r.name)==="em-pthread"&&wt()}),at,Ot,Ut,Kt,Qt,Jt,qt,Er,Qr=h(()=>{var r,i;ve(),at=import.meta.url??(typeof document<"u"?(r=document.currentScript)==null?void 0:r.src:typeof self<"u"?(i=self.location)==null?void 0:i.href:void 0),Ot=typeof location>"u"?void 0:location.origin,Ut=(s,u)=>{try{let c=u??at;return(c?new URL(s,c):new URL(s)).origin===Ot}catch{return!1}},Kt=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},Qt=(ft(),w(Re)).default,Jt=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ut(at))return[void 0,Qt()];let s=await Kt(at);return[s,Qt(s)]},qt=(Rt(),w(ht)).default,Er=async(s,u,c)=>[void 0,qt]}),Cr,mt,Pt,Bt,sn,Li,bi,Nr,mn=h(()=>{Qr(),mt=!1,Pt=!1,Bt=!1,sn=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Li=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},bi=async r=>{if(mt)return Promise.resolve();if(Pt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Pt=!0;let i=r.initTimeout,s=r.numThreads;if(!Li())throw new Error("WebAssembly SIMD is not supported in the current environment.");let u=sn();s>1&&!u&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),r.numThreads=s=1);let c=r.wasmPaths,p=typeof c=="string"?c:void 0,d=c==null?void 0:c.mjs,b=(d==null?void 0:d.href)??d,T=c==null?void 0:c.wasm,E=(T==null?void 0:T.href)??T,q=r.wasmBinary,[H,v]=await Er(b,p,s>1),ne=!1,re=[];if(i>0&&re.push(new Promise(ce=>{setTimeout(()=>{ne=!0,ce()},i)})),re.push(new Promise((ce,_e)=>{let be={numThreads:s};q?be.wasmBinary=q:(E||p)&&(be.locateFile=(he,Fe)=>E??(p??Fe)+he),v(be).then(he=>{Pt=!1,mt=!0,Cr=he,ce(),H&&URL.revokeObjectURL(H)},he=>{Pt=!1,Bt=!0,_e(he)})})),await Promise.race(re),ne)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Nr=()=>{if(mt&&Cr)return Cr;throw new Error("WebAssembly is not initialized yet.")}}),Wr,ci,Fr,Ri=h(()=>{mn(),Wr=(r,i)=>{let s=Nr(),u=s.lengthBytesUTF8(r)+1,c=s._malloc(u);return s.stringToUTF8(r,c,u),i.push(c),c},ci=(r,i,s,u)=>{if(typeof r=="object"&&r!==null){if(s.has(r))throw new Error("Circular reference in options");s.add(r)}Object.entries(r).forEach(([c,p])=>{let d=i?i+c:c;if(typeof p=="object")ci(p,d+".",s,u);else if(typeof p=="string"||typeof p=="number")u(d,p.toString());else if(typeof p=="boolean")u(d,p?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof p}`)})},Fr=r=>{let i=Nr(),s=i.stackSave();try{let u=i.stackAlloc(8);i._OrtGetLastError(u,u+4);let c=i.HEAP32[u/4],p=i.HEAPU32[u/4+1],d=p?i.UTF8ToString(p):"";throw new Error(`${r} ERROR_CODE: ${c}, ERROR_MESSAGE: ${d}`)}finally{i.stackRestore(s)}}}),xi,ks=h(()=>{mn(),Ri(),xi=r=>{let i=Nr(),s=0,u=[],c=r||{};try{if((r==null?void 0:r.logSeverityLevel)===void 0)c.logSeverityLevel=2;else if(typeof r.logSeverityLevel!="number"||!Number.isInteger(r.logSeverityLevel)||r.logSeverityLevel<0||r.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${r.logSeverityLevel}`);if((r==null?void 0:r.logVerbosityLevel)===void 0)c.logVerbosityLevel=0;else if(typeof r.logVerbosityLevel!="number"||!Number.isInteger(r.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${r.logVerbosityLevel}`);(r==null?void 0:r.terminate)===void 0&&(c.terminate=!1);let p=0;return(r==null?void 0:r.tag)!==void 0&&(p=Wr(r.tag,u)),s=i._OrtCreateRunOptions(c.logSeverityLevel,c.logVerbosityLevel,!!c.terminate,p),s===0&&Fr("Can't create run options."),(r==null?void 0:r.extra)!==void 0&&ci(r.extra,"",new WeakSet,(d,b)=>{let T=Wr(d,u),E=Wr(b,u);i._OrtAddRunConfigEntry(s,T,E)!==0&&Fr(`Can't set a run config entry: ${d} - ${b}.`)}),[s,u]}catch(p){throw s!==0&&i._OrtReleaseRunOptions(s),u.forEach(d=>i._free(d)),p}}}),Oo,Do,Lo,Ro,Bi,Ss=h(()=>{mn(),Ri(),Oo=r=>{switch(r){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${r}`)}},Do=r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}},Lo=r=>{r.extra||(r.extra={}),r.extra.session||(r.extra.session={});let i=r.extra.session;i.use_ort_model_bytes_directly||(i.use_ort_model_bytes_directly="1"),r.executionProviders&&r.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(r.enableMemPattern=!1)},Ro=(r,i,s)=>{for(let u of i){let c=typeof u=="string"?u:u.name;switch(c){case"webnn":if(c="WEBNN",typeof u!="string"){let d=u==null?void 0:u.deviceType;if(d){let b=Wr("deviceType",s),T=Wr(d,s);Nr()._OrtAddSessionConfigEntry(r,b,T)!==0&&Fr(`Can't set a session config entry: 'deviceType' - ${d}.`)}}break;case"webgpu":if(c="JS",typeof u!="string"){let d=u;if(d!=null&&d.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);let b=Wr("preferredLayout",s),T=Wr(d.preferredLayout,s);Nr()._OrtAddSessionConfigEntry(r,b,T)!==0&&Fr(`Can't set a session config entry: 'preferredLayout' - ${d.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${c}`)}let p=Wr(c,s);Nr()._OrtAppendExecutionProvider(r,p)!==0&&Fr(`Can't append execution provider: ${c}.`)}},Bi=r=>{let i=Nr(),s=0,u=[],c=r||{};Lo(c);try{let p=Oo(c.graphOptimizationLevel??"all"),d=Do(c.executionMode??"sequential"),b=typeof c.logId=="string"?Wr(c.logId,u):0,T=c.logSeverityLevel??2;if(!Number.isInteger(T)||T<0||T>4)throw new Error(`log serverity level is not valid: ${T}`);let E=c.logVerbosityLevel??0;if(!Number.isInteger(E)||E<0||E>4)throw new Error(`log verbosity level is not valid: ${E}`);let q=typeof c.optimizedModelFilePath=="string"?Wr(c.optimizedModelFilePath,u):0;if(s=i._OrtCreateSessionOptions(p,!!c.enableCpuMemArena,!!c.enableMemPattern,d,!!c.enableProfiling,0,b,T,E,q),s===0&&Fr("Can't create session options."),c.executionProviders&&Ro(s,c.executionProviders,u),c.enableGraphCapture!==void 0){if(typeof c.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${c.enableGraphCapture}`);let H=Wr("enableGraphCapture",u),v=Wr(c.enableGraphCapture.toString(),u);i._OrtAddSessionConfigEntry(s,H,v)!==0&&Fr(`Can't set a session config entry: 'enableGraphCapture' - ${c.enableGraphCapture}.`)}if(c.freeDimensionOverrides)for(let[H,v]of Object.entries(c.freeDimensionOverrides)){if(typeof H!="string")throw new Error(`free dimension override name must be a string: ${H}`);if(typeof v!="number"||!Number.isInteger(v)||v<0)throw new Error(`free dimension override value must be a non-negative integer: ${v}`);let ne=Wr(H,u);i._OrtAddFreeDimensionOverride(s,ne,v)!==0&&Fr(`Can't set a free dimension override: ${H} - ${v}.`)}return c.extra!==void 0&&ci(c.extra,"",new WeakSet,(H,v)=>{let ne=Wr(H,u),re=Wr(v,u);i._OrtAddSessionConfigEntry(s,ne,re)!==0&&Fr(`Can't set a session config entry: ${H} - ${v}.`)}),[s,u]}catch(p){throw s!==0&&i._OrtReleaseSessionOptions(s),u.forEach(d=>i._free(d)),p}}}),co,di,Mi,Ti,Yi,fo,po,Xt=h(()=>{co=r=>{switch(r){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"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${r}`)}},di=r=>{switch(r){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 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${r}`)}},Mi=(r,i)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][r],u=typeof i=="number"?i:i.reduce((c,p)=>c*p,1);return s>0?Math.ceil(u*s):void 0},Ti=r=>{switch(r){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${r}`)}},Yi=r=>{switch(r){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: ${r}`)}},fo=r=>r==="float32"||r==="float16"||r==="int32"||r==="int64"||r==="uint32"||r==="uint8"||r==="bool",po=r=>{switch(r){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${r}`)}}}),Zi,Bo=h(()=>{ve(),Zi=async r=>{if(typeof r=="string"){let i=await fetch(r);if(!i.ok)throw new Error(`failed to load external data file: ${r}`);let s=i.headers.get("Content-Length"),u=s?parseInt(s,10):0;if(u<1073741824)return new Uint8Array(await i.arrayBuffer());{if(!i.body)throw new Error(`failed to load external data file: ${r}, no response body.`);let c=i.body.getReader(),p;try{p=new ArrayBuffer(u)}catch(b){if(b instanceof RangeError){let T=Math.ceil(u/65536);p=new WebAssembly.Memory({initial:T,maximum:T}).buffer}else throw b}let d=0;for(;;){let{done:b,value:T}=await c.read();if(b)break;let E=T.byteLength;new Uint8Array(p,d,E).set(T),d+=E}return new Uint8Array(p,0,u)}}else return r instanceof Blob?new Uint8Array(await r.arrayBuffer()):r instanceof Uint8Array?r:new Uint8Array(r)}}),No,ho,jo,Uo,mo,Vo,Br,Rn=h(()=>{Xt(),No=["V","I","W","E","F"],ho=(r,i)=>{console.log(`[${No[r]},${new Date().toISOString()}]${i}`)},mo=(r,i)=>{jo=r,Uo=i},Vo=(r,i)=>{let s=Yi(r),u=Yi(jo);s>=u&&ho(s,typeof i=="function"?i():i)},Br=(...r)=>{Uo&&Vo(...r)}}),Ue,W=h(()=>{Xt(),Ue=(r,i)=>new(Ti(i))(r)}),fe=h(()=>{}),Pe,ze,Oe,nt,xt,kt,Tt,At,Zt,Pr=h(()=>{Rn(),fe(),Pe=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),ze=[],Oe=r=>Math.ceil(r/16)*16,nt=r=>{for(let i=0;i<ze.length;i++){let s=ze[i];if(r<=s)return s}return Math.ceil(r/16)*16},xt=1,kt=()=>xt++,Tt=async(r,i,s,u)=>{let c=Oe(s),p=r.device.createBuffer({size:c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=r.getCommandEncoder();r.endComputePass(),d.copyBufferToBuffer(i,0,p,0,c),r.flush(),await p.mapAsync(GPUMapMode.READ);let b=p.getMappedRange();if(u){let T=u();return T.set(new Uint8Array(b,0,s)),T}else return new Uint8Array(b.slice(0,s))}finally{p.destroy()}},At=class{constructor(r){this.backend=r,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[i]of Pe)ze.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[])}upload(r,i){let s=i.buffer,u=i.byteOffset,c=i.byteLength,p=Oe(c),d=this.storageCache.get(r);if(!d)throw new Error("gpu data for uploading does not exist");if(d.originalSize!==c)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${c}`);let b=this.backend.device.createBuffer({mappedAtCreation:!0,size:p,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),T=b.getMappedRange();new Uint8Array(T).set(new Uint8Array(s,u,c)),b.unmap();let E=this.backend.getCommandEncoder();this.backend.endComputePass(),E.copyBufferToBuffer(b,0,d.gpuData.buffer,0,p),Br("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${r})`),this.buffersForUploadingPending.push(b)}memcpy(r,i){let s=this.storageCache.get(r);if(!s)throw new Error("source gpu data for memcpy does not exist");let u=this.storageCache.get(i);if(!u)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==u.originalSize)throw new Error("inconsistent source and destination gpu data size");let c=Oe(s.originalSize),p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(s.gpuData.buffer,0,u.gpuData.buffer,0,c)}registerExternalBuffer(r,i,s){let u;if(s){if(u=this.externalBuffers.get(s),u===void 0)throw new Error("previous buffer is not registered");if(r===s)return Br("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${u}, buffer is the same, skip.`),u;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(s)}else u=kt();return this.storageCache.set(u,{gpuData:{id:u,type:0,buffer:r},originalSize:i}),this.externalBuffers.set(r,u),Br("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${u}, registered.`),u}unregisterExternalBuffer(r){let i=this.externalBuffers.get(r);i!==void 0&&(this.storageCache.delete(i),this.externalBuffers.delete(r),Br("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${i}`))}create(r,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=nt(r),u,c=(i&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,p=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||p){let b=(c?this.freeBuffers:this.freeUniformBuffers).get(s);b?b.length>0?u=b.pop():u=this.backend.device.createBuffer({size:s,usage:i}):u=this.backend.device.createBuffer({size:s,usage:i})}else u=this.backend.device.createBuffer({size:s,usage:i});let d={id:kt(),type:0,buffer:u};return this.storageCache.set(d.id,{gpuData:d,originalSize:r}),Br("verbose",()=>`[WebGPU] GpuDataManager.create(size=${r}) => id=${d.id}`),d}get(r){var i;return(i=this.storageCache.get(r))==null?void 0:i.gpuData}release(r){let i=this.storageCache.get(r);if(!i)throw new Error("releasing data does not exist");return Br("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${i.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(i.gpuData.buffer),i.originalSize}async download(r,i){let s=this.storageCache.get(r);if(!s)throw new Error("data does not exist");await Tt(this.backend,s.gpuData.buffer,s.originalSize,i)}refreshPendingBuffers(){for(let r of this.buffersForUploadingPending)r.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let r of this.buffersPending){let i=Pe.get(r.size);if((r.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(r.size)||[];i===void 0||s.length>=i?r.destroy():s.push(r)}else if((r.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(r.size)||[];i===void 0||s.length>=i?r.destroy():s.push(r)}else r.destroy()}this.buffersPending=[]}else{let r=this.capturedPendingBuffers.get(this.backend.currentSessionId);r||(r=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,r));for(let i of this.buffersPending)r.push(i);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(r=>{r.forEach(i=>{i.destroy()})}),this.freeUniformBuffers.forEach(r=>{r.forEach(i=>{i.destroy()})}),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(r=>{r.forEach(i=>{i.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(r){let i=this.capturedPendingBuffers.get(r);i&&(i.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(r))}},Zt=(...r)=>new At(...r)}),rr,Gt,mr=h(()=>{rr=class{constructor(r){Object.assign(this,r)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(r=>`${this[r]}`).join(";")),this.key}},Gt=r=>new rr(r)}),kn,pn,st,qn,xr,an,$n,Yt=h(()=>{kn=class{static calcMatMulShape(r,i){return r[1]!==i[0]?void 0:[r[0],i[1]]}},pn=class{static calcShape(r,i,s=!1){let u=r.length,c=i.length;if(u===0)return i;if(c===0)return r;let p=Math.max(r.length,i.length),d=new Array(p);if(s){if(u<2||c<2)return;let b=kn.calcMatMulShape([r[u-2],r[u-1]],[i[c-2],i[c-1]]);if(b===void 0)return;[d[p-2],d[p-1]]=b}for(let b=s?3:1;b<=p;b++){let T=u-b<0?1:r[u-b],E=c-b<0?1:i[c-b];if(T!==E&&T>1&&E>1)return;let q=Math.max(T,E);if(T&&E)d[p-b]=Math.max(T,E);else{if(q>1)return;d[p-b]=0}}return d}static isValidBroadcast(r,i){let s=r.length,u=i.length;if(s>u)return!1;for(let c=1;c<=s;c++)if(r[s-c]!==1&&r[s-c]!==i[u-c])return!1;return!0}},st=class xh{static size(i){return xh.getSizeFromDimensionRange(i,0,i.length)}static convertShape(i,s=4){let u=i.length;if(u===0)return[];let c=new Array(u),p=u-1;for(;p>=0;){if(i[p]%s===0){c[p]=i[p]/s;break}if(s%i[p]!==0)throw new Error("cannot convert shape");c[p]=1,s/=i[p],p--}for(p--;p>=0;p--)c[p]=i[p];return c}static sizeFromDimension(i,s){if(s<0||s>i.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${i.length} dimensions.`);return xh.getSizeFromDimensionRange(i,s,i.length)}static sizeToDimension(i,s){if(s<0||s>i.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${i.length} dimensions.`);return xh.getSizeFromDimensionRange(i,0,s)}static getSizeFromDimensionRange(i,s,u){let c=1;for(let p=s;p<u;p++){if(i[p]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");c*=i[p]}return c}static computeStrides(i){let s=i.length;if(s===0)return[];if(s===1)return[1];let u=new Array(s);u[s-1]=1,u[s-2]=i[s-1];for(let c=s-3;c>=0;--c)u[c]=u[c+1]*i[c+1];return u}static normalizeAxis(i,s){if(i<-s&&i>=s)throw new Error("unsupported axis for this operation.");return i<0?i+s:i}static normalizeAxes(i,s){return i.map(u=>this.normalizeAxis(u,s??i.length))}static sortBasedOnPerm(i,s){return s?s.map(u=>i[u]):i.slice().reverse()}static padShape(i,s){let u=i.length;return i.map((c,p)=>c+s[p]+s[p+u])}static areEqual(i,s){return i.length!==s.length?!1:i.every((u,c)=>u===s[c])}},qn=class vf{static adjustPoolAttributes(i,s,u,c,p,d){if(!i&&u.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(i)for(let b=0;b<s.length-2;b++)b>=u.length?u.push(s[b+2]):u[b]=s[b+2];for(let b=0;b<u.length;b++)if(b<c.length){if(c[b]<0)throw new Error("strides should be greater than or equal to 1")}else c.push(1);for(let b=0;b<u.length;b++)if(b<p.length){if(p[b]<0)throw new Error("dilations should be greater than or equal to 1")}else p.push(1);for(let b=0;b<u.length*2;b++)if(b<d.length){if(d[b]<0)throw new Error("pad should be greater than or equal to 1")}else d.push(0);for(let b=0;b<u.length;b++){if(u[b]<=0)throw new Error("kernel shapes need to be greater than 0");if(d[b]>=u[b]||d[b+u.length]>=u[b])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(i,s,u,c,p,d,b){if(b){if(p.length!==2*(i.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==i.length-2)throw new Error("length of strides should be the length of data dimensions");if(c.length!==i.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let T=0;T<i.length-2;T++)vf.adjustPadAndReturnShape(i[T+(d?1:2)],s[T],u[T],c[T],p,T,T+i.length-2,b)}}static computePoolOutputShape(i,s,u,c,p,d,b){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let T=[s[0],s[1]];return vf.computeShapeHelper(i,s,T,u,c,p,d,b),T}static computeConvOutputShape(i,s,u,c,p,d,b){if(i.length<=0||s.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let T=[i[0],s[0]];return vf.computeShapeHelper(!1,i,T,u,c,p,d,b),T}static computeShapeHelper(i,s,u,c,p,d,b,T){if(i)for(let E=0;E<s.length-2;E++)u.push(1);else for(let E=0;E<s.length-2;E++)u.push(vf.adjustPadAndReturnShape(s[E+2],c[E],p[E],d[E],b,E,E+s.length-2,T))}static adjustPadAndReturnShape(i,s,u,c,p,d,b,T){let E=u*(c-1)+1;if(T&&T!=="NOTSET")switch(T){case"VALID":return p[d]=0,p[b]=0,Math.floor((i-E)/s+1);case"SAME_LOWER":case"SAME_UPPER":if(u!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let q=((i+s-1)/s-1)*s+c-i;return p[d]=Math.floor(T==="SAME_LOWER"?(q+1)/2:q/2),p[b]=q-p[d],Math.floor((i+q-c)/s+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((i+p[d]+p[b]-E)/s+1)}},xr=class{static getShapeOfGemmResult(r,i,s,u,c){if(r.length!==2||s.length!==2)throw new Error("shape need to be of size 2");let p,d,b;i?(p=r[1],d=r[0]):(p=r[0],d=r[1]);let T=-1;if(u?(b=s[0],T=1):(b=s[1],T=0),s[T]!==d)throw new Error("dimension mismatch");if(p<=0||b<=0||d<=0)throw new Error("invalid shape specified");if(c&&!pn.isValidBroadcast(c,[p,b]))throw new Error("gemm: invalid bias shape for broadcast");return[p,b,d]}},an=-34028234663852886e22,$n=34028234663852886e22}),Bn,gn,Tr,kr,Ct,wr,zr,Gr,Nn,Dt,Es,gt,Vt,da,fa,su,go,or=h(()=>{Xt(),Yt(),Bn=64,gn=(r,i)=>{if(i===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(r){case 10:return i>1?`vec${i}<f16>`:"f16";case 1:return i>1?`vec${i}<f32>`:"f32";case 6:return i>1?`vec${i}<i32>`:"i32";case 12:return i>1?`vec${i}<u32>`:"u32";case 7:if(i>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(i>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(i!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];default:throw new Error(`Unknown data type: ${r}`)}},Tr=(r,i=1)=>{let s=gn(r,i);return typeof s=="string"?s:s[0]},kr=(r,i=1)=>{let s=gn(r,i);return typeof s=="string"?s:s[1]},Ct=(...r)=>{let i=[];return r.forEach(s=>{s.length!==0&&i.push({type:12,data:s},{type:12,data:st.computeStrides(s)})}),i},wr=r=>r%4===0?4:r%2===0?2:1,zr=(r="f32",i,s="0")=>!i||i===1?`${r}(${s})`:`vec${i}<${r}>(${s})`,Gr=(r,i,s)=>r==="f32"?s:i===1?`f32(${s})`:`vec${i}<f32>(${s})`,Nn=(r,i)=>i===4?`(${r}.x + ${r}.y + ${r}.z + ${r}.w)`:i===2?`(${r}.x + ${r}.y)`:i===3?`(${r}.x + ${r}.y + ${r}.z)`:r,Dt=(r,i,s,u)=>r.startsWith("uniforms.")&&s>4?typeof i=="string"?u==="f16"?`${r}[(${i}) / 8][(${i}) % 8 / 4][(${i}) % 8 % 4]`:`${r}[(${i}) / 4][(${i}) % 4]`:u==="f16"?`${r}[${Math.floor(i/8)}][${Math.floor(i%8/4)}][${i%8%4}]`:`${r}[${Math.floor(i/4)}][${i%4}]`:s>1?`${r}[${i}]`:r,Es=(r,i,s,u,c)=>{let p=typeof s=="number",d=p?s:s.length,b=[...new Array(d).keys()],T=d<2?"u32":d<=4?`vec${d}<u32>`:`array<u32, ${d}>`,E=gn(i,c),q=typeof E=="string"?E:E[1],H=typeof E=="string"?E:E[0],v={indices:T,value:q,storage:H,tensor:i},ne=pt=>typeof pt=="string"?pt:`${pt}u`,re={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},ce=p?"uniforms.":"",_e=`${ce}${r}_shape`,be=`${ce}${r}_strides`,he="";for(let pt=0;pt<d-1;pt++)he+=` + let dim${pt} = current / ${Dt(be,pt,d)}; + let rest${pt} = current % ${Dt(be,pt,d)}; + indices[${pt}] = dim${pt}; + current = rest${pt}; + `;he+=`indices[${d-1}] = current;`;let Fe=d<2?"":` + fn o2i_${r}(offset: u32) -> ${v.indices} { + var indices: ${v.indices}; + var current = offset; + ${he} + return indices; + }`,xe=pt=>(re.offsetToIndices=!0,d<2?pt:`o2i_${r}(${pt})`),Ie=[];if(d>=2)for(let pt=d-1;pt>=0;pt--)Ie.push(`${Dt(be,pt,d)} * (indices[${pt}])`);let ct=d<2?"":` + fn i2o_${r}(indices: ${v.indices}) -> u32 { + return ${Ie.join("+")}; + }`,et=pt=>(re.indicesToOffset=!0,d<2?pt:`i2o_${r}(${pt})`),vt=(...pt)=>d===0?"0u":`${v.indices}(${pt.map(ne).join(",")})`,Ft=(pt,zt)=>d<2?`${pt}`:`${Dt(pt,zt,d)}`,Lt=(pt,zt,ir)=>d<2?`${pt}=${ir};`:`${Dt(pt,zt,d)}=${ir};`,pr={},ar=(pt,zt)=>{re.broadcastedIndicesToOffset=!0;let ir=`${zt.name}broadcastedIndicesTo${r}Offset`;if(ir in pr)return`${ir}(${pt})`;let Hr=[];for(let un=d-1;un>=0;un--){let xn=zt.indicesGet("outputIndices",un+zt.rank-d);Hr.push(`${Ft(be,un)} * (${xn} % ${Ft(_e,un)})`)}return pr[ir]=`fn ${ir}(outputIndices: ${zt.type.indices}) -> u32 { + return ${Hr.length>0?Hr.join("+"):"0u"}; + }`,`${ir}(${pt})`},nr=(pt,zt)=>(()=>{if(v.storage===v.value)return`${r}[${pt}]=${zt};`;if(v.storage==="vec2<u32>"&&v.value==="i32")return`${r}[${pt}]=vec2<u32>(u32(${zt}), select(0u, 0xFFFFFFFFu, ${zt} < 0));`;if(v.storage==="vec2<u32>"&&v.value==="u32")return`${r}[${pt}]=vec2<u32>(u32(${zt}), 0u);`;if(v.storage==="u32"&&v.value==="vec4<bool>")return`${r}[${pt}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${zt}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),yr=pt=>(()=>{if(v.storage===v.value)return`${r}[${pt}]`;if(v.storage==="vec2<u32>"&&v.value==="i32")return`i32(${r}[${pt}].x)`;if(v.storage==="vec2<u32>"&&v.value==="u32")return`u32(${r}[${pt}].x)`;if(v.storage==="u32"&&v.value==="vec4<bool>")return`vec4<bool>(bool(${r}[${pt}] & 0xFFu), bool(${r}[${pt}] & 0xFF00u), bool(${r}[${pt}] & 0xFF0000u), bool(${r}[${pt}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),qr=d<2?"":` + fn get_${r}ByIndices(indices: ${v.indices}) -> ${q} { + return ${yr(`i2o_${r}(indices)`)}; + }`,Sr=d<2?"":(()=>{let pt=b.map(ir=>`d${ir}: u32`).join(", "),zt=b.map(ir=>`d${ir}`).join(", ");return` + fn get_${r}(${pt}) -> ${q} { + return get_${r}ByIndices(${vt(zt)}); + }`})(),jr=(...pt)=>{if(pt.length!==d)throw new Error(`indices length must be ${d}`);let zt=pt.map(ne).join(",");return d===0?yr("0u"):d===1?yr(zt[0]):(re.get=!0,re.getByIndices=!0,re.indicesToOffset=!0,`get_${r}(${zt})`)},It=pt=>d<2?yr(pt):(re.getByIndices=!0,re.indicesToOffset=!0,`get_${r}ByIndices(${pt})`),tr=d<2?"":` + fn set_${r}ByIndices(indices: ${v.indices}, value: ${q}) { + ${nr(`i2o_${r}(indices)`,"value")} + }`,er=d<2?"":(()=>{let pt=b.map(ir=>`d${ir}: u32`).join(", "),zt=b.map(ir=>`d${ir}`).join(", ");return` + fn set_${r}(${pt}, value: ${q}) { + set_${r}ByIndices(${vt(zt)}, value); + }`})();return{impl:()=>{let pt=[],zt=!1;return re.offsetToIndices&&(pt.push(Fe),zt=!0),re.indicesToOffset&&(pt.push(ct),zt=!0),re.broadcastedIndicesToOffset&&(Object.values(pr).forEach(ir=>pt.push(ir)),zt=!0),re.set&&(pt.push(er),zt=!0),re.setByIndices&&(pt.push(tr),zt=!0),re.get&&(pt.push(Sr),zt=!0),re.getByIndices&&(pt.push(qr),zt=!0),!p&&zt&&pt.unshift(`const ${_e} = ${v.indices}(${s.join(",")});`,`const ${be} = ${v.indices}(${st.computeStrides(s).join(",")});`),pt.join(` +`)},type:v,offsetToIndices:xe,indicesToOffset:et,broadcastedIndicesToOffset:ar,indices:vt,indicesGet:Ft,indicesSet:Lt,set:(...pt)=>{if(pt.length!==d+1)throw new Error(`indices length must be ${d}`);let zt=pt[d];if(typeof zt!="string")throw new Error("value must be string");let ir=pt.slice(0,d).map(ne).join(",");return d===0?nr("0u",zt):d===1?nr(ir[0],zt):(re.set=!0,re.setByIndices=!0,re.indicesToOffset=!0,`set_${r}(${ir}, ${zt})`)},setByOffset:nr,setByIndices:(pt,zt)=>d<2?nr(pt,zt):(re.setByIndices=!0,re.indicesToOffset=!0,`set_${r}ByIndices(${pt}, ${zt});`),get:jr,getByOffset:yr,getByIndices:It,usage:u,name:r,strides:be,shape:_e,rank:d}},gt=(r,i,s,u=1)=>Es(r,i,s,"input",u),Vt=(r,i,s,u=1)=>Es(r,i,s,"output",u),da=(r,i,s,u=1)=>Es(r,i,s,"internal",u),fa=class{constructor(r,i){this.normalizedDispatchGroup=r,this.limits=i,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(r){return`if (global_idx >= ${typeof r=="number"?`${r}u`:r}) { return; }`}mainStart(r=Bn){let i=typeof r=="number"?r:r[0],s=typeof r=="number"?1:r[1],u=typeof r=="number"?1:r[2];if(i>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||u>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${i}, ${s}, ${u}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(i*s*u>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${i}, ${s}, ${u}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let c=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,p=c?`@builtin(global_invocation_id) global_id : vec3<u32>, + @builtin(workgroup_id) workgroup_id : vec3<u32>, + @builtin(local_invocation_id) local_id : vec3<u32>`:`@builtin(global_invocation_id) global_id : vec3<u32>, + @builtin(local_invocation_id) local_id : vec3<u32>, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3<u32>, + @builtin(num_workgroups) num_workgroups : vec3<u32>`,d=c?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${i*s*u}u + local_idx;`;return`@compute @workgroup_size(${i}, ${s}, ${u}) + fn main(${p}) { + ${d} + `}appendVariableUniforms(r){r.rank!==0&&(r.shape.startsWith("uniforms.")&&this.uniforms.push({name:r.shape.replace("uniforms.",""),type:"u32",length:r.rank}),r.strides.startsWith("uniforms.")&&this.uniforms.push({name:r.strides.replace("uniforms.",""),type:"u32",length:r.rank}))}declareVariable(r,i){if(r.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(r),this.appendVariableUniforms(r);let s=r.usage==="input"?"read":"read_write",u=r.type.storage;return`@group(0) @binding(${i}) var<storage, ${s}> ${r.name}: array<${u}>;`}declareVariables(...r){return r.map(i=>this.declareVariable(i,this.variableIndex++)).join(` +`)}registerInternalVariable(r){if(r.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(r),this.appendVariableUniforms(r)}registerInternalVariables(...r){return r.forEach(i=>this.registerInternalVariable(i)),this}registerUniform(r,i,s=1){return this.uniforms.push({name:r,type:i,length:s}),this}registerUniforms(r){return this.uniforms=this.uniforms.concat(r),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let r=[];for(let{name:i,type:s,length:u}of this.uniforms)if(u&&u>4)s==="f16"?r.push(`@align(16) ${i}:array<mat2x4<${s}>, ${Math.ceil(u/8)}>`):r.push(`${i}:array<vec4<${s}>, ${Math.ceil(u/4)}>`);else{let c=u==null||u===1?s:`vec${u}<${s}>`;r.push(`${i}:${c}`)}return` + struct Uniforms { ${r.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(r=>r.impl()).join(` +`)+this.internalVariables.map(r=>r.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let r=i=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(i)];return this.uniforms.map(i=>[r(i.type),i.length??1])}},su=(r,i)=>new fa(r,i),go=(r,i)=>{let s=r.length,u=[];for(let c=0;c<s;c++){let p=s-1-c,d=r[p]||1;(i[i.length-1-c]||1)>1&&d===1&&u.unshift(p)}return u}}),au,pa,Wo,lu,fi,uu,ha,_o=h(()=>{Xt(),Yt(),mr(),or(),au=r=>{if(!r||r.length!==1)throw new Error("Transpose requires 1 input.")},pa=(r,i)=>i&&i.length!==r?[...new Array(r).keys()].reverse():i,Wo=(r,i)=>st.sortBasedOnPerm(r,pa(r.length,i)),lu=(r,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let p=0;p<i;++p)c.push(s.indicesSet("a",r[p],`i[${p}]`));return c.push("return a;}"),c.join(` +`)},fi=(r,i)=>{let s=r.dataType,u=r.dims.length,c=pa(u,i),p=Wo(r.dims,c),d=Vt("output",s,p.length),b=gt("a",s,u),T;if(c.length===2&&c[0]===1&&c[1]===0){let E=d.type.value,q=[16,16,1];T=H=>` + ${H.registerUniform("output_size","u32").declareVariables(b,d)} + var<workgroup> tile : array<array<${E}, ${q[0]+1}>, ${q[0]}>; + ${H.mainStart(q)} + var x = workgroup_id.x * ${q[0]}u + local_id.x; + var y = workgroup_id.y * ${q[0]}u + local_id.y; + let width = uniforms.output_shape[0]; + let height = uniforms.output_shape[1]; + if (x < width && y < height) { + tile[local_id.y][local_id.x] = ${b.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${q[0]}u + local_id.x; + y = workgroup_id.x * ${q[0]}u + local_id.y; + if (x < height && y < width) { + ${d.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else T=E=>` + ${E.registerUniform("output_size","u32").declareVariables(b,d)} + + ${lu(c,u,b,d)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${d.setByOffset("global_idx",b.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:E=>{let q=st.size(p);return{outputs:[{dims:p,dataType:E[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:[{type:12,data:q},...Ct(E[0].dims,p)]}},getShaderSource:T}},uu=(r,i)=>{au(r.inputs),r.compute(fi(r.inputs[0],i.perm))},ha=r=>Gt({perm:r.perm})}),cu,du,fu,pu,ma,hu,mu,ga,gu,_u,Hn,yu,wu,_a,vu,bu,ya,xu,Mu,wa,Tu,ep=h(()=>{Xt(),Yt(),or(),Sa(),_o(),cu={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},du={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},fu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},pu={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ma=(r,i)=>{let s=[];for(let u=i-r;u<i;++u)s.push(u);return s},hu=(r,i)=>{let s=[],u=r.length;for(let p=0;p<u;p++)i.indexOf(p)===-1&&s.push(r[p]);let c=i.map(p=>r[p]);return[s,c]},mu=(r,i)=>{let s=r.length+i.length,u=[],c=0;for(let p=0;p<s;p++)i.indexOf(p)===-1?u.push(r[c++]):u.push(1);return u},ga=(r,i)=>{for(let s=0;s<r.length;++s)if(r[r.length-s-1]!==i-1-s)return!1;return!0},gu=(r,i)=>{let s=[];if(!ga(r,i)){for(let u=0;u<i;++u)r.indexOf(u)===-1&&s.push(u);r.forEach(u=>s.push(u))}return s},_u=(r,i,s,u,c,p,d)=>{let b=s[0].dims,T=st.size(p),E=st.size(d),q=gt("_A",s[0].dataType,b),H=Vt("output",c,p),v=32,ne=` + var<workgroup> aBestValues : array<f32, ${v}>; + `;return{name:r,shaderCache:i,getShaderSource:re=>` + ${re.registerUniform("reduceSize","u32").declareVariables(q,H)} + ${ne} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${re.mainStart(v)} + + let outputIndex = global_idx / ${v}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${fu[u]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${v}) { + let candidate = f32(${q.getByOffset("offset + k")}); + bestValue = ${cu[u]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${v}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${du[u]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${H.setByOffset("outputIndex",`${u==="mean"?`${H.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${H.type.storage}(${pu[u]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:p,dataType:c}],dispatchGroup:{x:T},programUniforms:[{type:12,data:E}]})}},Hn=(r,i,s,u)=>{let c=r.inputs.length===1?s:Ps(r.inputs,s),p=c.axes;p.length===0&&!c.noopWithEmptyAxes&&(p=r.inputs[0].dims.map((ne,re)=>re));let d=st.normalizeAxes(p,r.inputs[0].dims.length),b=d,T=r.inputs[0],E=gu(b,r.inputs[0].dims.length);E.length>0&&(T=r.compute(fi(r.inputs[0],E),{inputs:[0],outputs:[-1]})[0],b=ma(b.length,T.dims.length));let[q,H]=hu(T.dims,b),v=q;c.keepDims&&(v=mu(q,d)),r.compute(_u(i,{hint:c.cacheKey,inputDependencies:["type"]},[T],u,r.inputs[0].dataType,v,H),{inputs:[T]})},yu=(r,i)=>{Hn(r,"ReduceMeanShared",i,"mean")},wu=(r,i)=>{Hn(r,"ReduceL1Shared",i,"l1")},_a=(r,i)=>{Hn(r,"ReduceL2Shared",i,"l2")},vu=(r,i)=>{Hn(r,"ReduceLogSumExpShared",i,"logSumExp")},bu=(r,i)=>{Hn(r,"ReduceMaxShared",i,"max")},ya=(r,i)=>{Hn(r,"ReduceMinShared",i,"min")},xu=(r,i)=>{Hn(r,"ReduceProdShared",i,"prod")},Mu=(r,i)=>{Hn(r,"ReduceSumShared",i,"sum")},wa=(r,i)=>{Hn(r,"ReduceSumSquareShared",i,"sumSquare")},Tu=(r,i)=>{Hn(r,"ReduceLogSumShared",i,"logSum")}}),Kn,ku,Cs,Ps,ni,Su,va,Eu,Cu,ba,Pu,$u,xa,Au,Iu,Qn,Fu,zu,Ma,Ou,Du,Ta,Lu,Ru,ka,Bu,Sa=h(()=>{Xt(),Yt(),mr(),or(),ep(),Kn=r=>{if(!r||r.length===0||r.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(r.length===2&&r[1].dims.length!==1)throw new Error("Invalid axes input dims.")},ku=r=>["","",`var value = ${r.getByIndices("input_indices")};`,""],Cs=(r,i,s,u,c,p,d=!1,b=!1)=>{let T=[],E=s[0].dims,q=E.length,H=st.normalizeAxes(c,q),v=!b&&H.length===0;E.forEach((ce,_e)=>{v||H.indexOf(_e)>=0?d&&T.push(1):T.push(ce)});let ne=T.length,re=st.size(T);return{name:r,shaderCache:i,getShaderSource:ce=>{let _e=[],be=gt("_A",s[0].dataType,q),he=Vt("output",p,ne),Fe=u(be,he,H),xe=Fe[2];for(let Ie=0,ct=0;Ie<q;Ie++)v||H.indexOf(Ie)>=0?(d&&ct++,xe=`for(var j${Ie}: u32 = 0; j${Ie} < ${E[Ie]}; j${Ie}++) { + ${Fe[2].includes("last_index")?`let last_index = j${Ie};`:""} + ${be.indicesSet("input_indices",Ie,`j${Ie}`)} + ${xe} + }`):(_e.push(`${be.indicesSet("input_indices",Ie,he.indicesGet("output_indices",ct))};`),ct++);return` + + ${ce.registerUniform("output_size","u32").declareVariables(be,he)} + + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${be.type.indices}; + let output_indices = ${he.offsetToIndices("global_idx")}; + + ${_e.join(` +`)} + ${Fe[0]} // init ops for reduce max/min + ${Fe[1]} + ${xe} + ${Fe[3]} + ${Fe.length===4?he.setByOffset("global_idx","value"):Fe.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:T,dataType:p}],dispatchGroup:{x:Math.ceil(re/64)},programUniforms:[{type:12,data:re},...Ct(E,T)]})}},Ps=(r,i)=>{let s=[];return r[1].dims[0]>0&&r[1].getBigInt64Array().forEach(u=>s.push(Number(u))),Gt({axes:s,keepDims:i.keepDims,noopWithEmptyAxes:i.noopWithEmptyAxes})},ni=(r,i,s,u)=>{let c=r.inputs,p=c.length===1?s:Ps(c,s);r.compute(Cs(i,{hint:p.cacheKey,inputDependencies:["rank"]},[c[0]],p.noopWithEmptyAxes&&p.axes.length===0?ku:u,p.axes,c[0].dataType,p.keepDims,p.noopWithEmptyAxes),{inputs:[0]})},Su=(r,i)=>{Kn(r.inputs),ni(r,"ReduceLogSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},va=(r,i)=>{Kn(r.inputs),ni(r,"ReduceL1",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Eu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceL2",i,(s,u)=>[`var t = ${u.type.value}(0); var value = ${u.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Cu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceLogSumExp",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ba=(r,i)=>{Kn(r.inputs),ni(r,"ReduceMax",i,(s,u,c)=>{let p=[];for(let d=0;d<s.rank;d++)(c.indexOf(d)>=0||c.length===0)&&p.push(s.indicesSet("input_indices",d,0));return[`${p.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Pu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceMean",i,(s,u,c)=>{let p=1;for(let d=0;d<s.rank;d++)(c.indexOf(d)>=0||c.length===0)&&(p*=r.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${u.type.value}(sum / ${p});`]})},$u=(r,i)=>{Kn(r.inputs),ni(r,"ReduceMin",i,(s,u,c)=>{let p=[];for(let d=0;d<s.rank;d++)(c.indexOf(d)>=0||c.length===0)&&p.push(`input_indices[${d}] = 0;`);return[`${p.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},xa=(r,i)=>{Kn(r.inputs),ni(r,"ReduceProd",i,(s,u)=>[`var value = ${u.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Au=(r,i)=>{Kn(r.inputs),ni(r,"ReduceSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Iu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceSumSquare",i,(s,u)=>[`var t = ${u.type.value}(0); var value = ${u.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Qn=(r,i,s)=>{if(i.length===0)return s;let u=1,c=1;for(let p=0;p<i.length;p++)i.indexOf(p)===-1?u*=r[p]:c*=r[p];return c<32&&u>1024},Fu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Pu(r,i):yu(r,i)},zu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?va(r,i):wu(r,i)},Ma=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Eu(r,i):_a(r,i)},Ou=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Cu(r,i):vu(r,i)},Du=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ba(r,i):bu(r,i)},Ta=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?$u(r,i):ya(r,i)},Lu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?xa(r,i):xu(r,i)},Ru=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Au(r,i):Mu(r,i)},ka=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Iu(r,i):wa(r,i)},Bu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Su(r,i):Tu(r,i)}}),$s,Nu,ju,As,tp=h(()=>{Xt(),mr(),Sa(),$s=r=>{if(!r||r.length===0||r.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(r[0].dataType!==1)throw new Error("Invalid input type.")},Nu=(r,i)=>{$s(r.inputs);let s=(u,c,p)=>{let d=[];for(let b=0;b<u.rank;b++)(p.indexOf(b)>=0||p.length===0)&&d.push(`input_indices[${b}] = 0;`);return[`${d.join(` +`)}`,`var value = ${u.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${u.getByIndices("input_indices")} ${i.selectLastIndex>0?"<=":"<"} value) { + value = ${u.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",c.setByOffset("global_idx","best_index")]};r.compute(Cs("ArgMin",{hint:i.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},ju=(r,i)=>{$s(r.inputs);let s=(u,c,p)=>{let d=[];for(let b=0;b<u.rank;b++)(p.indexOf(b)>=0||p.length===0)&&d.push(`input_indices[${b}] = 0;`);return[`${d.join(` +`)}`,`var value = ${u.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${u.getByIndices("input_indices")} ${i.selectLastIndex>0?">=":">"} value) { + value = ${u.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",c.setByOffset("global_idx","best_index")]};r.compute(Cs("argMax",{hint:i.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},As=r=>Gt(r)}),Uu,Ea,Vu,Wu,yo,Gu,qu,Is=h(()=>{Xt(),Yt(),fe(),or(),Uu=(r,i)=>{let s=r[0],u=r[1],c=r[2],p=r[3],d=r[4],b=r[5];if(d&&b)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let T=s.dims[0],E=s.dims[1],q=s.dims[2];if(c.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(u.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(u.dims[0]!==q)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(c.dims[0]!==u.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let H=c.dims[0]/3,v=H,ne=v;if(i.qkvHiddenSizes.length>0){if(i.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let Fe of i.qkvHiddenSizes)if(Fe%i.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");H=i.qkvHiddenSizes[0],v=i.qkvHiddenSizes[1],ne=i.qkvHiddenSizes[2]}let re=E;if(H!==v)throw new Error("qkv_hidden_sizes first element should be same as the second");if(c.dims[0]!==H+v+ne)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let ce=0;if(d){if(v!==ne)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(d.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(d.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(d.dims[1]!==T)throw new Error('Input "past" second dimension must be batch_size');if(d.dims[2]!==i.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(d.dims[4]!==v/i.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');i.pastPresentShareBuffer||(ce=d.dims[3])}let _e=re+ce,be=-1,he=0;if(p)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");if(b){if(b.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(b.dims[0]!==T||b.dims[1]!==i.numHeads||b.dims[2]!==E||b.dims[3]!==_e)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:T,sequenceLength:E,pastSequenceLength:ce,kvSequenceLength:re,totalSequenceLength:_e,maxSequenceLength:be,inputHiddenSize:q,hiddenSize:H,vHiddenSize:ne,headSize:Math.floor(H/i.numHeads),vHeadSize:Math.floor(ne/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:he,scale:i.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ea=(r,i,s)=>{let u=wr(s),c=64,p=s/u;p<c&&(c=32);let d=Math.ceil(s/u/c),b=[{type:1,data:1/s},{type:12,data:p},{type:12,data:d}],T=Tr(r.dataType,u),E=kr(1,u),q=["type"],H=v=>{let ne=Vt("x",r.dataType,r.dims,u),re=kr(r.dataType),ce=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var<workgroup> thread_max: array<f32, ${c}>; + var<workgroup> thread_sum: array<f32, ${c}>; + ${v.registerUniforms(ce).declareVariables(ne)} + ${v.mainStart([c,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${c}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${E}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${E}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(u){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${u}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${c}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${E}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${E}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(u){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${u}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${c}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + x[offset + i] = ${ne.type.value}(${re}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${E}(x[offset + i]); + x[offset + i] = ${ne.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${T};${u}`,inputDependencies:q},getShaderSource:H,getRunData:()=>({outputs:[],dispatchGroup:{x:i},programUniforms:b})}},Vu=(r,i,s,u,c,p,d,b)=>{let T=b+p.kvSequenceLength,E=[p.batchSize,p.numHeads,p.sequenceLength,T],q=p.kvNumHeads===void 0&&r>1&&u,H=q?[p.batchSize,p.numHeads,T,p.headSize]:void 0,v=d.scale===0?1/Math.sqrt(p.headSize):d.scale,ne=wr(p.headSize),re=p.headSize/ne,ce=12,_e={x:Math.ceil(T/ce),y:Math.ceil(p.sequenceLength/ce),z:p.batchSize*p.numHeads},be=[{type:12,data:p.sequenceLength},{type:12,data:re},{type:12,data:T},{type:12,data:p.numHeads},{type:1,data:v},{type:12,data:b},{type:12,data:p.kvSequenceLength}],he=q&&u&&st.size(u.dims)>0,Fe=["type","type"];he&&Fe.push("type"),c&&Fe.push("type");let xe=[{dims:E,dataType:i.dataType,gpuDataType:0}];q&&xe.push({dims:H,dataType:i.dataType,gpuDataType:0});let Ie=ct=>{let et=gt("q",i.dataType,i.dims,ne),vt=gt("key",s.dataType,s.dims,ne),Ft=[et,vt];if(he){let yr=gt("past_key",u.dataType,u.dims,ne);Ft.push(yr)}c&&Ft.push(gt("attention_bias",c.dataType,c.dims));let Lt=Vt("output",i.dataType,E),pr=[Lt];q&&pr.push(Vt("present_key",i.dataType,H,ne));let ar=kr(1,ne),nr=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${ce}u; + + var<workgroup> tileQ: array<${et.type.storage}, ${ce*ce}>; + var<workgroup> tileK: array<${et.type.storage}, ${ce*ce}>; + ${ct.registerUniforms(nr).declareVariables(...Ft,...pr)} + ${ct.mainStart([ce,ce,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + ${he&&q?` + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; + let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` + let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} + ${q?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${ar}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${he&&q?` + if (n + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else { + tileK[idx] = + key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; + }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} + ${q?"present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];":""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${ar}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + let headOffset = headIdx * uniforms.M * uniforms.N; + if (global_id.y < uniforms.M && global_id.x < uniforms.N) { + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(ne){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${ne}`)}})()}; + output[outputIdx] = ${Lt.type.value} (sum * uniforms.alpha) + ${c?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${ne};${c!==void 0};${u!==void 0};${r}`,inputDependencies:Fe},getRunData:()=>({outputs:xe,dispatchGroup:_e,programUniforms:be}),getShaderSource:Ie}},Wu=(r,i,s,u,c,p)=>{let d=p+c.kvSequenceLength,b=c.nReps?c.nReps:1,T=c.vHiddenSize*b,E=c.kvNumHeads==null&&r>1&&u,q=E?[c.batchSize,c.numHeads,d,c.headSize]:void 0,H=[c.batchSize,c.sequenceLength,T],v=12,ne={x:Math.ceil(c.vHeadSize/v),y:Math.ceil(c.sequenceLength/v),z:c.batchSize*c.numHeads},re=[{type:12,data:c.sequenceLength},{type:12,data:d},{type:12,data:c.vHeadSize},{type:12,data:c.numHeads},{type:12,data:T},{type:12,data:p},{type:12,data:c.kvSequenceLength}],ce=E&&u&&st.size(u.dims)>0,_e=["type","type"];ce&&_e.push("type");let be=[{dims:H,dataType:i.dataType,gpuDataType:0}];E&&be.push({dims:q,dataType:i.dataType,gpuDataType:0});let he=Fe=>{let xe=gt("probs",i.dataType,i.dims),Ie=gt("v",s.dataType,s.dims),ct=[xe,Ie];ce&&ct.push(gt("past_value",u.dataType,u.dims));let et=[Vt("output",i.dataType,H)];E&&et.push(Vt("present_value",i.dataType,q));let vt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${v}u; + var<workgroup> tileQ: array<${xe.type.value}, ${v*v}>; + var<workgroup> tileK: array<${xe.type.value}, ${v*v}>; + ${Fe.registerUniforms(vt).declareVariables(...ct,...et)} + ${Fe.mainStart([v,v,1])} + let headIdx = workgroup_id.z; + let m = global_id.y; + let n = global_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + ${ce&&E?` + let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; + let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; + `:` + let offsetB = headIdx * uniforms.N * uniforms.K + n; + `} + ${E?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${xe.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${ce&&E?` + if (w + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else { + tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; + } + `:` + tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; + `} + ${E?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + let batchIdx = workgroup_id.z / uniforms.num_heads; + let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + currentBatchHeadNumber * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${u!==void 0};${r}`,inputDependencies:_e},getRunData:()=>({outputs:be,dispatchGroup:ne,programUniforms:re}),getShaderSource:he}},yo=(r,i,s,u,c,p,d,b,T,E,q)=>{let H=Math.min(r.outputCount,1+(d?1:0)+(b?1:0)),v=E.kvNumHeads!==void 0||H>1?E.pastSequenceLength:0,ne=v+E.kvSequenceLength,re=T&&st.size(T.dims)>0?T:void 0,ce=[i,s];E.kvNumHeads===void 0&&H>1&&d&&st.size(d.dims)>0&&ce.push(d),re&&ce.push(re);let _e=r.compute(Vu(H,i,s,d,re,E,q,v),{inputs:ce,outputs:E.kvNumHeads===void 0&&H>1?[-1,1]:[-1]})[0];r.compute(Ea(_e,E.batchSize*E.numHeads*E.sequenceLength,ne),{inputs:[_e],outputs:[]});let be=[_e,u];E.kvNumHeads===void 0&&H>1&&b&&st.size(b.dims)>0&&be.push(b),r.compute(Wu(H,_e,u,b,E,v),{inputs:be,outputs:E.kvNumHeads===void 0&&H>1?[0,2]:[0]})},Gu=(r,i)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.headSize],u=i.sequenceLength,c=i.inputHiddenSize,p=i.headSize,d=12,b={x:Math.ceil(i.headSize/d),y:Math.ceil(i.sequenceLength/d),z:i.batchSize*i.numHeads},T=[r.inputs[0],r.inputs[1],r.inputs[2]],E=[{type:12,data:u},{type:12,data:c},{type:12,data:p},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:i.hiddenSize},{type:12,data:i.hiddenSize+i.hiddenSize+i.vHiddenSize}],q=H=>{let v=Vt("output_q",T[0].dataType,s),ne=Vt("output_k",T[0].dataType,s),re=Vt("output_v",T[0].dataType,s),ce=gt("input",T[0].dataType,T[0].dims),_e=gt("weight",T[1].dataType,T[1].dims),be=gt("bias",T[2].dataType,T[2].dims),he=ce.type.storage,Fe=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${d}u; + var<workgroup> tileInput: array<${he}, ${d*d}>; + var<workgroup> tileWeightQ: array<${he}, ${d*d}>; + var<workgroup> tileWeightK: array<${he}, ${d*d}>; + var<workgroup> tileWeightV: array<${he}, ${d*d}>; + ${H.registerUniforms(Fe).declareVariables(ce,_e,be,v,ne,re)} + ${H.mainStart([d,d,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${he}(0); + var valueK = ${he}(0); + var valueV = ${he}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) { + let inputTileOffset = TILE_SIZE * local_id.y + k; + let weightTileOffset = TILE_SIZE * k + local_id.x; + valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset]; + valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset]; + valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset]; + } + + workgroupBarrier(); + } + + let headOffset = (m * uniforms.N + n) % uniforms.head_size; + valueQ += bias[headOffset + biasOffsetQ]; + valueK += bias[headOffset + biasOffsetK]; + valueV += bias[headOffset + biasOffsetV]; + + let offset = workgroup_id.z * uniforms.M * uniforms.N; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = offset + m * uniforms.N + n; + output_q[outputIdx] = valueQ; + output_k[outputIdx] = valueK; + output_v[outputIdx] = valueV; + } + }`};return r.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:s,dataType:r.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:r.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:r.inputs[0].dataType,gpuDataType:0}],dispatchGroup:b,programUniforms:E}),getShaderSource:q},{inputs:T,outputs:[-1,-1,-1]})},qu=(r,i)=>{let s=Uu(r.inputs,i),[u,c,p]=Gu(r,s);return yo(r,u,c,p,r.inputs[4],void 0,void 0,void 0,r.inputs[5],s,i)}}),Hu,Ku,Qu,Xu,Yu=h(()=>{Z(),Xt(),Yt(),mr(),or(),Hu=(r,i)=>{if(!r||r.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(u,c,p)=>{let d=c.length;if(d!==u.length)throw new Error(`${p}: num dimensions != ${d}`);c.forEach((b,T)=>{if(b!==u[T])throw new Error(`${p}: dim[${T}] do not match`)})};if(r[0].dims.length>1){let u=i.format==="NHWC"?i.spatial?r[0].dims.slice(-1):r[0].dims.slice(-1).concat(r[0].dims.slice(1,r[0].dims.length-1)):r[0].dims.slice(1,i.spatial?2:void 0);s(r[1].dims,u,"Invalid input scale"),s(r[2].dims,u,"Invalid input B"),s(r[3].dims,u,"Invalid input mean"),s(r[4].dims,u,"Invalid input var")}else s(r[1].dims,[1],"Invalid input scale"),s(r[2].dims,[1],"Invalid input B"),s(r[3].dims,[1],"Invalid input mean"),s(r[4].dims,[1],"Invalid input var")},Ku=(r,i)=>{let{epsilon:s,spatial:u,format:c}=i,p=r[0].dims,d=u?wr(p[p.length-1]):1,b=c==="NHWC"&&p.length>1?d:1,T=st.size(p)/d,E=u,q=E?p.length:p,H=gt("x",r[0].dataType,r[0].dims,d),v=gt("scale",r[1].dataType,r[1].dims,b),ne=gt("bias",r[2].dataType,r[2].dims,b),re=gt("inputMean",r[3].dataType,r[3].dims,b),ce=gt("inputVar",r[4].dataType,r[4].dims,b),_e=Vt("y",r[0].dataType,q,d),be=()=>{let Fe="";if(u)Fe=`let cOffset = ${p.length===1?"0u":c==="NHWC"?`outputIndices[${p.length-1}] / ${d}`:"outputIndices[1]"};`;else if(c==="NCHW")Fe=` + ${_e.indicesSet("outputIndices","0","0")} + let cOffset = ${_e.indicesToOffset("outputIndices")};`;else{Fe=`var cIndices = ${v.type.indices}(0); + cIndices[0] = outputIndices[${p.length-1}];`;for(let xe=1;xe<v.rank;xe++)Fe+=`cIndices[${xe}] = outputIndices[${xe}];`;Fe+=`let cOffset = ${v.indicesToOffset("cIndices")};`}return Fe},he=Fe=>` + const epsilon = ${s}; + ${Fe.registerUniform("outputSize","u32").declareVariables(H,v,ne,re,ce,_e)} + ${Fe.mainStart()} + ${Fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${_e.offsetToIndices(`global_idx * ${d}`)}; + ${be()} + let scale = ${v.getByOffset("cOffset")}; + let bias = ${ne.getByOffset("cOffset")}; + let inputMean = ${re.getByOffset("cOffset")}; + let inputVar = ${ce.getByOffset("cOffset")}; + let x = ${H.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${_e.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${i.epsilon}_${i.format}_${u}_${d}`,inputDependencies:E?["rank","type","type","type","type"]:void 0},getShaderSource:he,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:E?[{type:12,data:T},...Ct(p)]:[{type:12,data:T}]})}},Qu=r=>Gt(r),Xu=(r,i)=>{let{inputs:s,outputCount:u}=r,c=Qu({...i,outputCount:u});if(D.webgpu.validateInputContent&&Hu(s,c),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");r.compute(Ku(s,c))}}),Zu,Ju,Ca,rp=h(()=>{Yt(),or(),Zu=r=>{if(r[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(r[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(r[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(r[0].dims[2]!==r[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Ju=r=>{let i=r[0].dims,s=r[0].dims[2],u=st.size(i)/4,c=r[0].dataType,p=gt("input",c,i,4),d=gt("bias",c,[s],4),b=gt("residual",c,i,4),T=Vt("output",c,i,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:E=>` + const channels = ${s}u / 4; + ${E.declareVariables(p,d,b,T)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes(u)} + let value = ${p.getByOffset("global_idx")} + + ${d.getByOffset("global_idx % channels")} + ${b.getByOffset("global_idx")}; + ${T.setByOffset("global_idx","value")} + }`}},Ca=r=>{Zu(r.inputs),r.compute(Ju(r.inputs))}}),ec,vr,tc,rc,Pa,nc,ic,$a,oc,sc,Fs,ac,lc,uc,Aa,cc,wo,dc,zs,fc,Ia,pc,hc,mc,Fa,gc,_c,za,yc,wc,Oa,vc,bc,Da,xc,La,Ra,Ba,Na,Mc,Tc,ja,kc,Sc,Ec,Ua=h(()=>{Xt(),Yt(),mr(),or(),ec=(r,i,s,u,c,p)=>{let d=Math.ceil(i/4),b="";typeof c=="string"?b=`${c}(a)`:b=c("a");let T=gt("inputData",s,[d],4),E=Vt("outputData",u,[d],4);return` + ${r.registerUniform("vec_size","u32").declareVariables(T,E)} + + ${p??""} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${T.getByOffset("global_idx")}; + ${E.setByOffset("global_idx",b)} + }`},vr=(r,i,s,u,c,p=r.dataType)=>({name:i,shaderCache:{hint:c,inputDependencies:["type"]},getShaderSource:d=>ec(d,st.size(r.dims),r.dataType,p,s,u),getRunData:d=>({outputs:[{dims:r.dims,dataType:p}],dispatchGroup:{x:Math.ceil(st.size(d[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(st.size(r.dims)/4)}]})}),tc=r=>{r.compute(vr(r.inputs[0],"Abs","abs"))},rc=r=>{r.compute(vr(r.inputs[0],"Acos","acos"))},Pa=r=>{r.compute(vr(r.inputs[0],"Acosh","acosh"))},nc=r=>{r.compute(vr(r.inputs[0],"Asin","asin"))},ic=r=>{r.compute(vr(r.inputs[0],"Asinh","asinh"))},$a=r=>{r.compute(vr(r.inputs[0],"Atan","atan"))},oc=r=>{r.compute(vr(r.inputs[0],"Atanh","atanh"))},sc=r=>Gt(r),Fs=(r,i)=>{let s;switch(i.to){case 10:s="vec4<f16>";break;case 1:s="vec4<f32>";break;case 12:s="vec4<u32>";break;case 6:s="vec4<i32>";break;case 9:s="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${i.to}`)}r.compute(vr(r.inputs[0],"Cast",s,void 0,i.cacheKey,i.to))},ac=r=>{let i=r.length>=2&&r[1].data!==0?r[1].getFloat32Array()[0]:an,s=r.length>=3&&r[2].data!==0?r[2].getFloat32Array()[0]:$n;return Gt({min:i,max:s})},lc=(r,i)=>{let s=r.inputs.length===1?i:ac(r.inputs),u=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Clip",c=>`clamp(${c}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${u}> = vec4(${u}(${s.min})); + const clip_max_: vec4<${u}> = vec4(${u}(${s.max})); +`,s.cacheKey),{inputs:[0]})},uc=r=>{r.compute(vr(r.inputs[0],"Ceil","ceil"))},Aa=r=>{r.compute(vr(r.inputs[0],"Cos","cos"))},cc=r=>{r.compute(vr(r.inputs[0],"Cosh","cosh"))},wo=r=>Gt(r),dc=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Elu",u=>`elu_vf32(${u})`,` + const elu_alpha_ = ${s}(${i.alpha}); + + fn elu_f32(a: ${s}) -> ${s} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,i.cacheKey))},zs=(r="f32")=>` +const r0: ${r} = 0.3275911; +const r1: ${r} = 0.254829592; +const r2: ${r} = -0.284496736; +const r3: ${r} = 1.421413741; +const r4: ${r} = -1.453152027; +const r5: ${r} = 1.061405429; + +fn erf_vf32(v: vec4<${r}>) -> vec4<${r}> { + let absv = abs(v); + let x = 1.0 / (1.0 + r0 * absv); + return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); +}`,fc=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Erf",s=>`erf_vf32(${s})`,zs(i)))},Ia=r=>{r.compute(vr(r.inputs[0],"Exp","exp"))},pc=r=>{r.compute(vr(r.inputs[0],"Floor","floor"))},hc=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,zs(i)))},mc=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"LeakyRelu",u=>`select(leaky_relu_alpha_ * ${u}, ${u}, ${u} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${i.alpha});`,i.cacheKey))},Fa=r=>{r.compute(vr(r.inputs[0],"Not",i=>`!${i}`))},gc=r=>{r.compute(vr(r.inputs[0],"Neg",i=>`-${i}`))},_c=r=>{r.compute(vr(r.inputs[0],"Reciprocal",i=>`1.0/${i}`))},za=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Relu",s=>`select(vec4<${i}>(0.0), ${s}, ${s} > vec4<${i}>(0.0))`))},yc=r=>{r.compute(vr(r.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},wc=r=>Gt(r),Oa=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"HardSigmoid",u=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${i.alpha} * ${u} + vec4<${s}>(${i.beta})))`,void 0,i.cacheKey))},vc=r=>{r.compute(vr(r.inputs[0],"Sin","sin"))},bc=r=>{r.compute(vr(r.inputs[0],"Sinh","sinh"))},Da=r=>{r.compute(vr(r.inputs[0],"Sqrt","sqrt"))},xc=r=>{r.compute(vr(r.inputs[0],"Tan","tan"))},La=r=>`sign(${r}) * (1 - exp(-2 * abs(${r}))) / (1 + exp(-2 * abs(${r})))`,Ra=r=>{r.compute(vr(r.inputs[0],"Tanh",La))},Ba=(r="f32")=>` +const fast_gelu_a: ${r} = 0.5; +const fast_gelu_b: ${r} = 0.7978845608028654; +const fast_gelu_c: ${r} = 0.035677408136300125; + +fn tanh_v(v: vec4<${r}>) -> vec4<${r}> { + return ${La("v")}; +} +`,Na=r=>`(fast_gelu_a + fast_gelu_a * tanh_v(${r} * (fast_gelu_c * ${r} * ${r} + fast_gelu_b))) * ${r}`,Mc=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"FastGelu",Na,Ba(i),void 0,r.inputs[0].dataType))},Tc=(r,i)=>{let s=kr(r.inputs[0].dataType);return r.compute(vr(r.inputs[0],"ThresholdedRelu",u=>`select(vec4<${s}>(0.0), ${u}, ${u} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${i.alpha});`,i.cacheKey)),0},ja=r=>{r.compute(vr(r.inputs[0],"Log","log"))},kc=(r,i)=>` +const alpha = vec4<${r}>(${i}); +const one = ${r}(1.0); +const zero = ${r}(0.0); + +fn quick_gelu_impl(x: vec4<${r}>) -> vec4<${r}> { + let v = x *alpha; + var x1 : vec4<${r}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,Sc=r=>`quick_gelu_impl(${r})`,Ec=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"QuickGelu",Sc,kc(s,i.alpha),i.cacheKey,r.inputs[0].dataType))}}),Va,Cc,Pc,$c=h(()=>{Yt(),or(),Ua(),Va=r=>{if(r[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(r[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(r[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(r[0].dims[2]!==r[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Cc=r=>{let i=r[0].dims.slice();i[2]=i[2]/2;let s=gt("input",r[0].dataType,r[0].dims,4),u=gt("bias",r[0].dataType,[r[0].dims[2]],4),c=Vt("output",r[0].dataType,i,4),p=st.size(i)/4,d=Tr(r[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)}}),getShaderSource:b=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${r[0].dims[2]/4/2}u; + + ${b.declareVariables(s,u,c)} + + ${zs(d)} + + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes(p)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${c.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Pc=r=>{Va(r.inputs),r.compute(Cc(r.inputs))}}),Ac,Ic,Xn,Fc,zc,Wa,Oc,Dc,Lc,Rc,Bc,Nc,Ga,np=h(()=>{Xt(),Yt(),or(),Ac=(r,i,s,u,c,p,d,b,T,E,q,H)=>{let v,ne;typeof b=="string"?v=ne=(he,Fe)=>`${b}((${he}),(${Fe}))`:typeof b=="function"?v=ne=b:(v=b.scalar,ne=b.vector);let re=Vt("outputData",q,u.length,4),ce=gt("aData",T,i.length,4),_e=gt("bData",E,s.length,4),be;if(c)if(p){let he=st.size(i)===1,Fe=st.size(s)===1,xe=i.length>0&&i[i.length-1]%4===0,Ie=s.length>0&&s[s.length-1]%4===0;he||Fe?be=re.setByOffset("global_idx",ne(he?`${ce.type.value}(${ce.getByOffset("0")}.x)`:ce.getByOffset("global_idx"),Fe?`${_e.type.value}(${_e.getByOffset("0")}.x)`:_e.getByOffset("global_idx"))):be=` + let outputIndices = ${re.offsetToIndices("global_idx * 4u")}; + let offsetA = ${ce.broadcastedIndicesToOffset("outputIndices",re)}; + let offsetB = ${_e.broadcastedIndicesToOffset("outputIndices",re)}; + ${re.setByOffset("global_idx",ne(d||xe?ce.getByOffset("offsetA / 4u"):`${ce.type.value}(${ce.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||Ie?_e.getByOffset("offsetB / 4u"):`${_e.type.value}(${_e.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else be=re.setByOffset("global_idx",ne(ce.getByOffset("global_idx"),_e.getByOffset("global_idx")));else{if(!p)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let he=(Fe,xe,Ie="")=>{let ct=`aData[indexA${xe}][componentA${xe}]`,et=`bData[indexB${xe}][componentB${xe}]`;return` + let outputIndices${xe} = ${re.offsetToIndices(`global_idx * 4u + ${xe}u`)}; + let offsetA${xe} = ${ce.broadcastedIndicesToOffset(`outputIndices${xe}`,re)}; + let offsetB${xe} = ${_e.broadcastedIndicesToOffset(`outputIndices${xe}`,re)}; + let indexA${xe} = offsetA${xe} / 4u; + let indexB${xe} = offsetB${xe} / 4u; + let componentA${xe} = offsetA${xe} % 4u; + let componentB${xe} = offsetB${xe} % 4u; + ${Fe}[${xe}] = ${Ie}(${v(ct,et)}); + `};q===9?be=` + var data = vec4<u32>(0); + ${he("data",0,"u32")} + ${he("data",1,"u32")} + ${he("data",2,"u32")} + ${he("data",3,"u32")} + outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:be=` + ${he("outputData[global_idx]",0)} + ${he("outputData[global_idx]",1)} + ${he("outputData[global_idx]",2)} + ${he("outputData[global_idx]",3)} + `}return` + ${r.registerUniform("vec_size","u32").declareVariables(ce,_e,re)} + + ${H??""} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${be} + }`},Ic=(r,i,s,u,c,p,d=s.dataType)=>{let b=!st.areEqual(s.dims,u.dims),T=s.dims,E=st.size(s.dims),q=!1,H=!1,v=[b];if(b){let ne=pn.calcShape(s.dims,u.dims,!1);if(!ne)throw new Error("Can't perform binary op on the given tensors");T=ne,E=st.size(T);let re=st.size(s.dims)===1,ce=st.size(u.dims)===1,_e=s.dims.length>0&&s.dims[s.dims.length-1]%4===0,be=u.dims.length>0&&u.dims[u.dims.length-1]%4===0;v.push(re),v.push(ce),v.push(_e),v.push(be);let he=1;for(let Fe=1;Fe<T.length;Fe++){let xe=s.dims[s.dims.length-Fe]??1,Ie=u.dims[u.dims.length-Fe]??1;if(xe===Ie)he*=xe;else break}he%4===0?(H=!0,q=!0):(re||ce||_e||be)&&(q=!0)}else q=!0;return v.push(q),{name:r,shaderCache:{hint:i+v.map(ne=>ne.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:ne=>Ac(ne,s.dims,u.dims,T,q,b,H,c,s.dataType,u.dataType,d,p),getRunData:()=>({outputs:[{dims:T,dataType:d}],dispatchGroup:{x:Math.ceil(E/64/4)},programUniforms:[{type:12,data:Math.ceil(st.size(T)/4)},...Ct(s.dims,u.dims,T)]})}},Xn=(r,i,s,u,c,p)=>{r.compute(Ic(i,c??"",r.inputs[0],r.inputs[1],s,u,p))},Fc=r=>{Xn(r,"Add",(i,s)=>`${i}+${s}`)},zc=r=>{Xn(r,"Div",(i,s)=>`${i}/${s}`)},Wa=r=>{Xn(r,"Equal",{scalar:(i,s)=>`u32(${i}==${s})`,vector:(i,s)=>`vec4<u32>(${i}==${s})`},void 0,void 0,9)},Oc=r=>{Xn(r,"Mul",(i,s)=>`${i}*${s}`)},Dc=r=>{let i=gt("input",r.inputs[0].dataType,r.inputs[0].dims).type.value;Xn(r,"Pow",{scalar:(s,u)=>`pow_custom(${s},${u})`,vector:(s,u)=>`pow_vector_custom(${s},${u})`},` + fn pow_custom(a : ${i}, b : ${i}) -> ${i} { + if (b == ${i}(0.0)) { + return ${i}(1.0); + } else if (a < ${i}(0.0) && f32(b) != floor(f32(b))) { + return ${i}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${i}(1.0), round(f32(abs(b) % ${i}(2.0))) != 1.0) * ${i}(${i==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${i}>, b : vec4<${i}>) -> vec4<${i}> { + // TODO: implement vectorized pow + return vec4<${i}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Lc=r=>{Xn(r,"Sub",(i,s)=>`${i}-${s}`)},Rc=r=>{Xn(r,"Greater",{scalar:(i,s)=>`u32(${i}>${s})`,vector:(i,s)=>`vec4<u32>(${i}>${s})`},void 0,void 0,9)},Bc=r=>{Xn(r,"Less",{scalar:(i,s)=>`u32(${i}<${s})`,vector:(i,s)=>`vec4<u32>(${i}<${s})`},void 0,void 0,9)},Nc=r=>{Xn(r,"GreaterOrEqual",{scalar:(i,s)=>`u32(${i}>=${s})`,vector:(i,s)=>`vec4<u32>(${i}>=${s})`},void 0,void 0,9)},Ga=r=>{Xn(r,"LessOrEqual",{scalar:(i,s)=>`u32(${i}<=${s})`,vector:(i,s)=>`vec4<u32>(${i}<=${s})`},void 0,void 0,9)}}),jc,qa,Uc,Vc,Ni,Wc,ip=h(()=>{Xt(),Yt(),mr(),or(),jc=(r,i)=>{if(!r||r.length<1)throw new Error("too few inputs");let s=0,u=r[s],c=u.dataType,p=u.dims.length;r.forEach((d,b)=>{if(b!==s){if(d.dataType!==c)throw new Error("input tensors should be one type");if(d.dims.length!==p)throw new Error("input tensors should have the same shape");d.dims.forEach((T,E)=>{if(E!==i&&T!==u.dims[E])throw new Error("non concat dimensions must match")})}})},qa=(r,i)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array<u32, ${r}u>(${i}); + for (var i: u32 = 0u; i < ${r}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${r}u; + }`,Uc=(r,i)=>{let s=r.length,u=[];for(let c=0;c<s;++c){let p=i.setByOffset("global_idx",r[c].getByIndices("indices"));s===1?u.push(p):c===0?u.push(`if (inputIndex == ${c}u) { ${p} }`):c===s-1?u.push(`else { ${p} }`):u.push(`else if (inputIndex == ${c}) { ${p} }`)}return u.join(` +`)},Vc=(r,i,s,u)=>{let c=st.size(s),p=new Array(r.length),d=new Array(r.length),b=0,T=[],E=[],q=[{type:12,data:c}];for(let ce=0;ce<r.length;++ce)b+=r[ce].dims[i],p[ce]=b,E.push(r[ce].dims.length),d[ce]=gt(`input${ce}`,u,E[ce]),T.push("rank"),q.push({type:12,data:p[ce]});for(let ce=0;ce<r.length;++ce)q.push(...Ct(r[ce].dims));q.push(...Ct(s));let H=Vt("output",u,s.length),v=H.indicesGet("indices",i),ne=Array.from(Array(p.length).keys()).map(ce=>`uniforms.sizeInConcatAxis${ce}`).join(","),re=ce=>` + + ${(()=>{ce.registerUniform("outputSize","u32");for(let _e=0;_e<r.length;_e++)ce.registerUniform(`sizeInConcatAxis${_e}`,"u32");return ce.declareVariables(...d,H)})()} + + ${qa(p.length,ne)} + + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + var indices = ${H.offsetToIndices("global_idx")}; + + let inputIndex = calculateInputIndex(${v}); + if (inputIndex != 0u) { + let sizeInConcatAxis = array<u32, ${p.length}u>(${ne}); + ${v} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Uc(d,H)} + }`;return{name:"Concat",shaderCache:{hint:`${i}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:s,dataType:u}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:q}),getShaderSource:re}},Ni=(r,i)=>{let s=r.inputs,u=s[0].dims,c=st.normalizeAxis(i.axis,u.length);jc(s,c);let p=u.slice();p[c]=s.reduce((b,T)=>b+(T.dims.length>c?T.dims[c]:0),0);let d=s.filter(b=>st.size(b.dims)>0);r.compute(Vc(d,c,p,s[0].dataType),{inputs:d})},Wc=r=>Gt({axis:r.axis})}),ji,Ui,ki,Ha,Vi=h(()=>{Xt(),Yt(),ji=(r,i,s="f32")=>{switch(r.activation){case"Relu":return`value = max(value, ${i}(0.0));`;case"Sigmoid":return`value = (${i}(1.0) / (${i}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${i}(${s}(uniforms.clip_min)), ${i}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${i}(0.0), min(${i}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${i}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${r.activation}`)}},Ui=(r,i)=>{r.activation==="Clip"?i.push({type:1,data:r.clipMax},{type:1,data:r.clipMin}):r.activation==="HardSigmoid"?i.push({type:1,data:r.alpha},{type:1,data:r.beta}):r.activation==="LeakyRelu"&&i.push({type:1,data:r.alpha})},ki=(r,i)=>{r.activation==="Clip"?i.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):r.activation==="HardSigmoid"?i.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):r.activation==="LeakyRelu"&&i.push({name:"alpha",type:"f32"})},Ha=r=>{let i=(r==null?void 0:r.activation)||"";if(i==="HardSigmoid"){let[s,u]=(r==null?void 0:r.activation_params)||[.2,.5];return{activation:i,alpha:s,beta:u}}else if(i==="Clip"){let[s,u]=(r==null?void 0:r.activation_params)||[an,$n];return{activation:i,clipMax:u,clipMin:s}}else if(i==="LeakyRelu"){let[s]=(r==null?void 0:r.activation_params)||[.01];return{activation:i,alpha:s}}return{activation:i}}}),_n,Ka,vo=h(()=>{_n=(r,i)=>{switch(r){case 1:return i;case 2:return`vec2<${i}>`;case 3:return`vec3<${i}>`;case 4:return`vec4<${i}>`;default:throw new Error(`${r}-component is not supported.`)}},Ka=r=>` + ${r?"value = value + getBiasByOutputCoords(coords);":""} + `}),Qa,Gc=h(()=>{Qa=r=>` +fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 { + return dot(coords, vec4<i32>( + shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); +} +fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 { + return dot(coords, vec4<i32>( + i32(${r}.x), i32(${r}.y), i32(${r}.z), 1)); +} +`}),qc,Go,Os,Xa,Hc,Ds,Ls,Ya,Rs=h(()=>{Xt(),Yt(),or(),Vi(),vo(),qc=(r,i)=>r?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${i?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${i?", batchIndices":""}); + `,Go=(r,i)=>r?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${i===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${i===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${i===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Os=(r,i,s="f32",u,c=!1,p=32,d=!1,b=32)=>{let T=i[1]*r[1],E=i[0]*r[0],q=c?T:p,H=c?p:T,v=q/i[0],ne=p/i[1];if(!((c&&v===4&&r[1]===4||!c&&(v===3||v===4))&&q%i[0]===0&&p%i[1]===0&&r[0]===4))throw new Error(`If transposeA ${c} is true, innerElementSize ${v} and workPerThread[1] ${r[1]} must be 4. + Otherwise, innerElementSize ${v} must be 3 or 4. + tileAWidth ${q} must be divisible by workgroupSize[0]${i[0]}. tileInner ${p} must be divisible by workgroupSize[1] ${i[1]}. colPerThread ${r[0]} must be 4.`);return` +var<workgroup> mm_Asub: array<array<vec${v}<${s}>, ${q/v}>, ${H}>; +var<workgroup> mm_Bsub: array<array<vec4<${s}>, ${E/r[0]}>, ${p}>; + +const rowPerThread = ${r[1]}; +const colPerThread = ${r[0]}; +const innerElementSize = ${v}; +const tileInner = ${p}; + +@compute @workgroup_size(${i[0]}, ${i[1]}, ${i[2]}) +fn main(@builtin(local_invocation_id) localId : vec3<u32>, + @builtin(global_invocation_id) globalId : vec3<u32>, + @builtin(workgroup_id) workgroupId : vec3<u32>) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${d?"0":"i32(globalId.z)"}; + ${u?`let batchIndices = ${u.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${T}; + + let num_tiles = ${d?`${Math.ceil(b/p)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${b}`:"0"}; + + var acc: array<vec4<${s}>, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${ne}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${qc(c,u)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${ne}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${u?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${v===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Go(c,v)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Xa=(r,i)=>r?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${i?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${i?", batchIndices":""}); + `,Hc=r=>r?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ds=(r,i,s="f32",u,c=!1,p=32,d=!1,b=32,T=!1)=>{let E=r[1]*i[1],q=r[0]*i[0],H=c?E:p,v=c?p:E;if(!(v%i[1]===0&&H%i[0]===0&&p%i[1]===0))throw new Error(`tileAHight ${v} must be divisible by workgroupSize[1]${i[1]}, tileAWidth ${H} must be divisible by workgroupSize[0]${i[0]}, tileInner ${p} must be divisible by workgroupSize[1]${i[1]}`);let ne=v/i[1],re=H/i[0],ce=p/i[1],_e=T?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${E}; + let globalColStart = i32(workgroupId.x) * ${q}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${v}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${H}; inputCol = inputCol + ${i[0]}) { + ${Xa(c,u)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${q}; inputCol = inputCol + ${i[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${u?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${i[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${c?`mm_Asub[k][localRow + innerRow * ${i[1]}];`:`mm_Asub[localRow + innerRow * ${i[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${i[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${i[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${E}; + +let tileRowA = i32(localId.y) * ${ne}; +let tileColA = i32(localId.x) * ${re}; +let tileRowB = i32(localId.y) * ${ce}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${ne}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${re}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Xa(c,u)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${ce}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${u?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${Hc(c)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var<workgroup> mm_Asub : array<array<${s}, ${H}>, ${v}>; + var<workgroup> mm_Bsub : array<array<${s}, ${q}>, ${p}>; + const rowPerThread = ${r[1]}; + const colPerThread = ${r[0]}; + const tileInner = ${p}; + +@compute @workgroup_size(${i[0]}, ${i[1]}, ${i[2]}) +fn main(@builtin(local_invocation_id) localId : vec3<u32>, + @builtin(global_invocation_id) globalId : vec3<u32>, + @builtin(workgroup_id) workgroupId : vec3<u32>) { + let batch = ${d?"0":"i32(globalId.z)"}; + ${u?`let batchIndices = ${u.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${d?`${Math.ceil(b/p)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${b}`:"0"}; + + var acc : array<array<${s}, colPerThread>, rowPerThread>; + ${_e} + } +`},Ls=(r,i,s,u,c,p=!1)=>{let[d,b,T]=c,[E,q,H,v]=u,ne=go(d,T),re=go(b,T),ce=Tr(u[0].type.tensor),_e=()=>{let he=q.rank,Fe=E.rank,xe=`var aIndices: ${q.type.indices};`;for(let Ie=he-2-1,ct=Fe-1;Ie>=0;Ie--,ct--)xe+=` +aIndices[${Ie}] = ${Fe>1?`batchIndices[${ct}]`:"batchIndices"};`;return ne.forEach(Ie=>{xe+=` +aIndices[${Ie}] = 0;`}),xe+=` +aIndices[${he-2}] = u32(row); + aIndices[${he-1}] = u32(colIn);`,xe},be=()=>{let he=H.rank,Fe=E.rank,xe=`var bIndices: ${H.type.indices};`;for(let Ie=he-2-1,ct=Fe-1;Ie>=0;Ie--,ct--)xe+=` +bIndices[${Ie}] = ${Fe>1?`batchIndices[${ct}]`:"batchIndices"};`;return re.forEach(Ie=>{xe+=` +bIndices[${Ie}] = 0;`}),xe+=` +bIndices[${he-2}] = u32(row); + bIndices[${he-1}] = u32(colIn);`,xe};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${E.type.indices}) -> ${_n(r,ce)} { + var value = ${_n(r,ce)}(0.0); + let col = colIn * ${r}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${_e()} + value = ${q.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${E.type.indices}) -> ${_n(r,ce)} { + var value = ${_n(r,ce)}(0.0); + let col = colIn * ${r}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${be()} + value = ${H.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${_n(r,ce)}) { + let col = colIn * ${r}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3<i32>(batch, row, colIn); + ${i?`value = value + ${p?"bias[colIn]":`${_n(r,ce)}(bias[row])`};`:""} + ${s} + ${v.setByIndices("vec3<u32>(coords)","value")} + } + } + `},Ya=(r,i,s,u,c=!1)=>{let p=r[0].dims,d=r[1].dims,b=p.slice(0,-2),T=d.slice(0,-2),E=u?u.slice(0,-2):s.slice(0,-2),q=st.size(E),H=p[p.length-2],v=p[p.length-1],ne=d[d.length-1],re=v%4===0&&ne%4===0,ce=H<=8?[4,1,1]:[4,4,1],_e=[8,8,1],be=[Math.ceil(ne/_e[0]/ce[0]),Math.ceil(H/_e[1]/ce[1]),Math.ceil(q/_e[2]/ce[2])],he=re?4:1,Fe=[...b,H,v/he],xe=Fe.length,Ie=[...T,v,ne/he],ct=Ie.length,et=[q,H,ne/he],vt=[{type:6,data:H},{type:6,data:ne},{type:6,data:v}];Ui(i,vt),vt.push(...Ct(E,Fe,Ie));let Ft=["rank","rank"],Lt=r.length>2;Lt&&(vt.push(...Ct(r[2].dims)),Ft.push("rank")),vt.push(...Ct(et));let pr=ar=>{let nr=E.length,yr=da("batchDims",r[0].dataType,nr,1),qr=Tr(r[0].dataType),Sr=gt("a",r[0].dataType,xe,he),jr=gt("b",r[1].dataType,ct,he),It=Vt("result",r[0].dataType,et.length,he),tr=[Sr,jr];if(Lt){let Hr=c?he:1;tr.push(gt("bias",r[2].dataType,r[2].dims.length,Hr))}let er=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ki(i,er);let pt=Tr(It.type.tensor),zt=ji(i,It.type.value,pt),ir=Ls(he,Lt,zt,[yr,Sr,jr,It],[b,T,E],c);return` + ${ar.registerUniforms(er).registerInternalVariables(yr).declareVariables(...tr,It)} + ${ir} + ${re?Os(ce,_e,qr,yr):Ds(ce,_e,qr,yr)} + `};return{name:"MatMul",shaderCache:{hint:`${ce};${i.activation};${re};${c}`,inputDependencies:Ft},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:vt}),getShaderSource:pr}}}),Kc,op,sp=h(()=>{Xt(),Rn(),or(),Vi(),vo(),Gc(),Rs(),Kc=(r,i,s,u,c=!1,p,d=4,b=4,T=4,E="f32")=>{let q=Ft=>{switch(Ft){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${E}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Ft} is not supported.`)}},H=Ft=>{switch(Ft){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Ft} is not supported.`)}},v=r?` + let coord = vec4<i32>(batch, xRow, xCol, xCh); + `:` + let coord = vec4<i32>(batch, xCh, xRow, xCol); + `,ne=r?` + let coords = vec4<i32>( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4<i32>( + batch, + row, + col / outWidth, + col % outWidth); + `,re=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",ce=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",_e=r?"row":"col",be=r?"col":"row",he=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${_e} / outWidth; + let outCol = ${_e} % outWidth; + + let WRow = ${be} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${be} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${be} % inChannels; + var resData = ${_n(d,E)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${re} && xCol >= 0 && xCol < ${ce}) { + ${v} + let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape)); + ${q(d)} + } + return resData;`,Fe=r?i&&u?` + let col = colIn * ${d}; + ${he}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${he} + } + return ${_n(d,E)}(0.0);`:u&&s?` + let col = colIn * ${d}; + ${he}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${he} + } + return ${_n(d,E)}(0.0);`,xe=`${H(b)}`,Ie=_n(T,E),ct=_n(r?d:b,E),et=_n(r?b:d,E),vt=ji(p,Ie,E);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${ct} { + ${r?Fe:xe} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${et} { + ${r?xe:Fe} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Ie}) { + let col = colIn * ${T}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${ne} + ${Ka(c)} + ${vt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},op=(r,i,s,u,c,p,d,b)=>{let T=i.format==="NHWC",E=T?r[0].dims[3]:r[0].dims[1],q=s[0],H=T?s[2]:s[3],v=T?s[1]:s[2],ne=T?s[3]:s[1],re=T&&(E%4===0||E%3===0)&&ne%4===0,ce=T?ne:H*v,_e=T?H*v:ne,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],Fe=[Math.ceil(ce/be[0]/he[0]),Math.ceil(_e/be[1]/he[1]),Math.ceil(q/be[2]/he[2])];Br("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${Fe}`);let xe=re?T&&E%4!==0?3:4:1,Ie=be[1]*he[1],ct=be[0]*he[0],et=Math.max(be[0]*xe,be[1]),vt=u%Ie===0,Ft=c%ct===0,Lt=p%et===0,pr=re?[xe,4,4]:[1,1,1],ar=[{type:6,data:u},{type:6,data:c},{type:6,data:p},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];Ui(i,ar),ar.push(...Ct(r[0].dims,r[1].dims));let nr=["rank","rank"];d&&(ar.push(...Ct(r[2].dims)),nr.push("rank")),ar.push(...Ct(s));let yr=qr=>{let Sr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ki(i,Sr);let jr=re?4:1,It=Tr(r[0].dataType),tr=` + fn setOutputAtIndex(flatIndex : i32, value : ${re?`vec4<${It}>`:It}) { + result[flatIndex] = ${re?`vec4<${It}>`:It}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${re?`vec4<${It}>`:It}) { + let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${re?"/ 4":""}, value); + }`,er=gt("x",r[0].dataType,r[0].dims.length,xe===3?1:xe),pt=gt("w",r[1].dataType,r[1].dims.length,jr),zt=[er,pt],ir=Vt("result",r[0].dataType,s.length,jr);if(d){let Hr=gt("bias",r[2].dataType,r[2].dims.length,jr);zt.push(Hr),tr+=` + fn getBiasByOutputCoords(coords : vec4<i32>) -> ${re?`vec4<${It}>`:It} { + return bias[coords.${T?"w":"y"}${re?"/ 4":""}]; + }`}return` + ${Qa("uniforms.result_strides")} + //struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>, + // outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>, + // dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${qr.registerUniforms(Sr).declareVariables(...zt,ir)} + ${tr} + ${Kc(T,vt,Ft,Lt,d,i,pr[0],pr[1],pr[2],It)} + ${re?Os(he,be,It,void 0,!T,et):Ds(he,be,It,void 0,!T,et,!1,void 0,b)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${xe};${re};${vt};${Ft};${Lt};${Ie};${ct};${et}`,inputDependencies:nr},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Fe[0],y:Fe[1],z:Fe[2]},programUniforms:ar}),getShaderSource:yr}}}),Qc,Za,Si,Xc,Ja,Yc,Zc,Jc,el=h(()=>{Xt(),Rn(),Yt(),or(),Vi(),vo(),Qc=r=>{let i=1;for(let s=0;s<r.length;s++)i*=r[s];return i},Za=r=>typeof r=="number"?[r,r,r]:r,Si=(r,i)=>i<=1?r:r+(r-1)*(i-1),Xc=(r,i,s,u=1)=>{let c=Si(i,u);return Math.floor((r[0]*(s-1)-s+c)/2)},Ja=(r,i,s,u,c)=>{c==null&&(c=Xc(r,i[0],u[0]));let p=[0,0,0,s];for(let d=0;d<3;d++)r[d]+2*c>=i[d]&&(p[d]=Math.trunc((r[d]-i[d]+2*c)/u[d]+1));return p},Yc=(r,i,s,u,c,p,d,b,T,E)=>{let q,H,v,ne;if(r==="VALID"&&(r=0),typeof r=="number"){q={top:r,bottom:r,left:r,right:r,front:r,back:r};let re=Ja([i,s,u,1],[b,T,E],1,[c,p,d],r);H=re[0],v=re[1],ne=re[2]}else if(Array.isArray(r)){if(!r.every((ce,_e,be)=>ce===be[0]))throw Error(`Unsupported padding parameter: ${r}`);q={top:r[0],bottom:r[1],left:r[2],right:r[3],front:r[4],back:r[5]};let re=Ja([i,s,u,1],[b,T,E],1,[c,p,d],r[0]);H=re[0],v=re[1],ne=re[2]}else if(r==="SAME_UPPER"){H=Math.ceil(i/c),v=Math.ceil(s/p),ne=Math.ceil(u/d);let re=(H-1)*c+b-i,ce=(v-1)*p+T-s,_e=(ne-1)*d+E-u,be=Math.floor(re/2),he=re-be,Fe=Math.floor(ce/2),xe=ce-Fe,Ie=Math.floor(_e/2),ct=_e-Ie;q={top:Fe,bottom:xe,left:Ie,right:ct,front:be,back:he}}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:q,outDepth:H,outHeight:v,outWidth:ne}},Zc=(r,i,s,u,c,p=!1,d="channelsLast")=>{let b,T,E,q,H;if(d==="channelsLast")[b,T,E,q,H]=r;else if(d==="channelsFirst")[b,H,T,E,q]=r;else throw new Error(`Unknown dataFormat ${d}`);let[v,,ne,re,ce]=i,[_e,be,he]=Za(s),[Fe,xe,Ie]=Za(u),ct=Si(ne,Fe),et=Si(re,xe),vt=Si(ce,Ie),{padInfo:Ft,outDepth:Lt,outHeight:pr,outWidth:ar}=Yc(c,T,E,q,_e,be,he,ct,et,vt),nr=p?v*H:v,yr=[0,0,0,0,0];return d==="channelsFirst"?yr=[b,nr,Lt,pr,ar]:d==="channelsLast"&&(yr=[b,Lt,pr,ar,nr]),{batchSize:b,dataFormat:d,inDepth:T,inHeight:E,inWidth:q,inChannels:H,outDepth:Lt,outHeight:pr,outWidth:ar,outChannels:nr,padInfo:Ft,strideDepth:_e,strideHeight:be,strideWidth:he,filterDepth:ne,filterHeight:re,filterWidth:ce,effectiveFilterDepth:ct,effectiveFilterHeight:et,effectiveFilterWidth:vt,dilationDepth:Fe,dilationHeight:xe,dilationWidth:Ie,inShape:r,outShape:yr,filterShape:i}},Jc=(r,i,s,u,c,p)=>{let d=p==="channelsLast";d?r[0].dims[3]:r[0].dims[1];let b=[64,1,1],T={x:s.map((_e,be)=>be)},E=[Math.ceil(Qc(T.x.map(_e=>s[_e]))/b[0]),1,1];Br("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${E}`);let q=1,H=st.size(s),v=[{type:12,data:H},{type:12,data:u},{type:12,data:c},{type:12,data:i.strides},{type:12,data:i.dilations}];Ui(i,v),v.push(...Ct(r[0].dims,r[1].dims));let ne=["rank","rank"],re=r.length===3;re&&(v.push(...Ct(r[2].dims)),ne.push("rank")),v.push(...Ct(s));let ce=_e=>{let be=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:u.length},{name:"pads",type:"u32",length:c.length},{name:"strides",type:"u32",length:i.strides.length},{name:"dilations",type:"u32",length:i.dilations.length}];ki(i,be);let he=1,Fe=Tr(r[0].dataType),xe=gt("x",r[0].dataType,r[0].dims.length,q),Ie=gt("W",r[1].dataType,r[1].dims.length,he),ct=[xe,Ie],et=Vt("result",r[0].dataType,s.length,he),vt="";if(re){let pr=gt("bias",r[2].dataType,r[2].dims.length,he);ct.push(pr),vt+=` + fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${Fe} { + return bias[${d?Dt("coords",4,5):Dt("coords",1,5)}]; + }`}let Ft=_n(q,Fe),Lt=ji(i,Ft,Fe);return` + ${vt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array<u32, 5>(d0, d1, d2, d3, d4); + return ${xe.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array<u32, 5>(d0, d1, d2, d3, d4); + return ${Ie.getByIndices("aIndices")}; + } + ${_e.registerUniforms(be).declareVariables(...ct,et)} + ${_e.mainStart()} + ${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${et.offsetToIndices("global_idx")}; + let batch = ${Dt("coords",0,xe.rank)}; + let d2 = ${d?Dt("coords",xe.rank-1,xe.rank):Dt("coords",1,xe.rank)}; + let xFRCCorner = vec3<u32>(${d?Dt("coords",1,xe.rank):Dt("coords",2,xe.rank)}, + ${d?Dt("coords",2,xe.rank):Dt("coords",3,xe.rank)}, + ${d?Dt("coords",3,xe.rank):Dt("coords",4,xe.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${d?Dt("uniforms.x_shape",1,xe.rank):Dt("uniforms.x_shape",2,xe.rank)}; + let xShapeZ = ${d?Dt("uniforms.x_shape",2,xe.rank):Dt("uniforms.x_shape",3,xe.rank)}; + let xShapeW = ${d?Dt("uniforms.x_shape",3,xe.rank):Dt("uniforms.x_shape",4,xe.rank)}; + let xShapeU = ${d?Dt("uniforms.x_shape",4,xe.rank):Dt("uniforms.x_shape",1,xe.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${d?`let xValues = vec4<f32>( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4<f32>( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4<f32>( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${d?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${d?`let xValues = vec2<f32>( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2<f32>( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2<f32>( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${d?`let xValues = vec3<f32>( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3<f32>( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3<f32>( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${re?"value = value + getBiasByOutputCoords(coords)":""}; + ${Lt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${d};${q};${re}`,inputDependencies:ne},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:v}),getShaderSource:ce}}}),ed,td,ap=h(()=>{Xt(),Yt(),or(),sd(),Vi(),ed=(r,i,s)=>{let u=r.length>2,c=u?"value += b[output_channel];":"",p=r[0].dims,d=r[1].dims,b=d[0]/i.group,T=i.format==="NHWC",E=Bs(p,d,i.dilations,i.pads,i.strides,T),q=st.size(E),H=[{type:12,data:q},{type:12,data:i.dilations},{type:12,data:[i.strides[0],i.strides[1]]},{type:12,data:[i.pads[0],i.pads[1]]},{type:12,data:b}];Ui(i,H),H.push(...Ct(p,d));let v=["rank","rank"];u&&(H.push(...Ct(r[2].dims)),v.push("rank")),H.push(...Ct(E));let ne=re=>{let ce=Vt("output",r[0].dataType,E.length),_e=Tr(ce.type.tensor),be=ji(i,ce.type.value,_e),he=gt("x",r[0].dataType,p.length),Fe=gt("w",r[1].dataType,d.length),xe=[he,Fe];u&&xe.push(gt("b",r[2].dataType,r[2].dims.length));let Ie=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:i.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return ki(i,Ie),` + ${re.registerUniforms(Ie).declareVariables(...xe,ce)} + + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ce.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${T?3:1}]; + let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${T?1:2}], outputIndices[${T?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${ce.type.value} = ${ce.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[${T?1:2}]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[${T?2:3}]) { + continue; + } + + let xVal = ${T?he.get("batch","xHeight","xWidth","input_channel"):he.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Fe.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${c} + ${be} + ${ce.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:i.cacheKey,inputDependencies:v},getRunData:()=>({outputs:[{dims:s?s(E):E,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:H}),getShaderSource:ne}},td=(r,i,s)=>{let u=r.length>2,c=wr(s[3]),p=wr(s[2]),d=st.size(s)/c/p,b=[r[0].dims[0],r[0].dims[1],r[0].dims[2],r[0].dims[3]/c],T=[r[1].dims[0],r[1].dims[1],r[1].dims[2],r[1].dims[3]/c],E=[s[0],s[1],s[2],s[3]/c],q=[{type:12,data:d},{type:6,data:[i.strides[0],i.strides[1]]},{type:6,data:[i.pads[0],i.pads[1]]}];Ui(i,q),q.push(...Ct(b,T,E));let H=(p-1)*i.strides[1]+T[1],v=ne=>{let re=Vt("output",r[0].dataType,E.length,c),ce=Tr(re.type.tensor),_e=ji(i,re.type.value,ce),be=gt("x",r[0].dataType,b.length,c),he=gt("w",r[1].dataType,T.length,c),Fe=[be,he];u&&Fe.push(gt("b",r[2].dataType,r[2].dims,c));let xe=u?"value += b[output_channel];":"",Ie=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ki(i,Ie),` + ${ne.registerUniforms(Ie).declareVariables(...Fe,re)} + ${ne.mainStart()} + ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${p}u; + let col = (index1 % width1) * ${p}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${be.type.value}, ${H}>; + var values: array<${re.type.value}, ${p}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${T[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${H}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${be.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${be.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${T[1]}; w_width++) { + let w_val = ${he.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${p}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${p}u; i++) { + var value = values[i]; + ${xe} + ${_e} + ${re.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${c};${p};${H};${T[0]};${T[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:q}),getShaderSource:v}}}),tl,rd,nd,rl=h(()=>{Xt(),Yt(),Rs(),or(),Vi(),tl=(r,i,s,u,c=!1)=>{let p=r[0].dims,d=r[1].dims,b=p[p.length-2],T=d[d.length-1],E=p[p.length-1],q=wr(T),H=wr(E),v=wr(b),ne=st.size(s)/q/v,re=r.length>2,ce=u?u.slice(0,-2):s.slice(0,-2),_e=[st.size(ce),b,T],be=[{type:12,data:ne},{type:12,data:b},{type:12,data:T},{type:12,data:E}];Ui(i,be),be.push(...Ct(ce,p,d)),re&&be.push(...Ct(r[2].dims)),be.push(...Ct(_e));let he=Fe=>{let xe=da("batch_dims",r[0].dataType,ce.length),Ie=gt("a",r[0].dataType,p.length,H),ct=gt("b",r[1].dataType,d.length,q),et=Vt("output",r[0].dataType,_e.length,q),vt=Tr(et.type.tensor),Ft=ji(i,et.type.value,vt),Lt=[Ie,ct],pr="";if(re){let tr=c?q:1;Lt.push(gt("bias",r[2].dataType,r[2].dims.length,tr)),pr=`${c?`value += bias[col / ${tr}];`:`value += ${et.type.value}(bias[row + i]);`}`}let ar=p.slice(0,-2),nr=d.slice(0,-2),yr=go(ar,ce),qr=go(nr,ce),Sr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ki(i,Sr);let jr=(tr,er)=>{let pt=tr.rank,zt=tr.name;if(pt===2)return`var ${zt}_indices = ${tr.type.indices}(0u, 0u);`;let ir=xe.rank,Hr=`var ${zt}_indices: ${tr.type.indices};`;for(let un=pt-2-1,xn=ir-1;un>=0;un--,xn--)Hr+=` +${zt}_indices[${un}] = ${ir>1?`batch_indices[${xn}]`:"batch_indices"};`;return er.forEach(un=>{Hr+=` +${zt}_indices[${un}] = 0;`}),Hr+=`${zt}_indices[${pt-2}] = 0u; + ${zt}_indices[${pt-1}] = 0u;`,Hr},It=()=>{let tr=`var a_data: ${Ie.type.value};`;for(let er=0;er<H;er++)tr+=` + let b_data${er} = b[(b_offset + (k + ${er}) * uniforms.N + col) / ${q}];`;for(let er=0;er<v;er++){tr+=`a_data = a[(a_offset + (row + ${er}) * uniforms.K + k) / ${H}];`;for(let pt=0;pt<H;pt++)tr+=` + values[${er}] = fma(${ct.type.value}(a_data${H===1?"":`[${pt}]`}), b_data${pt}, values[${er}]); +`}return tr};return` + ${Fe.registerUniforms(Sr).registerInternalVariables(xe).declareVariables(...Lt,et)} + ${Fe.mainStart()} + ${Fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let col = (global_idx % (uniforms.N / ${q})) * ${q}; + var index1 = global_idx / (uniforms.N / ${q}); + let stride1 = uniforms.M / ${v}; + let row = (index1 % stride1) * ${v}; + let batch = index1 / stride1; + + ${s.length===2?"":`let batch_indices = ${xe.offsetToIndices("batch")};`} + ${jr(Ie,yr)} + let a_offset = ${Ie.indicesToOffset("a_indices")}; + ${jr(ct,qr)} + let b_offset = ${ct.indicesToOffset("b_indices")}; + var values: array<${et.type.value}, ${v}>; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${H}) { + ${It()} + } + for (var i = 0u; i < ${v}u; i++) { + var value = values[i]; + ${pr} + ${Ft} + let cur_indices = ${et.type.indices}(batch, row + i, col); + let offset = ${et.indicesToOffset("cur_indices")}; + ${et.setByOffset(`offset / ${q}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${i.activation};${q};${H};${v};${c}`,inputDependencies:re?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(ne/64)},programUniforms:be}),getShaderSource:he}},rd=r=>{if(!r||r.length!==2)throw new Error("MatMul requires 2 inputs.");if(r[0].dims[r[0].dims.length-1]!==r[1].dims[r[1].dims.length-2])throw new Error("shared dimension does not match.")},nd=r=>{rd(r.inputs);let i=pn.calcShape(r.inputs[0].dims,r.inputs[1].dims,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let s=i[i.length-1],u=r.inputs[0].dims[r.inputs[0].dims.length-1];s<8&&u<8?r.compute(tl(r.inputs,{activation:""},i)):r.compute(Ya(r.inputs,{activation:""},i))}}),Bs,Ns,nl,js,il,ol,id,od,qo,sd=h(()=>{Yt(),sp(),el(),Rs(),ap(),Vi(),rl(),_o(),Bs=(r,i,s,u,c,p)=>{let d=r[0],b=r.slice(p?1:2,p?3:4),T=b.length,E=i[0],q=i.slice(2).map((v,ne)=>v+(v-1)*(s[ne]-1)),H=b.map((v,ne)=>v+u[ne]+u[ne+T]).map((v,ne)=>Math.floor((v-q[ne]+c[ne])/c[ne]));return H.splice(0,0,d),H.splice(p?3:1,0,E),H},Ns=[2,3,1,0],nl=(r,i)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length>5)throw new Error("greater than 5D is not supported");if(r[0].dims.length!==r[1].dims.length)throw new Error("filter does not have same dimension as input");let s=r[0].dims[i.format==="NHWC"?r[0].dims.length-1:1],u=r[1].dims[1]*i.group;if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(r.length===3&&(r[2].dims.length!==1||r[1].dims[0]!==r[2].dims[0]))throw new Error("invalid bias");let c=r[0].dims.length-2;if(i.dilations.length!==c)throw new Error(`dilations should be ${c}D`);if(i.strides.length!==c)throw new Error(`strides should be ${c}D`);if(i.pads.length!==c*2)throw new Error(`pads should be ${c*2}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape")},js=(r,i)=>{let s=r.kernelShape.slice();for(let p=2;p<i[1].dims.length;++p)s[p-2]===0&&(s[p-2]=i[1].dims[p]);let u=r.pads.slice();qn.adjustPadsBasedOnAutoPad(i[0].dims,r.strides,r.dilations,s,u,r.format==="NHWC",r.autoPad);let c=Object.assign({},r);return Object.assign(c,{kernelShape:s,pads:u}),c},il=r=>{let i=Ha(r),s=r.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],c=r.dilations,p=r.group,d=r.kernel_shape,b=r.pads,T=r.strides,E=r.w_is_const();return{autoPad:u,format:s,dilations:c,group:p,kernelShape:d,pads:b,strides:T,wIsConst:E,...i,cacheKey:`${r.format};${i.activation};`}},ol=(r,i,s)=>{let u=js(s,i),c=s.format==="NHWC";if(s.group!==1){if(!r.adapterInfo.isArchitecture("ampere")&&c&&i[1].dims[0]===s.group&&i[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1){let ct=Bs(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),et=r.kernelCustomData.wT??r.compute(fi(i[1],Ns),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=et);let vt=[i[0],et];i.length===3&&vt.push(i[2]),r.compute(td(vt,u,ct),{inputs:vt})}else r.compute(ed(i,u));return}let p=i.length===3,d=i[0].dims[c?1:2],b=i[0].dims[c?2:3],T=i[0].dims[c?3:1],E=i[1].dims[2],q=i[1].dims[3],H=Bs(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),v=H[c?1:2],ne=H[c?2:3],re=H[c?3:1],ce=c&&E===d&&q===b&&s.pads[0]===0&&s.pads[1]===0;if(ce||E===1&&q===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let ct=H[0],et,vt,Ft,Lt=[];if(c){let nr=r.kernelCustomData.wT??r.compute(fi(i[1],Ns),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=nr),ce){let yr=d*b*T;et=i[0].reshape([1,ct,yr]),vt=nr.reshape([1,yr,re]),Ft=[1,ct,re]}else et=i[0].reshape([ct,d*b,T]),vt=nr.reshape([1,T,re]),Ft=[ct,v*ne,re];Lt.push(et),Lt.push(vt)}else et=i[0].reshape([ct,T,d*b]),vt=i[1].reshape([1,re,T]),Ft=[ct,re,v*ne],Lt.push(vt),Lt.push(et);p&&Lt.push(i[2]);let pr=Ft[2],ar=Lt[0].dims[Lt[0].dims.length-1];pr<8&&ar<8?r.compute(tl(Lt,u,H,Ft,c),{inputs:Lt}):r.compute(Ya(Lt,u,H,Ft,c),{inputs:Lt});return}let _e=!0,be=r.kernelCustomData.wT??r.compute(fi(i[1],Ns),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=be);let he=[i[0],be];p&&he.push(i[2]);let Fe=c?v*ne:re,xe=c?re:v*ne,Ie=E*q*T;r.compute(op(he,u,H,Fe,xe,Ie,p,_e),{inputs:he})},id=(r,i)=>{let s=i.format==="NHWC",u=[r.inputs[0].reshape(s?[r.inputs[0].dims[0],1,r.inputs[0].dims[1],r.inputs[0].dims[2]]:[r.inputs[0].dims[0],r.inputs[0].dims[1],1,r.inputs[0].dims[2]]),r.inputs[1].reshape([r.inputs[1].dims[0],r.inputs[1].dims[1],1,r.inputs[1].dims[2]])];r.inputs.length===3&&u.push(r.inputs[2]);let c=[0,i.pads[0],0,i.pads[1]],p=[1].concat(i.strides),d=[1].concat(i.dilations),b=[1].concat(i.kernelShape),T=js({...i,pads:c,strides:p,dilations:d,kernelShape:b},u);r.compute(ed(u,T,E=>s?[E[0],E[2],E[3]]:[E[0],E[1],E[3]]))},od=(r,i,s)=>{let u=s.format==="NHWC"?"channelsLast":"channelsFirst",c=js(s,i),p=s.autoPad==="NOTSET"?s.pads:s.autoPad,d=Zc(i[0].dims,i[1].dims,s.strides,s.dilations,p,!1,u);r.compute(Jc(i,c,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],u))},qo=(r,i)=>{nl(r.inputs,i),r.inputs[0].dims.length===3?id(r,i):r.inputs[0].dims.length===5?od(r,r.inputs,i):ol(r,r.inputs,i)}}),ad,ld,lp=h(()=>{Xt(),Rn(),or(),Vi(),vo(),Gc(),Rs(),ad=(r,i=!1,s,u,c=4)=>{let p=_e=>{switch(_e){case 1:return"return w[getIndexFromCoords4D(coord, vec4<i32>(uniforms.w_shape))];";case 4:return` + let coord1 = vec4<i32>(coordX, coordY, col + 1, rowInner); + let coord2 = vec4<i32>(coordX, coordY, col + 2, rowInner); + let coord3 = vec4<i32>(coordX, coordY, col + 3, rowInner); + let v0 = w[getIndexFromCoords4D(coord, vec4<i32>(uniforms.w_shape))]; + let v1 = w[getIndexFromCoords4D(coord1, vec4<i32>(uniforms.w_shape))]; + let v2 = w[getIndexFromCoords4D(coord2, vec4<i32>(uniforms.w_shape))]; + let v3 = w[getIndexFromCoords4D(coord3, vec4<i32>(uniforms.w_shape))]; + return ${u}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${_e} is not supported.`)}},d=r?` + let coord = vec4<i32>(batch, iXR, iXC, xCh); + `:` + let coord = vec4<i32>(batch, xCh, iXR, iXC); + `,b=r?` + let coords = vec4<i32>( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4<i32>( + batch, + row, + col / outWidth, + col % outWidth); + `,T=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",E=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",q=r?"row":"col",H=r?"col":"row",v=` + let inChannels = ${r?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${q} / outWidth; + let outCol = ${q} % outWidth; + + let WRow = ${H} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${H} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${T}) || fract(xR) > 0.0) { + return ${u}(0.0); + } + if (xC < 0.0 || xC >= f32(${E}) || fract(xC) > 0.0) { + return ${u}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${H} % inChannels; + ${d} + return x[getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape))/${c}];`,ne=r?` + let col = colIn * ${c}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${v} + } + return ${u}(0.0);`:` + let col = colIn * ${c}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${v} + } + return ${u}(0.0);`,re=` + let col = colIn * ${c}; + let inChannels = ${r?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${r?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4<i32>(coordX, coordY, col, rowInner); + ${p(c)} + } + return ${u}(0.0); + `,ce=ji(s,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${u} { + ${r?ne:re} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${u} { + ${r?re:ne} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${u}) { + let col = colIn * ${c}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${b} + ${Ka(i)} + ${ce} + result[getIndexFromCoords4D(coords, vec4<i32>(uniforms.result_shape))/${c}] = value; + } + }`},ld=(r,i,s,u,c,p,d,b)=>{let T=i.format==="NHWC",E=T?r[0].dims[3]:r[0].dims[1],q=s[0],H=T?s[2]:s[3],v=T?s[1]:s[2],ne=T?s[3]:s[1],re=T&&E%4===0&&E%3&&ne%4===0,ce=T?ne:H*v,_e=T?H*v:ne,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],Fe=[Math.ceil(ce/be[0]/he[0]),Math.ceil(_e/be[1]/he[1]),Math.ceil(q/be[2]/he[2])];Br("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${Fe}`);let xe=re?4:1,Ie=Math.max(be[0]*xe,be[1]),ct=re?4:1,et=[i.kernelShape[T?1:2],i.kernelShape[T?2:3]],vt=[et[0]+(i.dilations[0]<=1?0:(et[0]-1)*(i.dilations[0]-1)),et[1]+(i.dilations[1]<=1?0:(et[1]-1)*(i.dilations[1]-1))],Ft=[vt[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),vt[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Lt=[{type:6,data:u},{type:6,data:c},{type:6,data:p},{type:6,data:i.strides},{type:6,data:i.dilations},{type:6,data:et},{type:6,data:Ft}];Ui(i,Lt),Lt.push(...Ct(r[0].dims,r[1].dims));let pr=["rank","rank"];d&&(Lt.push(...Ct(r[2].dims)),pr.push("rank")),Lt.push(...Ct(s));let ar=nr=>{let yr=gt("x",r[0].dataType,r[0].dims.length,ct),qr=gt("w",r[1].dataType,r[1].dims.length,1),Sr=Vt("result",r[0].dataType,s.length,ct),jr=[yr,qr],It="";if(d){let pt=gt("bias",r[2].dataType,r[2].dims.length,ct);jr.push(pt),It+=` + fn getBiasByOutputCoords(coords : vec4<i32>) -> ${pt.type.value} { + return bias[coords.${T?"w":"y"}${re?"/ 4":""}]; + }`}let tr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:et.length},{name:"pads",type:"i32",length:Ft.length}];ki(i,tr);let er=Tr(r[0].dataType,1);if(er!=="f16"&&er!=="f32")throw new Error(`elemType ${er} is not supported.`);return` + ${Qa("uniforms.result_strides")} + ${nr.registerUniforms(tr).declareVariables(...jr,Sr)}; + ${It} + ${ad(T,d,i,yr.type.value,xe)} + ${re?Os(he,be,er,void 0,!T,Ie):Ds(he,be,er,void 0,!T,Ie,!1,void 0,b)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${i.cacheKey};${he};${be};${re}`,inputDependencies:pr},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Fe[0],y:Fe[1],z:Fe[2]},programUniforms:Lt}),getShaderSource:ar}}}),sl,Ho,fm=h(()=>{Xt(),Rn(),Yt(),or(),sl=(r,i,s,u,c,p=!1,d,b,T=!1)=>{let E=T?1:2,q=T?2:3,H=T?3:1,v=p?2:1,ne=` + fn setOutputAtIndex(flatIndex : u32, value : ${p?`vec4<${d}>`:d}) { + result[flatIndex] = ${p?`vec4<${d}>`:d}(value); + }`;u&&(ne+=` + fn getBiasByOutputCoords(coords : vec4<u32>) -> ${p?`vec4<${d}>`:d} { + return bias[coords.${T?"w":"y"}${p?"/ 4":""}]; + }`);let re=p?4:1,ce=gt("W",i[1].dataType,i[1].dims.length,re),_e=gt("Dy",i[0].dataType,i[0].dims.length,re),be=[_e,ce];u&&be.push(gt("bias",i[2].dataType,[s[H]].length,re));let he=Vt("result",i[0].dataType,s.length,re),Fe=`{ + let batch: u32 = ${c?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${c?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${c?"global_id.y":"workgroup_id.y"} * ${v}; + let d1: u32 = ${c?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2<i32>(i32(r), i32(c)) - vec2<i32>(uniforms.pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array<vec4<${d}>, ${v}>; + for (var i = 0; i < ${v}; i++) { + dotProd[i] = vec4<${d}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${d}(dyCorner.x) + ${d}(wR)) / ${d}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${d}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${d}(dyCorner.y) + ${d}(wC)) / ${d}(uniforms.strides.y); + let dyC2 = (${d}(dyCorner.y) + 1.0 + ${d}(wC)) / ${d}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${d}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${d}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${_e.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${_e.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${H}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${_e.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${_e.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${v}; i = i + 1) { + let value = dotProd[i] + ${u?"bias[c+i]":`vec4<${d}>(0.0)`}; + ${he.set("batch","r","c + i","d1","value")}; + } + }`,xe=` + let outputIndices = ${he.offsetToIndices("global_idx")}; + let batch = ${he.indicesGet("outputIndices",0)}; + let d1 = ${he.indicesGet("outputIndices",H)}; + let r = ${he.indicesGet("outputIndices",E)}; + let c = ${he.indicesGet("outputIndices",q)}; + let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${d}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${d}(dyRCorner) + ${d}(wR)) / ${d}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${d}(uniforms.Dy_shape[${E}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${d}(dyCCorner) + ${d}(wC)) / ${d}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${d}(uniforms.Dy_shape[${q}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${T?_e.get("batch","idyR","idyC","inputChannel"):_e.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${ce.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${u?"bias[d1]":`${d}(0.0)`}; + ${he.setByOffset("global_idx","value")}; + `;return` + ${r.registerUniforms(b).declareVariables(...be,he)} + ${ne} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${p?Fe:xe}}`},Ho=(r,i,s)=>{let u=r.length>2,c=i.outputShape,p=st.size(c),d=[Math.ceil(p/64),1,1];Br("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${d}`);let b=i.format==="NHWC",T=["rank","rank"],E=[i.strides[0],i.strides[1]],q=[i.kernelShape[b?1:2],i.kernelShape[b?2:3]],H=[i.dilations[0],i.dilations[1]],v=[q[0]+(i.dilations[0]<=1?0:(i.kernelShape[b?1:2]-1)*(i.dilations[0]-1)),q[1]+(i.dilations[1]<=1?0:(i.kernelShape[b?2:3]-1)*(i.dilations[1]-1))],ne=[v[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),v[1]-1-Math.floor(i.pads[1]+i.pads[3])/2],re=!1,ce=i.group,_e=r[1].dims,be=_e[0]/ce,he=_e[1],Fe=[{type:12,data:p},{type:12,data:E},{type:12,data:q},{type:12,data:H},{type:12,data:v},{type:6,data:ne},{type:12,data:be},{type:12,data:he},...Ct(r[0].dims,r[1].dims)];u&&(Fe.push(...Ct(r[2].dims)),T.push("rank")),Fe.push(...Ct(c));let xe=d[1]===1&&d[2]===1,Ie=ct=>{let et=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:E.length},{name:"filter_dims",type:"u32",length:q.length},{name:"dilations",type:"u32",length:q.length},{name:"effective_filter_dims",type:"u32",length:v.length},{name:"pads",type:"i32",length:ne.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],vt=Tr(r[0].dataType);return`${sl(ct,r,c,u,xe,re,vt,et,b)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${i.cacheKey};`,inputDependencies:T},getRunData:()=>({dispatchGroup:{x:d[0],y:d[1],z:d[2]},outputs:[{dims:s?s(c):c,dataType:r[0].dataType}],programUniforms:Fe}),getShaderSource:Ie}}}),ud,cd,al,ll,dd,ul,fd,pd,cl,up,pm=h(()=>{lp(),fm(),Vi(),_o(),ud=(r,i,s,u,c,p)=>(r-1)*i+s+(u-1)*c+1-p,cd=(r,i,s,u,c)=>{let p=Math.floor(r/2);i==="SAME_UPPER"?(s[u]=p,s[c]=r-p):i==="SAME_LOWER"&&(s[u]=r-p,s[c]=p)},al=(r,i,s,u,c,p,d,b,T,E)=>{let q=r.length-2,H=E.length===0;if(T.length===0)for(let re=0;re<q;++re)T.push(0);let v=r[0],ne=i[b?3:1]*c;for(let re=0,ce=r.length-q-(b?1:0);re<q;++re,++ce){let _e=r[ce],be=H?_e*d[re]:E[re],he=ud(_e,d[re],p[re],i[ce],s[re],be);cd(he,u,p,re,re+q),H&&E.push(d[re]*(_e-1)+T[re]+(i[ce]-1)*s[re]+1-p[re]-p[re+q])}E.splice(0,0,v),E.splice(b?3:1,0,ne)},ll=(r,i)=>{let s=r.kernelShape.slice();if(r.kernelShape.length===0||r.kernelShape.reduce((H,v)=>H*v,1)===0){s.length=0;for(let H=2;H<i[1].dims.length;++H)s.push(i[1].dims[H])}let u=r.format==="NHWC";s.splice(0,0,i[1].dims[0]),s.splice(u?3:1,0,i[1].dims[1]);let c=r.pads.slice(),p=r.outputShape.slice(),d=r.outputPadding.slice(),b=i[0].dims,T=r.dilations.slice();if(T.reduce((H,v)=>H+v,0)===0){let H=i[0].dims.length-2;T=new Array(H).fill(1)}let E=r.strides.slice();if(E.reduce((H,v)=>H+v,0)===0){let H=i[0].dims.length-2;E=new Array(H).fill(1)}al(b,s,T,r.autoPad,r.group,c,E,u,d,p);let q=Object.assign({},r);return Object.assign(q,{kernelShape:s,pads:c,outputPadding:d,outputShape:p,dilations:T,strides:E}),q},dd=r=>{let i=Ha(r),s=r.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof r.autoPad>"u"?0:r.autoPad],c=r.dilations,p=r.group,d=r.kernelShape,b=r.pads,T=r.strides,E=r.wIsConst(),q=r.outputPadding,H=r.outputShape;return{autoPad:u,format:s,dilations:c,group:p,kernelShape:d,outputPadding:q,outputShape:H,pads:b,strides:T,wIsConst:E,...i,cacheKey:`${r.format};${i.activation};`}},ul=(r,i)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length!==4&&r[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(r[0].dims.length!==r[1].dims.length)throw new Error("filter does not have same dimension as input");let s=r[0].dims[i.format==="NHWC"?r[0].dims.length-1:1],u=r[1].dims[0];if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let c=r[1].dims[1]*i.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==c))throw new Error("invalid bias");let p=r[0].dims.length-2;if(i.dilations.reduce((d,b)=>d+b,0)>0&&i.dilations.length!==p)throw new Error(`dilations should be ${p}D`);if(i.strides.reduce((d,b)=>d+b,0)>0&&i.strides.length!==p)throw new Error(`strides should be ${p}D`);if(i.pads.reduce((d,b)=>d+b,0)>0&&i.pads.length!==p*2)throw new Error(`pads should be ${p*2}D`);if(i.outputPadding.length!==p&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${p}D`);if(i.kernelShape.reduce((d,b)=>d+b,0)>0&&i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==r[0].dims.length-2)throw new Error("invalid output shape")},fd=[2,3,1,0],pd=(r,i,s)=>{let u=ll(s,i),c=s.format==="NHWC",p=u.outputShape,d=p[c?3:1],b=i[0].dims[c?3:1];if(u.group!==1||d===1&&b===1){r.compute(Ho(i,u));return}let T=p[c?1:2],E=p[c?2:3],q=i[1].dims[2],H=i[1].dims[3],v=c?T*E:d,ne=c?d:T*E,re=q*H*b,ce=!0,_e=r.kernelCustomData.wT??r.compute(fi(i[1],fd),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=_e);let be=[i[0],_e],he=i.length===3;he&&(!c&&i[2].dims.length===1?be.push(i[2].reshape([i[2].dims[0],1,1])):be.push(i[2])),r.compute(ld(be,u,p,v,ne,re,he,ce),{inputs:be})},cl=(r,i)=>{let s=i.format==="NHWC",u=[r.inputs[0].reshape(s?[r.inputs[0].dims[0],1,r.inputs[0].dims[1],r.inputs[0].dims[2]]:[r.inputs[0].dims[0],r.inputs[0].dims[1],1,r.inputs[0].dims[2]]),r.inputs[1].reshape([r.inputs[1].dims[0],r.inputs[1].dims[1],1,r.inputs[1].dims[2]])];r.inputs.length===3&&u.push(r.inputs[2]);let c=i.kernelShape;(c.length===0||c[0]===0)&&(c=[r.inputs[1].dims[2]]);let p=i.dilations;(p.length===0||p[0]===0)&&(p=[1]);let d=i.strides;(d.length===0||d[0]===0)&&(d=[1]);let b=i.pads;b.length===0&&(b=[0,0]),b=[0,b[0],0,b[1]],d=[1].concat(d),p=[1].concat(p),c=[1].concat(c);let T=ll({...i,pads:b,strides:d,dilations:p,kernelShape:c},u);r.compute(Ho(u,T,E=>s?[E[0],E[2],E[3]]:[E[0],E[1],E[3]]))},up=(r,i)=>{ul(r.inputs,i),r.inputs[0].dims.length===3?cl(r,i):pd(r,r.inputs,i)}}),dl,fl,hd,cp=h(()=>{Xt(),Yt(),mr(),or(),dl=(r,i,s,u)=>{let c=st.size(i),p=i.length,d=gt("input",r,p),b=Vt("output",r,p),T=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),E=st.normalizeAxis(T,p),q=H=>{let v=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,ne=Dt("uniforms.input_shape","uniforms.axis",p),re=u.reverse?v+(u.exclusive?" + 1":""):"0",ce=u.reverse?ne:v+(u.exclusive?"":" + 1");return` + ${H.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,b)} + ${H.mainStart()} + ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${b.offsetToIndices("global_idx")}; + var sum = ${b.type.value}(0); + let first : i32 = ${re}; + let last : i32 = ${ce}; + for (var i : i32 = first; i < last; i++) { + ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${d.getByIndices("inputIndices")}; + } + ${b.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:r}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:12,data:E},...Ct(i,i)]}),getShaderSource:q}},fl=(r,i)=>{let s=r.inputs[0].dims,u=r.inputs[0].dataType,c=r.inputs[1];r.compute(dl(u,s,c,i),{inputs:[0]})},hd=r=>{let i=r.exclusive===1,s=r.reverse===1;return Gt({exclusive:i,reverse:s})}}),pl,md,gd,hl,_d,dp=h(()=>{Xt(),Yt(),mr(),or(),pl=r=>{if(!r||r.length!==1)throw new Error("DepthToSpace requires 1 input.");if(r[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},md=(r,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let p=0;p<i;++p)c.push(s.indicesSet("a",r[p],`i[${p}]`));return c.push("return a;}"),c.join(` +`)},gd=(r,i)=>{let s,u,c,p,d,b,T=i.format==="NHWC",E=i.blocksize,q=i.mode==="DCR";T?([s,u,c,p]=r.dims,d=q?[s,u,c,E,E,p/E**2]:[s,u,c,p/E**2,E,E],b=q?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,u,c,p]=[r.dims[0],r.dims[2],r.dims[3],r.dims[1]],d=q?[s,E,E,p/E**2,u,c]:[s,p/E**2,E,E,u,c],b=q?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let H=r.reshape(d),v=H.dims.length,ne=r.dataType,re=gt("a",ne,v),ce=Vt("output",ne,v),_e=be=>` + ${be.registerUniform("output_size","u32").declareVariables(re,ce)} + + ${md(b,v,re,ce)} + + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${ce.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${ce.setByOffset("global_idx",re.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${r.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:be=>{let he=T?[s,u*E,c*E,p/E**2]:[s,p/E**2,u*E,c*E],Fe=st.size(he),xe=H.dims,Ie=st.sortBasedOnPerm(xe,b);return{outputs:[{dims:he,dataType:be[0].dataType}],dispatchGroup:{x:Math.ceil(Fe/64)},programUniforms:[{type:12,data:Fe},...Ct(xe,Ie)]}},getShaderSource:_e}},hl=(r,i)=>{pl(r.inputs),r.compute(gd(r.inputs[0],i))},_d=r=>Gt({blocksize:r.blocksize,mode:r.mode,format:r.format})}),Ko,Qo,ml,Or,fp,pp,hp,Us,yd,wd,vd,mp=h(()=>{Xt(),Yt(),mr(),or(),Ko="[a-zA-Z]|\\.\\.\\.",Qo="("+Ko+")+",ml="^"+Qo+"$",Or="("+Qo+",)*"+Qo,fp="^"+Or+"$",pp=class{constructor(r=-1){this.symbolToIndices=new Map,this.inputIndex=r}addSymbol(r,i){let s=this.symbolToIndices.get(r);s===void 0?s=[i]:s.push(i),this.symbolToIndices.set(r,s)}},hp=class{constructor(r,i){var c;this.equation=i,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,u]=i.includes("->")?i.split("->",2):[i,""];if(!s.match(RegExp(fp)))throw new Error("Invalid LHS term");if(s.split(",").forEach((p,d)=>{let b=r[d].dims.slice();if(!p.match(RegExp(ml)))throw new Error("Invalid LHS term");let T=this.processTerm(p,!0,b,d);this.lhs.push(T)}),u==="")u+=[...this.symbolToInfo.entries()].filter(([p,d])=>d.count===1||p==="...").map(([p])=>p).join("");else if(!u.match(RegExp(Qo)))throw new Error("Invalid RHS");(c=u.match(RegExp(Ko,"g")))==null||c.forEach(p=>{if(p==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(p);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(u,!1,this.outputDims)}addSymbol(r,i,s){let u=this.symbolToInfo.get(r);if(u!==void 0){if(u.dimValue!==i&&u.count!==1)throw new Error("Dimension mismatch");u.count++,u.inputIndices.push(s)}else u={count:1,dimValue:i,inputIndices:[s]};this.symbolToInfo.set(r,u)}processTerm(r,i,s,u=-1){let c=s.length,p=!1,d=[],b=0;if(!r.match(RegExp(ml))&&!i&&r!=="")throw new Error("Invalid LHS term");let T=r.match(RegExp(Ko,"g")),E=new pp(u);return T==null||T.forEach((q,H)=>{if(q==="..."){if(p)throw new Error("Only one ellipsis is allowed per input term");p=!0;let v=c-T.length+1;if(v<0)throw new Error("Ellipsis out of bounds");if(d=s.slice(b,b+v),this.hasEllipsis){if(this.ellipsisDims.length!==d.length||this.ellipsisDims.toString()!==d.toString())throw new Error("Ellipsis dimensions mismatch")}else if(i)this.hasEllipsis=!0,this.ellipsisDims=d;else throw new Error("Ellipsis must be specified in the LHS");for(let ne=0;ne<d.length;ne++){let re=String.fromCharCode(48+ne);E.addSymbol(re,H+ne),this.addSymbol(re,s[b++],u)}}else E.addSymbol(q,H+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(q,s[b++],u)}),E}},Us=r=>r+"_max",yd=(r,i,s,u)=>{let c=r.map(E=>E.length).map((E,q)=>gt(`input${q}`,i,E)),p=st.size(u),d=Vt("output",i,u.length),b=[...s.symbolToInfo.keys()].filter(E=>!s.rhs.symbolToIndices.has(E)),T=E=>{let q=[],H="var prod = 1.0;",v="var sum = 0.0;",ne="sum += prod;",re=[],ce=[],_e=[],be=[],he=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((xe,Ie)=>{var ct;if(s.rhs.symbolToIndices.has(Ie)){let et=(ct=s.rhs.symbolToIndices.get(Ie))==null?void 0:ct[0];et!==void 0&&s.lhs.forEach((vt,Ft)=>{if(xe.inputIndices.includes(Ft)){let Lt=vt.symbolToIndices.get(Ie);if(Lt===void 0)throw new Error("Invalid symbol error");Lt.forEach(pr=>{q.push(`${c[Ft].indicesSet(`input${Ft}Indices`,pr,d.indicesGet("outputIndices",et))}`)})}})}else s.lhs.forEach((et,vt)=>{if(xe.inputIndices.includes(vt)){let Ft=et.symbolToIndices.get(Ie);if(Ft===void 0)throw new Error("Invalid symbol error");Ft.forEach(Lt=>{re.push(`${c[vt].indicesSet(`input${vt}Indices`,Lt,`${Ie}`)}`)}),be.push(`prod *= ${c[vt].getByIndices(`input${vt}Indices`)};`)}}),ce.push(`for(var ${Ie}: u32 = 0; ${Ie} < uniforms.${Us(Ie)}; ${Ie}++) {`),_e.push("}")});let Fe=he?[...q,`let sum = ${c.map((xe,Ie)=>xe.getByIndices(`input${Ie}Indices`)).join(" * ")};`]:[...q,v,...ce,...re,H,...be,ne,..._e];return` + ${E.registerUniforms(b.map(xe=>({name:`${Us(xe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...c,d)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${d.offsetToIndices("global_idx")}; + ${c.map((xe,Ie)=>`var input${Ie}Indices: ${c[Ie].type.indices};`).join(` +`)} + ${Fe.join(` +`)}; + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:r.map(()=>"rank")},getRunData:()=>{let E=b.filter(H=>s.symbolToInfo.has(H)).map(H=>{var v;return{type:12,data:((v=s.symbolToInfo.get(H))==null?void 0:v.dimValue)||0}});E.push({type:12,data:p});let q=r.map((H,v)=>[...Ct(H)]).reduce((H,v)=>H.concat(v),E);return q.push(...Ct(u)),{outputs:[{dims:u,dataType:i}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:q}},getShaderSource:T}},wd=(r,i)=>{let s=new hp(r.inputs,i.equation),u=s.outputDims,c=r.inputs.map((p,d)=>p.dims);r.compute(yd(c,r.inputs[0].dataType,s,u))},vd=r=>{let i=r.equation.replace(/\s+/g,"");return Gt({equation:i})}}),gl,Vs,bd,xd,_l,hm=h(()=>{Xt(),Yt(),or(),gl=r=>{if(!r||r.length!==2)throw new Error("Expand requires 2 input.");let i=r[0].dims,s=Array.from(r[1].getBigInt64Array(),Number),u=s.length<i.length?0:s.length-i.length,c=i.length<s.length?0:i.length-s.length;for(;u<s.length&&c<i.length;++u,++c)if(s[u]!==i[c]&&s[u]!==1&&i[c]!==1)throw new Error("Expand requires shape to be broadcastable to input")},Vs=(r,i)=>{let s=r.length-i.length,u=[];for(let c=0;c<s;++c)u.push(r[c]);for(let c=0;c<i.length;++c)u.push(i[c]===1?r[c+s]:i[c]);return u},bd=(r,i)=>r.length>i.length?Vs(r,i):Vs(i,r),xd=r=>{let i=r[0].dims,s=Array.from(r[1].getBigInt64Array(),Number),u=bd(i,s),c=r[0].dataType,p=c===9?4:1,d=Math.ceil(st.size(u)/p),b=E=>{let q=gt("input",c,i.length,p),H=Vt("output",c,u.length,p),v;if(c===9){let ne=(re,ce,_e="")=>` + let outputIndices${ce} = ${H.offsetToIndices(`outputOffset + ${ce}u`)}; + let offset${ce} = ${q.broadcastedIndicesToOffset(`outputIndices${ce}`,H)}; + let index${ce} = offset${ce} / 4u; + let component${ce} = offset${ce} % 4u; + ${re}[${ce}] = ${_e}(${q.getByOffset(`index${ce}`)}[component${ce}]); + `;v=` + let outputOffset = global_idx * ${p}; + var data = vec4<u32>(0); + ${ne("data",0,"u32")} + ${ne("data",1,"u32")} + ${ne("data",2,"u32")} + ${ne("data",3,"u32")} + ${H.setByOffset("global_idx","data")} + }`}else v=` + let outputIndices = ${H.offsetToIndices("global_idx")}; + let inputOffset = ${q.broadcastedIndicesToOffset("outputIndices",H)}; + ${H.setByOffset("global_idx",q.getByOffset("inputOffset"))} + }`;return` + ${E.registerUniform("vec_size","u32").declareVariables(q,H)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v}`},T=[{type:12,data:d},...Ct(i,u)];return{name:"Expand",shaderCache:{hint:`${u.length}`,inputDependencies:["rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:T})}},_l=r=>{gl(r.inputs),r.compute(xd(r.inputs),{inputs:[0]})}}),gp,Md,_p=h(()=>{Xt(),Yt(),or(),Ua(),gp=r=>{let i=r[0].dataType,s=st.size(r[0].dims),u=st.size(r[1].dims),c=u%4===0,p=d=>{let b=gt("x",i,[1],4),T=gt("bias",i,[1],4),E=Vt("y",i,[1],4),q=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],H=ne=>` + let bias${ne}_offset: u32 = (global_idx * 4 + ${ne}) % uniforms.bias_size; + let bias${ne} = ${T.getByOffset(`bias${ne}_offset / 4`)}[bias${ne}_offset % 4];`,v=c?` + let bias = ${T.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${H(0)}${H(1)}${H(2)}${H(3)} + let bias = ${b.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(q).declareVariables(b,T,E)} + + ${Ba(kr(i))} + + ${d.mainStart(Bn)} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${b.getByOffset("global_idx")}; + ${v} + let x_in = x + bias; + ${E.setByOffset("global_idx",Na("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${c}`,inputDependencies:["type","type"]},getShaderSource:p,getRunData:d=>({outputs:[{dims:d[0].dims,dataType:d[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:u}],dispatchGroup:{x:Math.ceil(s/Bn/4)}})}},Md=r=>{r.inputs.length<2||st.size(r.inputs[1].dims)===0?Mc(r):r.compute(gp(r.inputs))}}),Td,kd,Sd,Ed,yp=h(()=>{Xt(),Yt(),mr(),or(),Td=r=>{if(!r||r.length!==2)throw new Error("Gather requires 2 inputs.")},kd=(r,i)=>{let s=r[0].dims,u=r[1].dims,c=s.length,p=st.normalizeAxis(i.axis,c),d=s.slice(0);d.splice(p,1,...u);let b=s[p],T=r[0].dataType===9?4:1,E=Math.ceil(st.size(d)/T),q=[{type:12,data:E},{type:6,data:b},{type:12,data:p},...Ct(r[0].dims,r[1].dims,d)],H=v=>{let ne=gt("data",r[0].dataType,r[0].dims.length,T),re=gt("inputIndices",r[1].dataType,r[1].dims.length),ce=Vt("output",r[0].dataType,d.length,T),_e=he=>{let Fe=u.length,xe=`var indicesIndices${he} = ${re.type.indices}(0);`;for(let Ie=0;Ie<Fe;Ie++)xe+=`${Fe>1?`indicesIndices${he}[${Ie}]`:`indicesIndices${he}`} = ${d.length>1?`outputIndices${he}[uniforms.axis + ${Ie}]`:`outputIndices${he}`};`;xe+=` + var idx${he} = ${re.getByIndices(`indicesIndices${he}`)}; + if (idx${he} < 0) { + idx${he} = idx${he} + uniforms.axisDimLimit; + } + var dataIndices${he} : ${ne.type.indices}; + `;for(let Ie=0,ct=0;Ie<c;Ie++)Ie===p?(xe+=`${c>1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = u32(idx${he});`,ct+=Fe):(xe+=`${c>1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = ${d.length>1?`outputIndices${he}[${ct}]`:`outputIndices${he}`};`,ct++);return xe},be;if(r[0].dataType===9){let he=(Fe,xe,Ie="")=>` + let outputIndices${xe} = ${ce.offsetToIndices(`outputOffset + ${xe}u`)}; + ${_e(xe)}; + let offset${xe} = ${ne.indicesToOffset(`dataIndices${xe}`)}; + let index${xe} = offset${xe} / 4u; + let component${xe} = offset${xe} % 4u; + ${Fe}[${xe}] = ${Ie}(${ne.getByOffset(`index${xe}`)}[component${xe}]); + `;be=` + let outputOffset = global_idx * ${T}; + var value = vec4<u32>(0); + ${he("value",0,"u32")} + ${he("value",1,"u32")} + ${he("value",2,"u32")} + ${he("value",3,"u32")} + ${ce.setByOffset("global_idx","value")} + `}else be=` + let outputIndices = ${ce.offsetToIndices("global_idx")}; + ${_e("")}; + let value = ${ne.getByIndices("dataIndices")}; + ${ce.setByOffset("global_idx","value")}; + `;return` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(ne,re,ce)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${be} + }`};return{name:"Gather",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:q}),getShaderSource:H}},Sd=r=>Gt({axis:r.axis}),Ed=(r,i)=>{let s=r.inputs;Td(s),r.compute(kd(r.inputs,i))}}),Cd,Pd,$d,Ad,wp=h(()=>{Xt(),Yt(),mr(),or(),Cd=r=>{if(!r||r.length!==2)throw new Error("GatherElements requires 2 inputs.");if(r[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(r[0].dims.length!==r[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Pd=(r,i)=>{let s=r[0].dims,u=r[0].dataType,c=s.length,p=r[1].dims,d=r[1].dataType,b=st.normalizeAxis(i.axis,c),T=s[b],E=p.slice(0),q=st.size(E),H=gt("input",u,c),v=gt("indicesInput",d,p.length),ne=Vt("output",u,E.length),re=[{type:12,data:q},{type:6,data:T},{type:12,data:b}];return re.push(...Ct(s,p,E)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:E,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:re}),getShaderSource:ce=>` + ${ce.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(H,v,ne)} + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${ne.offsetToIndices("global_idx")}; + + var idx = ${v.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${H.type.indices}(outputIndices); + ${H.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${H.getByIndices("inputIndices")}; + + ${ne.setByOffset("global_idx","value")}; + }`}},$d=r=>Gt({axis:r.axis}),Ad=(r,i)=>{let s=r.inputs;Cd(s),r.compute(Pd(r.inputs,i))}}),Id,Fd,zd,vp,Od=h(()=>{Xt(),Yt(),or(),Id=r=>{if(!r)throw new Error("Input is missing");if(r.length<2||r.length>3)throw new Error("Invaid input number.");if(r.length===3&&r[2].dims.length>2)throw new Error("Invalid input shape of C");if(r[0].dataType!==r[1].dataType||r.length===3&&r[0].dataType!==r[2].dataType)throw new Error("Input types are mismatched")},Fd=(r,i)=>{let s=r[0].dims.slice(),u=r[1].dims.slice(),[c,p,d]=xr.getShapeOfGemmResult(s,i.transA,u,i.transB,r.length===3?r[2].dims:void 0),b=[c,p];if(!b)throw new Error("Can't use gemm on the given tensors");let T=st.size(b),E=[{type:12,data:T},{type:12,data:c},{type:12,data:p},{type:12,data:d},{type:1,data:i.alpha},{type:1,data:i.beta}],q=["type","type"];r.length===3&&(E.push(...Ct(r[2].dims)),q.push("rank")),E.push(...Ct(b));let H=v=>{let ne="";i.transA&&i.transB?ne="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":i.transA&&!i.transB?ne="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!i.transA&&i.transB?ne="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!i.transA&&!i.transB&&(ne="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let re=i.alpha===1?"":"value *= uniforms.alpha;",ce=gt("a",r[0].dataType,r[0].dims),_e=gt("b",r[1].dataType,r[1].dims),be=ce.type.value,he=null,Fe=[ce,_e];r.length===3&&(he=gt("c",r[2].dataType,r[2].dims.length),Fe.push(he));let xe=Vt("output",r[0].dataType,b.length);Fe.push(xe);let Ie=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${v.registerUniforms(Ie).declareVariables(...Fe)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${be}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${ne} + } + + ${re} + ${he!=null?`let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)",xe)}; value += ${be}(uniforms.beta) * ${he.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:b,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:E}),getShaderSource:H}},zd=r=>{let i=r.transA,s=r.transB,u=r.alpha,c=r.beta;return{transA:i,transB:s,alpha:u,beta:c,cacheKey:`${r.transA};${r.transB};${r.alpha===1}`}},vp=(r,i)=>{Id(r.inputs),r.compute(Fd(r.inputs,i))}}),Sn,Dd,Ld,yl,Rd,Xo,Bd,Nd=h(()=>{Xt(),Yt(),mr(),fe(),Is(),or(),_o(),Sn=(r,i)=>r.length>i&&r[i].dims.length>0?r[i]:void 0,Dd=(r,i)=>{let s=r[0],u=Sn(r,1),c=Sn(r,2),p=Sn(r,3),d=Sn(r,4),b=Sn(r,5),T=Sn(r,6),E=Sn(r,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let q=s.dims[0],H=s.dims[1],v=s.dims.length===3?s.dims[2]:i.numHeads*s.dims[4],ne=H,re=0,ce=0,_e=Math.floor(v/i.numHeads);if(T&&E){if(T.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(T.dims[0]!==q||T.dims[1]!==i.numHeads||T.dims[3]!==_e)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(E.dims[0]!==q||E.dims[1]!==i.numHeads||E.dims[3]!==_e)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(T.dims[2]!==E.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(E.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');re=T.dims[2],ce=T.dims[2]}else if(T||E)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let be;if(u){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(u.dims.length<3||u.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==u.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(u.dims.length===3){if(u.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');be=2,ne=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==_e)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(c)throw new Error('Expect "value" be none when "key" has packed kv format.');be=5,ne=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==_e)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');be=0,ne=u.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==i.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');be=3}if(p){if(p.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(u&&u.dims.length===5&&u.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let he=re+ne,Fe=0;if(d){Fe=8;let et=d.dims;throw et.length===1?et[0]===q?Fe=1:et[0]===3*q+2&&(Fe=3):et.length===2&&et[0]===q&&et[1]===he&&(Fe=5),Fe===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let xe=!1,Ie=v;if(c){if(c.dims.length!==3&&c.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==c.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(c.dims.length===3){if(ne!==c.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ie=c.dims[2]}else{if(ne!==c.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Ie=c.dims[1]*c.dims[3],xe=!0}}let ct=!1;if(d)throw new Error("Key padding mask is not supported");if(b){if(b.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(b.dims[0]!==q||b.dims[1]!==i.numHeads||b.dims[2]!==H||b.dims[3]!==he)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:q,sequenceLength:H,pastSequenceLength:re,kvSequenceLength:ne,totalSequenceLength:he,maxSequenceLength:ce,inputHiddenSize:0,hiddenSize:v,vHiddenSize:Ie,headSize:_e,vHeadSize:Math.floor(Ie/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:Fe,scale:i.scale,broadcastResPosBias:ct,passPastInKv:xe,qkvFormat:be}},Ld=r=>Gt({...r}),yl=Gt({perm:[0,2,1,3]}),Rd=(r,i,s,u,c,p,d)=>{let b=[u,c,p],T=st.size(b),E=[{type:12,data:T},{type:12,data:d},{type:12,data:p}],q=H=>{let v=Vt("qkv_with_bias",i.dataType,b),ne=gt("qkv",i.dataType,b),re=gt("bias",s.dataType,b),ce=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${H.registerUniforms(ce).declareVariables(ne,re,v)} + ${H.mainStart()} + ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return r.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:b,dataType:i.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:E}),getShaderSource:q},{inputs:[i,s],outputs:[-1]})[0]},Xo=(r,i,s,u,c,p,d,b)=>{let T=p;if(d){if(u===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return T=Rd(r,p,d,i,u,s*c,b),T=T.reshape([i,u,s,c]),r.compute(fi(T,yl.perm),{inputs:[T],outputs:[-1]})[0]}else return p.dims.length===3&&(T=p.reshape([i,u,s,c])),r.compute(fi(T,yl.perm),{inputs:[T],outputs:[-1]})[0]},Bd=(r,i)=>{let s=Dd(r.inputs,i),u=r.inputs[0],c=Sn(r.inputs,1),p=Sn(r.inputs,2),d=Sn(r.inputs,3),b=Sn(r.inputs,4),T=Sn(r.inputs,5),E=Sn(r.inputs,6),q=Sn(r.inputs,7);if(u.dims.length===5)throw new Error("Packed QKV is not implemented");if((c==null?void 0:c.dims.length)===5)throw new Error("Packed KV is not implemented");let H=c&&p&&c.dims.length===4&&p.dims.length===4,v=Xo(r,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,d,0);if(H)return yo(r,v,c,p,b,void 0,E,q,T,s,i);if(!c||!p)throw new Error("key and value must be provided");let ne=Xo(r,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,c,d,s.hiddenSize),re=Xo(r,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,p,d,2*s.hiddenSize);yo(r,v,ne,re,b,void 0,E,q,T,s,i)}}),wl,jd,Ud,vl,Vd,Wd=h(()=>{Xt(),Yt(),or(),wl=r=>Array.from(r.getBigInt64Array(),Number),jd=r=>{if(!r||r.length!==2)throw new Error("Tile requires 2 inputs.");if(r[0].dataType!==1&&r[0].dataType!==10&&r[0].dataType!==6&&r[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(r[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(r[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(wl(r[1]).length!==r[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Ud=(r,i)=>{let s=[];for(let u=0;u<r.length;++u)s.push(r[u]*i[u]);return s},vl=(r,i)=>{let s=r[0].dims,u=i??wl(r[1]),c=Ud(s,u),p=st.size(c),d=r[0].dataType,b=gt("input",d,s.length),T=Vt("output",d,c.length),E=q=>` + const inputShape = ${b.indices(...s)}; + ${q.registerUniform("output_size","u32").declareVariables(b,T)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${T.offsetToIndices("global_idx")}; + var input_indices: ${b.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${b.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${T.indicesGet("output_indices","i")} % input_dim_i; + + ${b.indicesSet("input_indices","i","input_dim_value")} + } + ${T.setByOffset("global_idx",b.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${u}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:c,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...Ct(r[0].dims,c)]}),getShaderSource:E}},Vd=r=>{jd(r.inputs),r.compute(vl(r.inputs),{inputs:[0]})}}),Gd,bl,qd,Hd,xl,Kd,bp=h(()=>{Xt(),Yt(),mr(),Is(),or(),Nd(),Wd(),_o(),Gd=(r,i)=>{let s=r[0],u=r[1],c=r[2],p=r[3],d=r[4];if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let b=!1,T=s.dims[0],E=s.dims[1],q=s.dims.length===3?b?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],H=E,v=0,ne=0,re=Math.floor(q/i.numHeads),ce=p&&p.dims.length!==0,_e=d&&d.dims.length!==0,be=!0;if(ce&&_e){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');v=p.dims[1],ne=p.dims[1]}else if(ce||_e)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let he;if(u){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(u.dims.length<3||u.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==u.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(u.dims.length===3){if(s.dims[2]%u.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');he=2,H=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==re)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(c)throw new Error('Expect "value" be none when "key" has packed kv format.');he=5,H=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==re)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,H=u.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==i.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');he=3}let Fe=0,xe=!1,Ie=q;if(c){if(c.dims.length!==3&&c.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==c.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(c.dims.length===3){if(H!==c.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ie=c.dims[2]}else{if(H!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');Ie=c.dims[1]*c.dims[3],xe=!0}}let ct=v+H;return{batchSize:T,sequenceLength:E,pastSequenceLength:v,kvSequenceLength:H,totalSequenceLength:ct,maxSequenceLength:ne,inputHiddenSize:0,hiddenSize:q,vHiddenSize:Ie,headSize:re,vHeadSize:Math.floor(Ie/i.kvNumHeads),numHeads:i.numHeads,kvNumHeads:i.kvNumHeads,nReps:i.numHeads/i.kvNumHeads,pastPresentShareBuffer:!1,maskType:Fe,scale:i.scale,broadcastResPosBias:!1,passPastInKv:xe,qkvFormat:he,isPastkvBSNH:be}},bl=(r,i,s,u)=>{let c=[u.batchSize,u.totalSequenceLength,u.kvNumHeads,u.headSize],p=4,d=st.size(c)/p,b=u.totalSequenceLength,T=Vt("present_kv",s,c.length,p),E=gt("new_kv",r.dataType,r.dims.length,p),q=i?gt("past_kv",i.dataType,i.dims.length,p):void 0,H=Math.ceil(u.headSize/p),v={x:b,y:r.dims[0],z:1},ne=i?["rank","rank"]:["rank"],re=[{type:12,data:d},{type:12,data:u.pastSequenceLength},{type:12,data:u.kvSequenceLength},{type:12,data:u.totalSequenceLength}],ce=[E];q?(re.push(...Ct(r.dims),...Ct(i.dims),...Ct(c)),ce.push(q)):re.push(...Ct(r.dims),...Ct(c));let _e=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],be=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; + var past_head_stride = uniforms.past_seqlen * H; + if (is_bsnh) { + past_head_stride = H; + } + let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; + present_kv[out_offset] = past_kv[in_offset];`,he=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; + let new_row_stride = num_heads * H; + let new_head_stride = H; + let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; + present_kv[out_offset] = new_kv[in_offset];`,Fe=i?`if (s < past_seqlen) { + ${be} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${he} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${he} + }`,xe=Ie=>` + + ${Ie.registerUniforms(_e).declareVariables(...ce,T)} + ${Ie.mainStart([H,u.kvNumHeads,1])} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${T.offsetToIndices("global_idx")}; + let h = local_id.x; + let n = local_id.y; + let s = workgroup_id.x; + let b = workgroup_id.y; + let num_heads = ${u.kvNumHeads}u; + let H = ${H}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${u.isPastkvBSNH}; + + if (is_bsnh) { + row_stride = num_heads * H; + } + var present_head_stride = present_seqlen * H; + if (is_bsnh) { + present_head_stride = H; + } + + let past_seqlen = uniforms.past_seqlen; + + let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; + ${Fe} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${u.kvNumHeads}${H}${!!i}`,inputDependencies:ne},getRunData:()=>({outputs:[{dims:c,dataType:s}],dispatchGroup:v,programUniforms:re}),getShaderSource:xe}},qd=r=>Gt({...r}),Hd=Gt({perm:[0,2,1,3]}),xl=(r,i,s,u,c)=>{let p=i,d=u.kvNumHeads,b=u.nReps;return i.dims.length===3&&u.kvSequenceLength!==0&&(p=i.reshape([u.batchSize,u.kvSequenceLength,d,u.headSize])),s?p=r.compute(bl(p,s,p.dataType,u),{inputs:[p,s],outputs:[u.isPastkvBSNH?c:-1]})[0]:p=r.compute(bl(p,void 0,p.dataType,u),{inputs:[p],outputs:[u.isPastkvBSNH?c:-1]})[0],b!==1&&(p=r.compute(vl([p],[1,1,1,b]),{inputs:[p],outputs:[-1]})[0],p=p.reshape([u.batchSize,u.totalSequenceLength,d*b,u.headSize])),r.compute(fi(p,Hd.perm),{inputs:[p],outputs:[-1]})[0]},Kd=(r,i)=>{var T;let s=Gd(r.inputs,i);if(r.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((T=r.inputs[1])==null?void 0:T.dims.length)===5)throw new Error("Packed KV is not implemented");let u=Xo(r,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,r.inputs[0],void 0,0),c=r.inputs[3]&&r.inputs[3].dims.length!==0?r.inputs[3]:void 0,p=r.inputs[4]&&r.inputs[4].dims.length!==0?r.inputs[4]:void 0,d=xl(r,r.inputs[1],c,s,1),b=xl(r,r.inputs[2],p,s,2);yo(r,u,d,b,void 0,void 0,void 0,void 0,void 0,s,i)}}),Qd,Xd,Yd,Zd,mm=h(()=>{Xt(),Yt(),or(),Qd=(r,i)=>{let s=r[0].dims,u=s,c=2,p=st.sizeToDimension(s,c),d=st.sizeFromDimension(s,c),b=wr(d),T=d/b,E=[s[0],s[1],T],q=["rank","type","type"],H=[{type:12,data:d},{type:12,data:T}];H.push(...Ct(E,E));let v=ne=>{let re=gt("x",r[0].dataType,E.length,b),ce=gt("scale",r[1].dataType,r[1].dims),_e=gt("bias",r[2].dataType,r[2].dims),be=Vt("output",r[0].dataType,E.length,b),he=[re,ce,_e,be],Fe=re.type.value,xe=b===1?"f32":`vec${b}<f32>`,Ie=64,ct=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var<workgroup> meanShared : f32; + var<workgroup> squaredNormShared : f32; + var<workgroup> workgroupShared : array<${xe}, ${Ie}>; + const workgroupSize = ${Ie}u; + ${ne.registerUniforms(ct).declareVariables(...he)} + ${ne.mainStart(Ie)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${xe}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${xe}(${re.get("batch","channel","h")}); + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the mean of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + meanShared = ${Nn("workgroupShared[0]",b)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${xe}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${xe}(${re.get("batch","channel","h")}) - ${xe}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${Nn("workgroupShared[0]",b)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${i.epsilon})); + let channelScale = invStdDev * f32(${ce.getByOffset("channel")}); + let channelShift = f32(${_e.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${re.get("batch","channel","h")} * ${Fe}(${xe}(channelScale)) + ${Fe}(${xe}(channelShift)); + ${be.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${i.epsilon};${b}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:p},programUniforms:H}),getShaderSource:v}},Xd=(r,i,s,u,c,p,d,b)=>{let T=wr(d),E=64,q=T===1?"vec2f":`mat2x${T}f`,H=T===1?"f32":`vec${T}f`,v=(ct,et)=>`${q}(${ct}, ${et})`,ne=c*d/T,re=Math.ceil(p/E),ce=["type"],_e=[{type:12,data:re},{type:12,data:p},{type:12,data:Math.floor(d/T)},{type:12,data:Math.floor(p*d/T)}],be=ct=>{let et=gt("input",i.dataType,i.dims,T);return` + ${ct.declareVariables(et)} + @group(0) @binding(1) var<storage, read_write> output : array<${q}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var<uniform> uniforms: Uniforms; + + ${ct.mainStart(E)} + let currentImageNumber = global_idx / ${E} / uniforms.C; + let currentChannelNumber = (global_idx / ${E}) % uniforms.C; + let wgOffset = local_id.x * uniforms.wg_size; + if (wgOffset >= uniforms.H) { + return; + } + let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); + + let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; + var sum = ${zr("f32",T)}; + var squaredSum = ${zr("f32",T)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${H}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${v("sum","squaredSum")}; + }`},he=r.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${T}`,inputDependencies:ce},getRunData:()=>({outputs:[{dims:[c,d,E,2],dataType:1}],dispatchGroup:{x:c*d/T},programUniforms:_e}),getShaderSource:be},{inputs:[i],outputs:[-1]})[0],Fe=[{type:12,data:ne},{type:12,data:p},{type:12,data:Math.floor(d/T)},{type:12,data:Math.floor(E*d/T)}],xe=["type","type","type"],Ie=ct=>{let et=gt("scale",s.dataType,s.dims,T),vt=gt("bias",u.dataType,u.dims,T);return` + @group(0) @binding(0) var<storage, read> input : array<${q}>; + @group(0) @binding(1) var<storage, read> scale : array<${et.type.storage}>; + @group(0) @binding(2) var<storage, read> bias : array<${vt.type.storage}>; + @group(0) @binding(3) var<storage, read_write> output : array<${q}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var<uniform> uniforms: Uniforms; + + ${ct.mainStart()} + ${ct.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} + let currentImageNumber = global_idx / uniforms.C; + let currentChannelNumber = global_idx % uniforms.C; + + let offset = currentImageNumber * uniforms.image_size; + var sum = ${zr("f32",T)}; + var squaredSum = ${zr("f32",T)}; + for (var i: u32 = 0; i < min(${E}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${E}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${b})); + let channelScale = invStdDev * ${H}(scale[currentChannelNumber]); + let channelShift = ${H}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${v("channelScale","channelShift")}; + }`};return r.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${T};${b}`,inputDependencies:xe},getRunData:()=>({outputs:[{dims:[c,d,2],dataType:1}],dispatchGroup:{x:Math.ceil(ne/64)},programUniforms:Fe}),getShaderSource:Ie},{inputs:[he,s,u],outputs:[-1]})[0]},Yd=(r,i,s)=>{let u=i[0].dims,c=u,p=u[0],d=u[u.length-1],b=st.sizeFromDimension(u,1)/d,T=wr(d),E=st.size(c)/T,q=[{type:12,data:b},{type:12,data:Math.floor(d/T)}],H=["type","type"],v=Xd(r,i[0],i[1],i[2],p,b,d,s.epsilon),ne=re=>{let ce=Tr(i[0].dataType),_e=T===1?"vec2f":`mat2x${T}f`,be=T===1?ce:`vec${T}<${ce}>`,he=gt("input",i[0].dataType,i[0].dims,T),Fe=Vt("output",i[0].dataType,c,T);return` + @group(0) @binding(0) var<storage, read> input : array<${he.type.storage}>; + @group(0) @binding(1) var<storage, read> scaleInput : array<${_e}>; + @group(0) @binding(2) var<storage, read_write> output : array<${Fe.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var<uniform> uniforms: Uniforms; + + ${re.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${be}(scale[0]), ${be}(scale[1])); + }`};r.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${T}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:c,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:q}),getShaderSource:ne},{inputs:[i[0],v]})},Zd=(r,i)=>{i.format==="NHWC"?Yd(r,r.inputs,i):r.compute(Qd(r.inputs,i))}}),ur,Jd,dn,yn=h(()=>{Xt(),Yt(),or(),ur=r=>{if(!r||r.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Jd=(r,i,s)=>{let u=i.simplified,c=r[0].dims,p=r[1],d=!u&&r[2],b=c,T=st.normalizeAxis(i.axis,c.length),E=st.sizeToDimension(c,T),q=st.sizeFromDimension(c,T),H=st.size(p.dims),v=d?st.size(d.dims):0;if(H!==q||d&&v!==q)throw new Error(`Size of X.shape()[axis:] == ${q}. + Size of scale and bias (if provided) must match this. + Got scale size of ${H} and bias size of ${v}`);let ne=[];for(let Ie=0;Ie<c.length;++Ie)Ie<T?ne.push(c[Ie]):ne.push(1);let re=wr(q),ce=["type","type"],_e=[{type:12,data:E},{type:1,data:q},{type:12,data:Math.floor(q/re)},{type:1,data:i.epsilon}];d&&ce.push("type");let be=s>1,he=s>2,Fe=Ie=>{let ct=Tr(r[0].dataType),et=[gt("x",r[0].dataType,r[0].dims,re),gt("scale",p.dataType,p.dims,re)];d&&et.push(gt("bias",d.dataType,d.dims,re)),et.push(Vt("output",r[0].dataType,b,re)),be&&et.push(Vt("mean_data_output",1,ne)),he&&et.push(Vt("inv_std_output",1,ne));let vt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Ie.registerUniforms(vt).declareVariables(...et)} + ${Ie.mainStart()} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${zr("f32",re)}; + var mean_square_vector = ${zr("f32",re)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Gr(ct,re,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Nn("mean_vector",re)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Nn("mean_square_vector",re)} / uniforms.norm_size ${u?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Gr(ct,re,"x[j + offset]")}; + let f32scale = ${Gr(ct,re,"scale[j]")}; + output[j + offset] = ${et[0].type.value}((f32input ${u?"":"- mean"}) * inv_std_dev * f32scale + ${d?`+ ${Gr(ct,re,"bias[j]")}`:""} + ); + } + + ${be?"mean_data_output[global_idx] = mean":""}; + ${he?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},xe=[{dims:b,dataType:r[0].dataType}];return be&&xe.push({dims:ne,dataType:1}),he&&xe.push({dims:ne,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${re};${s};${u}`,inputDependencies:ce},getRunData:()=>({outputs:xe,dispatchGroup:{x:Math.ceil(E/64)},programUniforms:_e}),getShaderSource:Fe}},dn=(r,i)=>{ur(r.inputs),r.compute(Jd(r.inputs,i,r.outputCount))}}),wn,Ji,xp,ef,Mp=h(()=>{Xt(),Yt(),mr(),or(),wn=(r,i)=>{if(r.length<3||r.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=r[0],u=s.dims.length;if(s.dims[u-1]!==i.k)throw new Error("The last dim of input shape does not match the k value");let c=Math.floor((i.k+i.blockSize-1)/i.blockSize),p=i.blockSize/8*i.bits,d=r[1];if(!st.areEqual(d.dims,[i.n,c,p]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let b=r[2].dims;if(st.size(b)!==i.n*c)throw new Error("scales input size error.");if(r.length===4){let T=r[3].dims,E=i.bits>4?i.n*c:i.n*Math.floor((c+1)/2);if(st.size(T)!==E)throw new Error("zeroPoints input size error.")}},Ji=(r,i,s,u)=>{let c=r[0].dims,p=c.length,d=Math.floor((i.k+i.blockSize-1)/i.blockSize),b=c[p-2],T=i.k,E=i.n,q=c.slice(0,p-2),H=st.size(q),v=i.blockSize/8*i.bits/4,ne=r[0].dataType,re=wr(b),ce=wr(i.k),_e=wr(v),be=Mi(ne,b*d),he=Math.floor(u/be),Fe=d<=s[0]&&he>0,xe=!Fe||he>=4?wr(E):he>=2&&wr(E)>=2?2:1,Ie=q.concat([b,E]),ct=st.size(Ie)/xe/re,et=Fe?[]:[{type:12,data:ct},{type:12,data:i.blockSize}],vt=[H,b,T/ce],Ft=st.convertShape(r[1].dims).slice();Ft.splice(-1,1,v/_e),et.push(...Ct(vt)),et.push(...Ct(Ft)),et.push(...Ct(r[2].dims)),r.length===4&&et.push(...Ct(st.convertShape(r[3].dims)));let Lt=[H,b,E/xe];et.push(...Ct(Lt));let pr=ar=>{let nr=vt.length,yr=gt("a",r[0].dataType,nr,ce),qr=gt("b",12,Ft.length,_e),Sr=gt("scales",r[2].dataType,r[2].dims.length),jr=[yr,qr,Sr],It=r.length===4?gt("zero_points",12,r[3].dims.length):void 0;It&&jr.push(It);let tr=Lt.length,er=Vt("output",r[0].dataType,tr,xe),pt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],zt=Tr(r[0].dataType),ir=(()=>{switch(ce){case 1:return`array<${zt}, 8>`;case 2:return`mat4x2<${zt}>`;case 4:return`mat2x4<${zt}>`;default:throw new Error(`${ce}-component is not supported.`)}})(),Hr=` + for (var word: u32 = 0; word < ${v}; word += ${_e}) { + ${qr.indicesSet("b_indices","2","word")}; + let b_data = ${qr.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${_e}; i++) { + let b_value: u32 = ${_e===1?"b_data":"b_data[word + i]"}; + let b_mask: u32 = 0x0F0F0F0Fu; + let b_value_lower: vec4<u32> = unpack4xU8(b_value & b_mask); + let b_value_upper: vec4<u32> = unpack4xU8((b_value >> 4) & b_mask); + let b_quantized_values = ${ir}(${Array.from({length:4},(xn,Yn)=>`${zt}(b_value_lower[${Yn}]), ${zt}(b_value_upper[${Yn}])`).join(", ")}); + let b_dequantized_values = ${ce===1?`${ir}(${Array.from({length:8},(xn,Yn)=>`(b_quantized_values[${Yn}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ir}(${Array(8).fill("zero_point").join(",")})) * scale;`}; + // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 + for (var m: u32 = 0; m < ${Fe?b:re}u; m++) { + ${yr.indicesSet("a_indices",nr-2,Fe?"m":`row * ${re} + m`)}; + ${yr.indicesSet("a_indices",nr-1,"word_offset")}; + var input_offset = ${yr.indicesToOffset("a_indices")}; + var a_data: ${ir}; + for (var j: u32 = 0; j < ${8/ce}; j++) { + a_data[j] = ${yr.getByOffset("input_offset")}; + input_offset++; + } + ${Fe?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${xe>1?"[c]":""} += ${Array.from({length:8/ce},(xn,Yn)=>`${ce===1?`a_data[${Yn}] * b_dequantized_values[${Yn}]`:`dot(a_data[${Yn}], b_dequantized_values[${Yn}])`}`).join(" + ")}; + } + word_offset += ${8/ce}; + } + }`,un=It?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${It.getByOffset("zero_point_index")}; + }`:"";return Fe?` + var<workgroup> workgroup_shared: array<${er.type.value}, ${b*d}>; + ${ar.declareVariables(...jr,er)} + ${ar.mainStart([d,1,1])} + var a_indices: ${yr.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${yr.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${xe}; c++) { + let col_times_components_plus_c = col * ${xe} + c; + ${It?` + var zero_point_bytes_per_col: u32 = (${d} + 1) / 2; + var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); + var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; + var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; + var zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + var zero_point_word: u32 = ${It.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${qr.type.indices}; + ${qr.indicesSet("b_indices","0","col_times_components_plus_c")}; + // The scale and zero points are computed per block. + var scales_index = col_times_components_plus_c * ${d} + block; + let scale = ${Sr.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${zt}(${It?"(zero_point_word) & 0xFu":8}); + ${qr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${i.blockSize/ce}; + var workgroup_shared_offset: u32 = block * ${b}; + ${Hr} + } + workgroupBarrier(); + var output_indices: ${er.type.indices}; + var elements_per_thread: u32 = ${Math.ceil(b/d)}; + ${er.indicesSet("output_indices","0","batch")}; + ${er.indicesSet("output_indices",tr-1,"col")}; + ${er.indicesSet("output_indices",tr-2,"local_id.x * elements_per_thread")}; + var output_offset = ${er.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < elements_per_thread; m++) { + var row = m + local_id.x * elements_per_thread; + if (row < ${b}) { + var output_value: ${er.type.value} = ${er.type.value}(0); + var workgroup_shared_offset: u32 = row; + for (var b: u32 = 0u; b < ${d}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${b}; + } + ${er.setByOffset("output_offset","output_value")}; + output_offset += ${E/xe}; + } + } + }`:` + ${ar.registerUniforms(pt).declareVariables(...jr,er)} + ${ar.mainStart()} + ${ar.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${er.type.value}, ${re}>; + var output_indices = ${er.offsetToIndices("global_idx")}; + var col = ${er.indicesGet("output_indices",tr-1)}; + var row = ${er.indicesGet("output_indices",tr-2)}; + var a_indices: ${yr.type.indices} = output_indices; + // Two zero points are packed into one byte because uniforms.bits <= 4. + // zero_point_offset is either 0 or 4. It is bit offset within one byte. + // TODO support zero_point_offset for bits > 4 + ${It?` + var zero_point_abs_offset = col * ${xe} * ((${d} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${It.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${d*xe}; + var b_indices: ${qr.type.indices}; + for (var c: u32 = 0; c < ${xe}; c++) { + ${qr.indicesSet("b_indices","0",`col * ${xe} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${d}; block++) { + // The scale and zero points are computed per block. + let scale = ${Sr.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${zt}(${It?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${qr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${Hr} + scale_index++; + ${un} + block_offset += uniforms.block_size / ${ce}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${It?`if (zero_point_offset % 8 > 0) { + ${un} + }`:""} + } + for (var k: u32 = 0u; k < ${re}u; k++) { + ${er.indicesSet("output_indices",tr-2,`${re} * row + k`)}; + ${er.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:Fe?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${i.cacheKey};${b};${ne};${r.length}`,inputDependencies:Array(r.length).fill("rank")},getRunData:()=>({outputs:[{dims:Ie,dataType:ne}],name:Fe?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:Fe?{x:1,y:Math.ceil(E/xe),z:H}:{x:Math.ceil(ct/64)},programUniforms:et}),getShaderSource:pr}},xp=(r,i)=>{wn(r.inputs,i);let s=r.getMaxComputeWorkgroupSizes(),u=r.getMaxComputeWorkgroupStoragesize();r.compute(Ji(r.inputs,i,s,u))},ef=r=>Gt(r)}),V,G,ie,Ee,Ze,it,_t,Et,Wt,cr=h(()=>{Xt(),Yt(),or(),V=r=>{if(!r||r.length<1)throw new Error("Too few inputs");if(r[0].dataType!==1&&r[0].dataType!==10)throw new Error("Input type must be float or float16.");if(r.length>=2){let i=r[0].dims.length*2===r[1].dims[0];if(r.length===4&&(i=r[3].dims[0]*2===r[1].dims[0]),!i)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},G=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Dt("uniforms.x_shape",c,i)})) { + break; + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + value = ${r.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + } + `},ie=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Dt("uniforms.x_shape",c,i)}) - 1); + k = k % _2n_1; + if(k >= i32(${Dt("uniforms.x_shape",c,i)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ee=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Dt("uniforms.x_shape",c,i)})) { + k = i32(${Dt("uniforms.x_shape",c,i)}) - 1; + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ze=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + k += i32(${Dt("uniforms.x_shape",c,i)}]); + } + if (k >= i32(${Dt("uniforms.x_shape",c,i)})) { + k -= i32(${Dt("uniforms.x_shape",c,i)}); + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},it=(r,i,s)=>{switch(s.mode){case 0:return G(r,i,s.pads.length);case 1:return ie(r,i,s.pads.length);case 2:return Ee(r,i,s.pads.length);case 3:return Ze(r,i,s.pads.length);default:throw new Error("Invalid mode")}},_t=(r,i)=>{let s=st.padShape(r[0].dims.slice(),i.pads),u=r[0].dims,c=st.size(s),p=[{type:12,data:c},{type:6,data:i.pads}];i.mode===0&&p.push({type:r[0].dataType,data:i.value}),p.push(...Ct(r[0].dims,s));let d=["rank"],b=T=>{let E=Vt("output",r[0].dataType,s.length),q=gt("x",r[0].dataType,u.length),H=q.type.value,v=it(E,u.length,i),ne=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:i.pads.length}];return i.mode===0&&ne.push({name:"constant_value",type:H}),` + ${T.registerUniforms(ne).declareVariables(q,E)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${E.offsetToIndices("global_idx")}; + + var value = ${H}(0); + ${v} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${i.mode}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(st.size(s)/64)},programUniforms:p}),getShaderSource:b}},Et=(r,i)=>{if(r.length>1){let s=r[1].getBigInt64Array(),u=r.length>=3&&r[2].data?r[2].getFloat32Array()[0]:0,c=r[0].dims.length,p=new Int32Array(2*c).fill(0);if(r.length>=4){let b=r[3].getBigInt64Array();for(let T=0;T<b.length;T++)p[Number(b[T])]=Number(s[T]),p[Number(b[T])+c]=Number(s[T+b.length])}else s.forEach((b,T)=>p[Number(T)]=Number(b));let d=[];return p.forEach(b=>d.push(b)),{mode:i.mode,value:u,pads:d}}else return i},Wt=(r,i)=>{V(r.inputs);let s=Et(r.inputs,i);r.compute(_t(r.inputs,s),{inputs:[0]})}}),sr,$r,dr,_r,fr,gr,br,Dr,En,An,Ei,vn,ln,bn,Ws,Gs,Ml,gm,pi,Yo=h(()=>{Z(),Xt(),Yt(),or(),sr=r=>{if(D.webgpu.validateInputContent&&(!r||r.length!==1))throw new Error("Pool ops requires 1 input.")},$r=(r,i,s)=>{let u=i.format==="NHWC",c=r.dims.slice();u&&c.splice(1,0,c.pop());let p=Object.hasOwnProperty.call(i,"dilations"),d=i.kernelShape.slice(),b=i.strides.slice(),T=p?i.dilations.slice():[],E=i.pads.slice();qn.adjustPoolAttributes(s,c,d,b,T,E);let q=qn.computePoolOutputShape(s,c,b,T,d,E,i.autoPad),H=Object.assign({},i);p?Object.assign(H,{kernelShape:d,strides:b,pads:E,dilations:T,cacheKey:i.cacheKey}):Object.assign(H,{kernelShape:d,strides:b,pads:E,cacheKey:i.cacheKey});let v=q.slice();return v.push(v.splice(1,1)[0]),[H,u?v:q]},dr=(r,i)=>{let s=i.format==="NHWC",u=st.size(r),c=st.size(i.kernelShape),p=[{type:12,data:u},{type:12,data:c}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(i.kernelShape.length<=2){let b=i.kernelShape[i.kernelShape.length-1],T=i.strides[i.strides.length-1],E=i.pads[i.pads.length/2-1],q=i.pads[i.pads.length-1],H=!!(E+q);p.push({type:12,data:b},{type:12,data:T},{type:12,data:E},{type:12,data:q}),d.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let v=!1;if(i.kernelShape.length===2){let ne=i.kernelShape[i.kernelShape.length-2],re=i.strides[i.strides.length-2],ce=i.pads[i.pads.length/2-2],_e=i.pads[i.pads.length-2];v=!!(ce+_e),p.push({type:12,data:ne},{type:12,data:re},{type:12,data:ce},{type:12,data:_e}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[p,d,!0,H,v]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let b=st.computeStrides(i.kernelShape);p.push({type:12,data:b},{type:12,data:i.pads},{type:12,data:i.strides}),d.push({name:"kernelStrides",type:"u32",length:b.length},{name:"pads",type:"u32",length:i.pads.length},{name:"strides",type:"u32",length:i.strides.length});let T=i.pads.reduce((E,q)=>E+q);return[p,d,!!T,!1,!1]}},_r=(r,i,s,u,c,p,d,b,T,E,q,H)=>{let v=c.format==="NHWC",ne=i.type.value,re=Vt("output",i.type.tensor,u);if(c.kernelShape.length<=2){let ce="",_e="",be="",he=s-(v?2:1);if(q?ce=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${he}] = indices[${he}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${he}] < 0 || xIndices[${he}] + >= uniforms.x_shape[${he}]) { + pad++; + continue; + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + }`:ce=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${he}] = indices[${he}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + }`,c.kernelShape.length===2){let Fe=s-(v?3:2);H?_e=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${Fe}] = indices[${Fe}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${Fe}] < 0 || xIndices[${Fe}] >= uniforms.x_shape[${Fe}]) { + pad += i32(uniforms.kw); + continue; + } + `:_e=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${Fe}] = indices[${Fe}] * uniforms.sh - uniforms.phStart + j; + `,be=` + } + `}return` + ${r.registerUniforms(T).declareVariables(i,re)} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${re.offsetToIndices("global_idx")}; + var xIndices = ${re.offsetToIndices("global_idx")}; + + var value = ${ne}(${b}); + var pad = 0; + ${_e} + ${ce} + ${be} + ${d} + + output[global_idx] = value; + }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let ce=c.kernelShape.length,_e=c.pads.length,be="";return E?be=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + }`:be=` + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + `,` + ${r.registerUniforms(T).declareVariables(i,re)} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${re.offsetToIndices("global_idx")}; + var xIndices = ${re.offsetToIndices("global_idx")}; + + var offsets: array<u32, ${ce}>; + + var value = ${ne}(${b}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${ce-1}u; j++) { + offsets[j] = offset / ${Dt("uniforms.kernelStrides","j",ce)}; + offset -= offsets[j] * ${Dt("uniforms.kernelStrides","j",ce)}; + } + offsets[${ce-1}] = offset; + + isPad = false; + for (var j = ${s-ce}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Dt("uniforms.strides",`j - ${s-ce}u`,ce)} + + offsets[j - ${s-ce}u] - ${Dt("uniforms.pads","j - 2u",_e)}; + ${be} + } + ${d} + + output[global_idx] = value; + }`}},fr=r=>`${r.format};${r.ceilMode};${r.autoPad};${r.kernelShape.length}`,gr=r=>`${fr(r)};${r.countIncludePad}`,br=r=>`${fr(r)};${r.storageOrder};${r.dilations}`,Dr=r=>({format:r.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],ceilMode:r.ceil_mode,kernelShape:r.kernel_shape,strides:r.strides,pads:r.pads}),En=(r,i,s,u)=>{let[c,p]=$r(i,u,s),d=gt("x",i.dataType,i.dims.length),b=d.type.value,T="value += x_val;",E="";c.countIncludePad?E+=`value /= ${b}(uniforms.kernelSize);`:E+=`value /= ${b}(i32(uniforms.kernelSize) - pad);`;let[q,H,v,ne,re]=dr(p,c);q.push(...Ct(i.dims,p));let ce=["rank"];return{name:r,shaderCache:{hint:`${u.cacheKey};${v};${ne};${re}`,inputDependencies:ce},getRunData:()=>({outputs:[{dims:p,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(st.size(p)/64)},programUniforms:q}),getShaderSource:_e=>_r(_e,d,i.dims.length,p.length,c,T,E,0,H,v,ne,re)}},An=r=>{let i=r.count_include_pad!==0,s=Dr(r);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let u={countIncludePad:i,...s,cacheKey:""};return{...u,cacheKey:gr(u)}},Ei=(r,i)=>{sr(r.inputs),r.compute(En("AveragePool",r.inputs[0],!1,i))},vn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ln=r=>{let i=r.format;return{format:i,...vn,cacheKey:i}},bn=(r,i)=>{sr(r.inputs),r.compute(En("GlobalAveragePool",r.inputs[0],!0,i))},Ws=(r,i,s,u)=>{let[c,p]=$r(i,u,s),d=` + value = max(x_val, value); + `,b="",T=gt("x",i.dataType,i.dims.length),E=["rank"],[q,H,v,ne,re]=dr(p,c);return q.push(...Ct(i.dims,p)),{name:r,shaderCache:{hint:`${u.cacheKey};${v};${ne};${re}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:p,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(st.size(p)/64)},programUniforms:q}),getShaderSource:ce=>_r(ce,T,i.dims.length,p.length,c,d,b,i.dataType===10?-65504:-1e5,H,v,ne,re)}},Gs=(r,i)=>{sr(r.inputs),r.compute(Ws("MaxPool",r.inputs[0],!1,i))},Ml=r=>{let i=r.storage_order,s=r.dilations,u=Dr(r);if(i!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(u.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let c={storageOrder:i,dilations:s,...u,cacheKey:""};return{...c,cacheKey:br(c)}},gm=r=>{let i=r.format;return{format:i,...vn,cacheKey:i}},pi=(r,i)=>{sr(r.inputs),r.compute(Ws("GlobalMaxPool",r.inputs[0],!0,i))}}),Tp,kp,Sp,tf,J2=h(()=>{Xt(),Yt(),mr(),or(),Tp=(r,i)=>{if(r.length<2||r.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(r.length===3&&r[1].dims===r[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(r.length===3&&r[0].dataType!==r[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(r[0].dataType===6&&r.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(r[1].dims.length!==0&&r[1].dims.length!==1&&r[1].dims.length!==r[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(r.length>2){if(r[0].dataType!==r[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(r[1].dims.length!==r[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!r[1].dims.map((s,u)=>s===r[2].dims[u]).reduce((s,u)=>s&&u,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(i.blockSize>0){if(r[1].dims.length===0||r[1].dims.length===1&&r[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!r[1].dims.map((c,p)=>p===i.axis||c===r[0].dims[p]).reduce((c,p)=>c&&p,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(r[1].dims.length!==r[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=r[0].dims[i.axis],u=r[1].dims[i.axis];if(i.blockSize<Math.ceil(s/u)||i.blockSize>Math.ceil(s/(u-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},kp=(r,i)=>{let s=st.normalizeAxis(i.axis,r[0].dims.length),u=r[0].dataType,c=u===3,p=r[0].dims,d=r[1].dataType,b=st.size(p),T=u===3||u===2,E=T?[Math.ceil(st.size(r[0].dims)/4)]:r[0].dims,q=r[1].dims,H=r.length>2?r[2]:void 0,v=H?T?[Math.ceil(st.size(H.dims)/4)]:H.dims:void 0,ne=q.length===0||q.length===1&&q[0]===1,re=ne===!1&&q.length===1,ce=wr(b),_e=ne&&(!T||ce===4),be=_e?ce:1,he=_e&&!T?ce:1,Fe=gt("input",T?12:u,E.length,he),xe=gt("scale",d,q.length),Ie=H?gt("zero_point",T?12:u,v.length):void 0,ct=Vt("output",d,p.length,be),et=[Fe,xe];Ie&&et.push(Ie);let vt=[E,q];H&&vt.push(v);let Ft=[{type:12,data:b/be},{type:12,data:s},{type:12,data:i.blockSize},...Ct(...vt,p)],Lt=pr=>{let ar=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${pr.registerUniforms(ar).declareVariables(...et,ct)} + ${pr.mainStart()} + ${pr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${ct.offsetToIndices("global_idx")}; + + // Set input x + ${T?` + let input = ${Fe.getByOffset("global_idx / 4")}; + let x_vec = ${c?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${be===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${Fe.getByOffset("global_idx")};`}; + + // Set scale input + ${ne?`let scale_value= ${xe.getByOffset("0")}`:re?` + let scale_index = ${ct.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${xe.getByOffset("scale_index")};`:` + var scale_indices: ${xe.type.indices} = output_indices; + let index = ${xe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${xe.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${xe.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Ie?ne?T?` + let zero_point_input = ${Ie.getByOffset("0")}; + let zero_point_vec = ${c?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Ie.getByOffset("0")}`:re?T?` + let zero_point_index = ${ct.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${Ie.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${c?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${ct.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Ie.getByOffset("zero_point_index")};`:T?` + let zero_point_offset = ${xe.indicesToOffset("scale_indices")}; + let zero_point_input = ${Ie.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${c?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Ie.getByIndices("scale_indices")};`:`let zero_point_value = ${T?c?"i32":"u32":Fe.type.value}(0);`}; + // Compute and write output + ${ct.setByOffset("global_idx",`${ct.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:i.cacheKey,inputDependencies:Ie?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Lt,getRunData:()=>({outputs:[{dims:p,dataType:d}],dispatchGroup:{x:Math.ceil(b/be/64),y:1,z:1},programUniforms:Ft})}},Sp=(r,i)=>{Tp(r.inputs,i),r.compute(kp(r.inputs,i))},tf=r=>Gt({axis:r.axis,blockSize:r.blockSize})}),_0,y0,w0,ex=h(()=>{Z(),Xt(),or(),_0=(r,i,s)=>{let u=r===i,c=r<i&&s<0,p=r>i&&s>0;if(u||c||p)throw new Error("Range these inputs' contents are invalid.")},y0=(r,i,s,u)=>{let c=Math.abs(Math.ceil((i-r)/s)),p=[c],d=c,b=[{type:12,data:d},{type:u,data:r},{type:u,data:s},...Ct(p)],T=E=>{let q=Vt("output",u,p.length),H=q.type.value,v=[{name:"outputSize",type:"u32"},{name:"start",type:H},{name:"delta",type:H}];return` + ${E.registerUniforms(v).declareVariables(q)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${H}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${u}`},getShaderSource:T,getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:b})}},w0=r=>{let i=0,s=0,u=0;r.inputs[0].dataType===6?(i=r.inputs[0].getInt32Array()[0],s=r.inputs[1].getInt32Array()[0],u=r.inputs[2].getInt32Array()[0]):r.inputs[0].dataType===1&&(i=r.inputs[0].getFloat32Array()[0],s=r.inputs[1].getFloat32Array()[0],u=r.inputs[2].getFloat32Array()[0]),D.webgpu.validateInputContent&&_0(i,s,u),r.compute(y0(i,s,u,r.inputs[0].dataType),{inputs:[]})}}),v0,b0,x0,M0,T0,k0,S0,E0,C0,P0,$0,_m,A0,I0,F0,z0,O0,D0,L0,tx=h(()=>{Xt(),Yt(),mr(),or(),v0=(r,i)=>{if(r.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),r.length>0){if(i.mode==="linear"){if(!(r.length===2||r.length===3||r.length===4&&r[0]===1&&r[1]===1||r.length===4&&r[0]===1&&r[3]===1||r.length===5&&r[0]===1&&r[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(i.mode==="cubic"&&!(r.length===2||r.length===4&&r[0]===1&&r[1]===1||r.length===4&&r[0]===1&&r[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},b0=(r,i,s)=>{i.every(c=>c>=0&&c<s||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let u=new Array(s).fill(1);return i.forEach((c,p)=>u[c]=r[p]),u},x0=(r,i,s,u,c,p)=>{let[d,b,T]=s>10?[1,2,3]:[-1,r.length>1?1:-1,-1],E=r[0].dims.length;if(d>0&&r.length>d&&r[d].dims.length>0)r[d].getFloat32Array().forEach(q=>p.push(q));else if(i.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(b>0&&r.length>b&&r[b].dims.length>0){if(r[b].getFloat32Array().forEach(q=>u.push(q)),u.length!==0&&u.length!==E&&s>=18&&u.length!==i.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");v0(u,i),i.axes.length>0&&b0(u,i.axes,E).forEach((q,H)=>u[H]=q)}if(T>0&&r.length>T&&(r[T].getBigInt64Array().forEach(q=>c.push(Number(q))),c.length!==E||s>=18&&c.length===i.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(i.axes.length>0){if(u.length!==i.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(c.length!==i.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof u<"u"&&typeof c<"u"&&u.length>0&&c.length>E)throw new Error("Resize requires only of scales or sizes to be specified")},M0=(r,i)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${i} { `+(()=>{switch(r){case"asymmetric":return`return ${i}(xResized) / ${i}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${i}(xResized) + 0.5) / ${i}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${i}(xResized) + 0.5) / ${i}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let whole = ${i}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); + let fract = + ${i}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${i}(lengthResized - 1); + return whole + fract; + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${i}(roiStart) * ${i}(lengthOriginal - 1) + + (${i}(xResized) * ${i}(roiEnd - roiStart) * ${i}(lengthOriginal - 1)) / + ${i}(lengthResized - 1); + } else { + return 0.5 * ${i}(roiStart + roiEnd) * ${i}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${i}xScale * ${i}(lengthResized); + const adjustment = ${i}(lengthResized) / outputWidth; + const center = ${i}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${i}(xResized) + 0.5) / ${i}(xScale)) - 0.5;`;case"half_pixel":return`return ((${i}(xResized) + 0.5) / ${i}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${r} is not supported`)}})()+"}",T0=(r,i,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(r){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(i<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${r} is not supported`)}})()+"}",k0=(r,i,s)=>{let u=new Array(s).fill(0).concat(new Array(s).fill(1)),c=r.length===0?u:r.slice();return i.length>0?(i.forEach((p,d)=>{u[p]=c[d],u[d+s]=c[i.length+d]}),u):c},S0=(r,i,s,u)=>{let c=[];if(s.length>0)if(u.length>0){if(r.forEach(p=>c.push(p)),Math.max(...u)>r.length)throw new Error("axes is out of bound");u.forEach((p,d)=>c[p]=s[d])}else s.forEach(p=>c.push(p));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");c=r.map((p,d)=>Math.round(p*i[d]))}return c},E0=(r,i,s)=>{let u=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(p=>i[p]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(p=>i[p]),Number.MIN_VALUE):Math.max(...i,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();i.fill(1,0,i.length);let c=r.slice();return s.axes.length>0?(s.axes.forEach(p=>i[p]=u),s.axes.forEach(p=>c[p]=Math.round(r[p]*i[p]))):(i.fill(u,0,i.length),c.forEach((p,d)=>c[d]=Math.round(p*i[d]))),c},C0=(r,i,s,u,c)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> array<${r.type.value}, ${s.length}> { + var original_indices: array<${r.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var scale = ${Dt("uniforms.scales","i",u)}; + var roi_low = ${Dt("uniforms.roi","i",c)}; + var roi_hi = ${Dt("uniforms.roi",`i + ${i.length}`,c)}; + if (scale == 1.0) { + original_indices[i] = ${r.type.value}(output_index); + } else { + var input_shape_i = ${Dt("uniforms.input_shape","i",i.length)}; + var output_shape_i = ${Dt("uniforms.output_shape","i",s.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,P0=(r,i,s,u,c,p,d)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${i.type.indices}) -> ${r.type.indices} { + var input_indices: ${r.type.indices}; + for (var i:u32 = 0; i < ${u.length}; i++) { + var output_index = ${i.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Dt("uniforms.scales","i",c)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Dt("uniforms.roi","i",p)}; + var roi_hi = ${Dt("uniforms.roi",`i + ${s.length}`,p)}; + var input_shape_i = ${Dt("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Dt("uniforms.output_shape","i",u.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${d} || (original_idx >= 0 && original_idx < ${i.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${i.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${r.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,$0=(r,i)=>` + fn checkInputIndices(input_indices: ${r.type.indices}) -> bool { + for (var i:u32 = 0; i < ${i.length}; i++) { + var input_index = ${r.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${Dt("uniforms.input_shape","i",i.length)}) { + return false; + } + } + return true; + }`,_m=(r,i,s,u)=>r.rank>u?` + ${r.indicesSet("input_indices",i,"channel")}; + ${r.indicesSet("input_indices",s,"batch")}; +`:"",A0=(r,i,s,u,c)=>{let[p,d,b,T]=s.length===2?[-1,0,1,-1]:[0,2,3,1],E=r.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${E} { + var input_indices: ${r.type.indices}; + ${r.indicesSet("input_indices",d,`max(0, min(row, ${s[d]} - 1))`)}; + ${r.indicesSet("input_indices",b,`max(0, min(col, ${s[b]} - 1))`)}; + ${_m(r,T,p,2)} + return ${r.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${i.type.indices}) -> ${E} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${E} = originalIndices[${d}]; + var col:${E} = originalIndices[${b}]; + ${u?`if (row < 0 || row > (${s[d]} - 1) || col < 0 || col > (${s[b]} - 1)) { + return ${c}; + }`:""}; + row = max(0, min(row, ${s[d]} - 1)); + col = max(0, min(col, ${s[b]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${s.length>2?`u32(originalIndices[${T}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; + var x11: ${E} = getInputValue(batch, channel, row1, col1); + var x12: ${E} = getInputValue(batch, channel, row1, col2); + var x21: ${E} = getInputValue(batch, channel, row2, col1); + var x22: ${E} = getInputValue(batch, channel, row2, col2); + var dx1: ${E} = abs(row - ${E}(row1)); + var dx2: ${E} = abs(${E}(row2) - row); + var dy1: ${E} = abs(col - ${E}(col1)); + var dy2: ${E} = abs(${E}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},I0=(r,i,s,u,c,p,d,b,T,E)=>{let q=s.length===2,[H,v]=q?[0,1]:[2,3],ne=r.type.value,re=ce=>{let _e=ce===H?"row":"col";return` + fn ${_e}CubicInterpolation(input_indices: ${r.type.indices}, output_indices: ${i.type.indices}) -> ${ne} { + var output_index = ${i.indicesGet("output_indices",ce)}; + var originalIdx: ${ne} = getOriginalCoordinateFromResizedCoordinate(output_index, ${c[ce]}, + ${u[ce]}, ${s[ce]}, ${p[ce]}, ${p[ce]} + ${s.length}); + var fractOriginalIdx: ${ne} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${b} && (originalIdx < 0 || originalIdx > (${s[ce]} - 1))) { + return ${T}; + } + var data: array<${ne}, 4> = array<${ne}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${_e}: ${ne} = originalIdx + ${ne}(i); + if (${_e} < 0 || ${_e} >= ${s[ce]}) { + ${E?`coefs[i + 1] = 0.0; + continue;`:b?`return ${T};`:`${_e} = max(0, min(${_e}, ${s[ce]} - 1));`}; + } + var input_indices_copy: ${r.type.indices} = input_indices; + ${r.indicesSet("input_indices_copy",ce,`u32(${_e})`)}; + data[i + 1] = ${ce===H?r.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${re(H)}; + ${re(v)}; + fn getCubicInterpolationCoefs(s: ${ne}) -> array<${ne}, 4> { + var absS = abs(s); + var coeffs: array<${ne}, 4> = array<${ne}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${ne} = 1.0 - absS; + var twoMinusAbsS: ${ne} = 2.0 - absS; + var onePlusAbsS: ${ne} = 1.0 + absS; + coeffs[0] = ((${d} * onePlusAbsS - 5 * ${d}) * onePlusAbsS + 8 * ${d}) * onePlusAbsS - 4 * ${d}; + coeffs[1] = ((${d} + 2) * absS - (${d} + 3)) * absS * absS + 1; + coeffs[2] = ((${d} + 2) * oneMinusAbsS - (${d} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${d} * twoMinusAbsS - 5 * ${d}) * twoMinusAbsS + 8 * ${d}) * twoMinusAbsS - 4 * ${d}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${ne}, 4>, coefs: array<${ne}, 4>) -> ${ne} { + var coefsSum: ${ne} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${i.type.indices}) -> ${ne} { + var input_indices: ${r.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},F0=(r,i,s,u,c)=>{let[p,d,b,T,E]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],q=r.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${q} { + var input_indices: ${r.type.indices}; + ${r.indicesSet("input_indices",d,`max(0, min(depth, ${s[d]} - 1))`)}; + ${r.indicesSet("input_indices",b,`max(0, min(height, ${s[b]} - 1))`)}; + ${r.indicesSet("input_indices",T,`max(0, min(width, ${s[T]} - 1))`)}; + ${_m(r,E,p,3)} + return ${r.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${i.type.indices}) -> ${q} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${q} = originalIndices[${d}]; + var height:${q} = originalIndices[${b}]; + var width:${q} = originalIndices[${T}]; + ${u?`if (depth < 0 || depth > (${s[d]} - 1) || height < 0 || height > (${s[b]} - 1) || width < 0 || (width > ${s[T]} - 1)) { + return ${c}; + }`:""}; + + depth = max(0, min(depth, ${s[d]} - 1)); + height = max(0, min(height, ${s[b]} - 1)); + width = max(0, min(width, ${s[T]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${s.length>3?`u32(originalIndices[${E}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${p}])`:"0"}; + + var x111: ${q} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${q} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${q} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${q} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${q} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${q} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${q} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${q} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${q} = abs(depth - ${q}(depth1)); + var dx2: ${q} = abs(${q}(depth2) - depth); + var dy1: ${q} = abs(height - ${q}(height1)); + var dy2: ${q} = abs(${q}(height2) - height); + var dz1: ${q} = abs(width - ${q}(width1)); + var dz2: ${q} = abs(${q}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},z0=(r,i,s,u,c,p)=>{let d=r.dims,b=k0(p,i.axes,d.length),T=S0(d,u,c,i.axes),E=u.slice();u.length===0&&(E=d.map((he,Fe)=>he===0?1:T[Fe]/he),i.keepAspectRatioPolicy!=="stretch"&&(T=E0(d,E,i)));let q=Vt("output",r.dataType,T.length),H=gt("input",r.dataType,d.length),v=st.size(T),ne=d.length===T.length&&d.every((he,Fe)=>he===T[Fe]),re=i.coordinateTransformMode==="tf_crop_and_resize",ce=i.extrapolationValue,_e=H.type.value,be=he=>` + ${ne?"":` + ${M0(i.coordinateTransformMode,_e)}; + ${(()=>{switch(i.mode){case"nearest":return` + ${$0(H,d)}; + ${T0(i.nearestMode,s,_e)}; + ${P0(H,q,d,T,E.length,b.length,re)}; + `;case"linear":return` + ${C0(q,d,T,E.length,b.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${A0(H,q,d,re,ce)}`;if(d.length===3||d.length===5)return`${F0(H,q,d,re,ce)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(d.length===2||d.length===4)return`${I0(H,q,d,T,E,b,i.cubicCoeffA,re,i.extrapolationValue,i.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${he.registerUniform("output_size","u32").registerUniform("scales","f32",E.length).registerUniform("roi","f32",b.length).declareVariables(H,q)} + ${he.mainStart()} + ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${ne?"output[global_idx] = input[global_idx];":` + let output_indices = ${q.offsetToIndices("global_idx")}; + var input_indices: ${H.type.indices}; + ${(()=>{switch(i.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${H.getByIndices("input_indices")}; + } else { + output[global_idx] = ${i.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${d.length===2||d.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${i.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${i.cacheKey}|${s}|${E.length>0?E:""}|${c.length>0?c:""}|${b.length>0?b:""}|${ne}|${d}`,inputDependencies:["rank"]},getShaderSource:be,getRunData:()=>({outputs:[{dims:T,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},{type:1,data:E},{type:1,data:b},...Ct(d,T)]})}},O0=r=>{let i=r.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},D0=(r,i)=>{let s=[],u=[],c=[],p=O0(r);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");x0(r.inputs,i,p,s,u,c),r.compute(z0(r.inputs[0],i,p,s,u,c),{inputs:[0]})},L0=r=>{let i=r.antialias,s=r.axes,u=r.coordinateTransformMode,c=r.cubicCoeffA,p=r.excludeOutside!==0,d=r.extrapolationValue,b=r.keepAspectRatioPolicy,T=r.mode,E=r.nearestMode===""?"simple":r.nearestMode;return Gt({antialias:i,axes:s,coordinateTransformMode:u,cubicCoeffA:c,excludeOutside:p,extrapolationValue:d,keepAspectRatioPolicy:b,mode:T,nearestMode:E})}}),R0,B0,N0,rx=h(()=>{Xt(),Yt(),mr(),or(),R0=(r,i)=>{let[s,u,c,p]=r,{numHeads:d,rotaryEmbeddingDim:b}=i;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!st.areEqual(u.dims,[])&&!st.areEqual(u.dims,[1])&&u.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${u.dims.length}`);if(c.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${c.dims.length}`);if(p.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${p.dims.length}`);if(!st.areEqual(c.dims,p.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(b>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let T=s.dims[0],E=s.dims[s.dims.length-2],q=c.dims[0],H=st.sizeFromDimension(s.dims,1)/E,v=b===0?c.dims[1]*2:H/d;if(b>v)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(u.dims.length===2){if(T!==u.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${u.dims[0]}`);if(E!==u.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${u.dims[1]}`)}if(v/2!==c.dims[1]&&b/2!==c.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${c.dims[1]}`);if(E>q)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},B0=(r,i)=>{let{interleaved:s,numHeads:u,rotaryEmbeddingDim:c,scale:p}=i,d=r[0].dims[0],b=st.sizeFromDimension(r[0].dims,1),T=r[0].dims[r[0].dims.length-2],E=b/T,q=r[2].dims[1],H=c===0?q*2:E/u,v=new Array(d,T,E/H,H-q),ne=st.computeStrides(v),re=[{type:1,data:p},{type:12,data:v},{type:12,data:ne},...r[0].dims.length===3?new Array({type:12,data:[b,E,H,1]}):[],...r[0].dims.length===4?new Array({type:12,data:[b,H,T*H,1]}):[],...Ct(r[0].dims,r[1].dims,r[2].dims,r[3].dims,r[0].dims)],ce=_e=>{let be=gt("input",r[0].dataType,r[0].dims.length),he=gt("position_ids",r[1].dataType,r[1].dims.length),Fe=gt("cos_cache",r[2].dataType,r[2].dims.length),xe=gt("sin_cache",r[3].dataType,r[3].dims.length),Ie=Vt("output",r[0].dataType,r[0].dims.length);return _e.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:v.length},{name:"global_strides",type:"u32",length:ne.length},{name:"input_output_strides",type:"u32",length:ne.length}]),` + ${_e.declareVariables(be,he,Fe,xe,Ie)} + + ${_e.mainStart(Bn)} + let half_rotary_emb_dim = uniforms.${Fe.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${_e.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${he.broadcastedIndicesToOffset("bsnh.xy",Vt("",he.type.tensor,2))}; + let position_id = + u32(${he.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); + let j = i + select(half_rotary_emb_dim, 1, ${s}); + let re = ${be.getByOffset("i")} * ${Fe.get("position_id","bsnh[3]")} - + ${be.getByOffset("j")} * ${xe.get("position_id","bsnh[3]")}; + ${Ie.setByOffset("i","re")} + let im = ${be.getByOffset("i")} * ${xe.get("position_id","bsnh[3]")} + + ${be.getByOffset("j")} * ${Fe.get("position_id","bsnh[3]")}; + ${Ie.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${Ie.setByOffset("k",be.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Gt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:ce,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(st.size(v)/Bn)},programUniforms:re})}},N0=(r,i)=>{R0(r.inputs,i),r.compute(B0(r.inputs,i))}}),j0,U0,V0,nx=h(()=>{Xt(),Yt(),or(),j0=r=>{if(!r||r.length<3)throw new Error("layerNorm requires at least 3 inputs.");let i=r[0],s=r[1],u=r[2];if(i.dataType!==s.dataType||i.dataType!==u.dataType)throw new Error("All inputs must have the same data type");if(i.dims.length!==3&&i.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let c=i.dims[i.dims.length-1],p=i.dims[i.dims.length-2];if(s.dims[s.dims.length-1]!==c)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==p)throw new Error("Skip must have the same sequence length as input");if(u.dims.length!==1)throw new Error("Gamma must be 1D");if(u.dims[u.dims.length-1]!==c)throw new Error("Gamma must have the same hidden size as input");if(r.length>3){let d=r[3];if(d.dims.length!==1)throw new Error("Beta must be 1D");if(d.dims[d.dims.length-1]!==c)throw new Error("Beta must have the same hidden size as input")}if(r.length>4){let d=r[4];if(d.dims.length!==1)throw new Error("Bias must be 1D");if(d.dims[d.dims.length-1]!==c)throw new Error("Bias must have the same hidden size as input")}},U0=(r,i,s,u)=>{let c=i.simplified,p=r[0].dims,d=st.size(p),b=p,T=d,E=p.slice(-1)[0],q=u?p.slice(0,-1).concat(1):[],H=!c&&r.length>3,v=r.length>4,ne=u&&s>1,re=u&&s>2,ce=s>3,_e=64,be=wr(E),he=[{type:12,data:T},{type:12,data:be},{type:12,data:E},{type:1,data:i.epsilon}],Fe=Ie=>{let ct=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],et=[gt("x",r[0].dataType,r[0].dims,be),gt("skip",r[1].dataType,r[1].dims,be),gt("gamma",r[2].dataType,r[2].dims,be)];H&&et.push(gt("beta",r[3].dataType,r[3].dims,be)),v&&et.push(gt("bias",r[4].dataType,r[4].dims,be)),et.push(Vt("output",r[0].dataType,b,be)),ne&&et.push(Vt("mean_output",1,q)),re&&et.push(Vt("inv_std_output",1,q)),ce&&et.push(Vt("input_skip_bias_sum",r[0].dataType,b,be));let vt=Tr(r[0].dataType),Ft=Tr(1,be);return` + + ${Ie.registerUniforms(ct).declareVariables(...et)} + var<workgroup> sum_shared : array<${Ft}, ${_e}>; + var<workgroup> sum_squared_shared : array<${Ft}, ${_e}>; + + ${Ie.mainStart([_e,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${_e}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${_e}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${_e-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${v?"bias[offset1d + i]":vt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${ce?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Gr(vt,be,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${_e}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Nn("sum",be)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Nn("square_sum",be)} / f32(uniforms.hidden_size) ${c?"":"- mean * mean"} + uniforms.epsilon); + ${ne?"mean_output[global_idx] = mean;":""} + ${re?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${c?"":`- ${vt}(mean)`}) * + ${vt}(inv_std_dev) * gamma[offset1d + i] + ${H?"+ beta[offset1d + i]":""}; + } + }`},xe=[{dims:b,dataType:r[0].dataType}];return s>1&&xe.push({dims:q,dataType:1}),s>2&&xe.push({dims:q,dataType:1}),s>3&&xe.push({dims:p,dataType:r[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${be};${ne};${re};${ce}`,inputDependencies:r.map((Ie,ct)=>"type")},getShaderSource:Fe,getRunData:()=>({outputs:xe,dispatchGroup:{x:Math.ceil(T/E)},programUniforms:he})}},V0=(r,i)=>{j0(r.inputs);let s=[0];r.outputCount>1&&s.push(-3),r.outputCount>2&&s.push(-3),r.outputCount>3&&s.push(3),r.compute(U0(r.inputs,i,r.outputCount,!1),{outputs:s})}}),W0,rf,G0,ym,q0,H0,K0,Q0,ix=h(()=>{Xt(),Yt(),mr(),or(),W0=(r,i)=>{if(!r||r.length<1)throw new Error("too few inputs");if(i.axes.length!==0){if(i.axes.length!==i.starts.length||i.axes.length!==i.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(i.starts.length!==i.ends.length)throw new Error("starts and ends must have the same length");r.slice(1).forEach((s,u)=>{if(r[u+1].dataType!==6&&r[u+1].dataType!==7)throw new Error(`Input ${u} must be an array of int32 or int64`)})},rf=(r,i)=>{let s=[];if(r.length>i)if(r[i].dataType===7)r[i].getBigInt64Array().forEach(u=>s.push(Number(u)));else if(r[i].dataType===6)r[i].getInt32Array().forEach(u=>s.push(Number(u)));else throw new Error(`Input ${i} must be an array of int32 or int64`);return s},G0=(r,i)=>{if(r.length>1){let s=rf(r,1),u=rf(r,2),c=rf(r,3);return c.length===0&&(c=[...Array(r[0].dims.length).keys()]),Gt({starts:s,ends:u,axes:c})}else return i},ym=(r,i,s,u,c)=>{let p=r;return r<0&&(p+=s[u[i]]),c[i]<0?Math.max(0,Math.min(p,s[u[i]]-1)):Math.max(0,Math.min(p,s[u[i]]))},q0=(r,i,s)=>`fn calculateInputIndices(output_indices: ${i.type.indices}) -> ${r.type.indices} { + var input_indices: ${r.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${Dt("uniforms.input_shape","i",s.length)}; + let steps_i = ${Dt("uniforms.steps","i",s.length)}; + let signs_i = ${Dt("uniforms.signs","i",s.length)}; + let starts_i = ${Dt("uniforms.starts","i",s.length)}; + var output_index = ${i.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${r.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,H0=(r,i)=>{let s=r[0].dims,u=st.size(s),c=i.axes.length>0?st.normalizeAxes(i.axes,s.length):[...Array(s.length).keys()],p=rf(r,4);p.forEach(be=>be!==0||(()=>{throw new Error("step cannot be 0")})),p.length===0&&(p=Array(c.length).fill(1));let d=i.starts.map((be,he)=>ym(be,he,s,c,p)),b=i.ends.map((be,he)=>ym(be,he,s,c,p));if(c.length!==d.length||c.length!==b.length)throw new Error("start, ends and axes should have the same number of elements");if(c.length!==s.length)for(let be=0;be<s.length;++be)c.includes(be)||(d.splice(be,0,0),b.splice(be,0,s[be]),p.splice(be,0,1));let T=p.map(be=>Math.sign(be));p.forEach((be,he,Fe)=>{if(be<0){let xe=(b[he]-d[he])/be,Ie=d[he],ct=Ie+xe*p[he];d[he]=ct,b[he]=Ie,Fe[he]=-be}});let E=s.slice(0);c.forEach((be,he)=>{E[be]=Math.ceil((b[be]-d[be])/p[be])});let q={dims:E,dataType:r[0].dataType},H=Vt("output",r[0].dataType,E.length),v=gt("input",r[0].dataType,r[0].dims.length),ne=st.size(E),re=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:T.length},{name:"steps",type:"u32",length:p.length}],ce=[{type:12,data:ne},{type:12,data:d},{type:6,data:T},{type:12,data:p},...Ct(r[0].dims,E)],_e=be=>` + ${be.registerUniforms(re).declareVariables(v,H)} + ${q0(v,H,s)} + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${H.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${H.setByOffset("global_idx",v.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${T.length}_${d.length}_${p.length}`,inputDependencies:["rank"]},getShaderSource:_e,getRunData:()=>({outputs:[q],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:ce})}},K0=(r,i)=>{W0(r.inputs,i);let s=G0(r.inputs,i);r.compute(H0(r.inputs,s),{inputs:[0]})},Q0=r=>{let i=r.starts,s=r.ends,u=r.axes;return Gt({starts:i,ends:s,axes:u})}}),X0,Y0,Z0,J0,ox=h(()=>{Xt(),Yt(),mr(),or(),X0=r=>{if(!r||r.length!==1)throw new Error("Softmax op requires 1 input.")},Y0=(r,i)=>{let s=r.dims,u=st.size(s),c=64,p=i.axis;if(p<0&&(p=s.length+p),p<s.length-1)throw new Error("softmax only supports last axis for now.");let d=s[p],b=u/d,T=wr(d),E=d/T,q=(_e,be)=>be===4?`max(max(${_e}.x, ${_e}.y), max(${_e}.z, ${_e}.w))`:be===2?`max(${_e}.x, ${_e}.y)`:be===3?`max(max(${_e}.x, ${_e}.y), ${_e}.z)`:_e,H=gt("x",r.dataType,r.dims,T),v=Vt("result",r.dataType,r.dims,T),ne=H.type.value,re=Tr(r.dataType)==="f32"?`var threadMax = ${ne}(-3.402823e+38f);`:`var threadMax = ${ne}(-65504.0h);`,ce=_e=>` + var<workgroup> rowMaxShared : ${ne}; + var<workgroup> rowSumShared : ${ne}; + var<workgroup> threadShared : array<${ne}, ${c}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${ne} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${ne}) { + let index = row * row_stride + col; + result[index] = value; + } + ${_e.registerUniform("packedCols","i32").declareVariables(H,v)} + ${_e.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${c}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${re} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${ne}(${q("threadShared[0]",T)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${ne}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${ne}(${Nn("threadShared[0]",T)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`;return{name:"Softmax",shaderCache:{hint:`${T}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:s,dataType:r.dataType}],dispatchGroup:{x:b},programUniforms:[{type:6,data:E}]}),getShaderSource:ce}},Z0=(r,i)=>{X0(r.inputs),r.compute(Y0(r.inputs[0],i))},J0=r=>Gt({axis:r.axis})}),ey,ty,ry,ny,iy,oy,sy,sx=h(()=>{Xt(),Yt(),mr(),or(),ey=r=>{if(!r||r.length<1)throw new Error("too few inputs")},ty=(r,i)=>{let s=[],u=i.numOutputs;return r[1].dims[0]>0&&(r[1].getBigInt64Array().forEach(c=>s.push(Number(c))),u=s.length),Gt({numOutputs:u,axis:i.axis,splitSizes:s})},ry=r=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${r}u; i += 1u ) { + if (index < ${Dt("uniforms.size_in_split_axis","i",r)}) { + return i; + } + } + return ${r}u; +}`,ny=r=>{let i=r.length,s=[];for(let u=0;u<i;++u){let c=r[u].setByIndices("indices","input[global_idx]");i===1?s.push(c):u===0?s.push(`if (output_number == ${u}u) { ${c} }`):u===i-1?s.push(`else { ${c} }`):s.push(`else if (output_number == ${u}) { ${c} }`)}return` + fn writeBufferData(output_number: u32, indices: ${r[0].type.indices}, global_idx: u32) { + ${s.join(` +`)} + }`},iy=(r,i)=>{let s=r[0].dims,u=st.size(s),c=r[0].dataType,p=st.normalizeAxis(i.axis,s.length),d=new Array(i.numOutputs),b=gt("input",c,s.length),T=new Array(i.numOutputs),E=[],q=[],H=0,v=[{type:12,data:u}];for(let re=0;re<i.numOutputs;re++){H+=i.splitSizes[re],T[re]=H;let ce=s.slice();ce[p]=i.splitSizes[re],q.push(ce),d[re]=Vt(`output${re}`,c,ce.length),E.push({dims:q[re],dataType:r[0].dataType})}v.push({type:12,data:T},...Ct(s,...q));let ne=re=>` + ${re.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",T.length).declareVariables(b,...d)} + ${ry(T.length)} + ${ny(d)} + + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${b.offsetToIndices("global_idx")}; + var index = ${b.indicesGet("indices",p)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Dt("uniforms.size_in_split_axis","output_number - 1u",T.length)}; + ${b.indicesSet("indices",p,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getShaderSource:ne,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:v})}},oy=(r,i)=>{ey(r.inputs);let s=r.inputs.length===1?i:ty(r.inputs,i);r.compute(iy(r.inputs,s),{inputs:[0]})},sy=r=>{let i=r.axis,s=r.splitSizes,u=r.numOutputs<0?s.length:r.numOutputs;if(u!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Gt({axis:i,numOutputs:u,splitSizes:s})}}),ay,ly,uy,ax=h(()=>{Xt(),Yt(),or(),ay=(r,i,s,u,c)=>{let p=Vt("output_data",c,s.length,4),d=gt("a_data",i[1].dataType,i[1].dims.length,4),b=gt("b_data",i[2].dataType,i[2].dims.length,4),T=gt("c_data",i[0].dataType,i[0].dims.length,4),E,q=(H,v,ne)=>`select(${v}, ${H}, ${ne})`;if(!u)E=p.setByOffset("global_idx",q(d.getByOffset("global_idx"),b.getByOffset("global_idx"),T.getByOffset("global_idx")));else{let H=(v,ne,re="")=>{let ce=`a_data[index_a${ne}][component_a${ne}]`,_e=`b_data[index_b${ne}][component_b${ne}]`,be=`bool(c_data[index_c${ne}] & (0xffu << (component_c${ne} * 8)))`;return` + let output_indices${ne} = ${p.offsetToIndices(`global_idx * 4u + ${ne}u`)}; + let offset_a${ne} = ${d.broadcastedIndicesToOffset(`output_indices${ne}`,p)}; + let offset_b${ne} = ${b.broadcastedIndicesToOffset(`output_indices${ne}`,p)}; + let offset_c${ne} = ${T.broadcastedIndicesToOffset(`output_indices${ne}`,p)}; + let index_a${ne} = offset_a${ne} / 4u; + let index_b${ne} = offset_b${ne} / 4u; + let index_c${ne} = offset_c${ne} / 4u; + let component_a${ne} = offset_a${ne} % 4u; + let component_b${ne} = offset_b${ne} % 4u; + let component_c${ne} = offset_c${ne} % 4u; + ${v}[${ne}] = ${re}(${q(ce,_e,be)}); + `};c===9?E=` + var data = vec4<u32>(0); + ${H("data",0,"u32")} + ${H("data",1,"u32")} + ${H("data",2,"u32")} + ${H("data",3,"u32")} + output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:E=` + ${H("output_data[global_idx]",0)} + ${H("output_data[global_idx]",1)} + ${H("output_data[global_idx]",2)} + ${H("output_data[global_idx]",3)} + `}return` + ${r.registerUniform("vec_size","u32").declareVariables(T,d,b,p)} + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${E} + }`},ly=r=>{let i=r[1].dims,s=r[2].dims,u=r[0].dims,c=r[1].dataType,p=!(st.areEqual(i,s)&&st.areEqual(s,u)),d=i,b=st.size(i);if(p){let E=pn.calcShape(pn.calcShape(i,s,!1),u,!1);if(!E)throw new Error("Can't perform where op on the given tensors");d=E,b=st.size(d)}let T=Math.ceil(b/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:E=>ay(E,r,d,p,c),getRunData:()=>({outputs:[{dims:d,dataType:c}],dispatchGroup:{x:Math.ceil(b/64/4)},programUniforms:[{type:12,data:T},...Ct(u,i,s,d)]})}},uy=r=>{r.compute(ly(r.inputs))}}),cy,lx=h(()=>{tp(),Is(),Yu(),rp(),$c(),np(),ip(),sd(),pm(),cp(),dp(),mp(),hm(),_p(),yp(),wp(),Od(),bp(),mm(),yn(),rl(),Mp(),Nd(),cr(),Yo(),J2(),ex(),Sa(),tx(),rx(),nx(),ix(),ox(),sx(),Wd(),_o(),Ua(),ax(),cy=new Map([["Abs",[tc]],["Acos",[rc]],["Acosh",[Pa]],["Add",[Fc]],["ArgMax",[ju,As]],["ArgMin",[Nu,As]],["Asin",[nc]],["Asinh",[ic]],["Atan",[$a]],["Atanh",[oc]],["Attention",[qu]],["AveragePool",[Ei,An]],["BatchNormalization",[Xu]],["BiasAdd",[Ca]],["BiasSplitGelu",[Pc]],["Cast",[Fs,sc]],["Ceil",[uc]],["Clip",[lc]],["Concat",[Ni,Wc]],["Conv",[qo,il]],["ConvTranspose",[up,dd]],["Cos",[Aa]],["Cosh",[cc]],["CumSum",[fl,hd]],["DepthToSpace",[hl,_d]],["DequantizeLinear",[Sp,tf]],["Div",[zc]],["Einsum",[wd,vd]],["Elu",[dc,wo]],["Equal",[Wa]],["Erf",[fc]],["Exp",[Ia]],["Expand",[_l]],["FastGelu",[Md]],["Floor",[pc]],["FusedConv",[qo,il]],["Gather",[Ed,Sd]],["GatherElements",[Ad,$d]],["Gelu",[hc]],["Gemm",[vp,zd]],["GlobalAveragePool",[bn,ln]],["GlobalMaxPool",[pi,gm]],["Greater",[Rc]],["GreaterOrEqual",[Nc]],["GroupQueryAttention",[Kd,qd]],["HardSigmoid",[Oa,wc]],["InstanceNormalization",[Zd]],["LayerNormalization",[dn]],["LeakyRelu",[mc,wo]],["Less",[Bc]],["LessOrEqual",[Ga]],["Log",[ja]],["MatMul",[nd]],["MatMulNBits",[xp,ef]],["MaxPool",[Gs,Ml]],["Mul",[Oc]],["MultiHeadAttention",[Bd,Ld]],["Neg",[gc]],["Not",[Fa]],["Pad",[Wt]],["Pow",[Dc]],["QuickGelu",[Ec,wo]],["Range",[w0]],["Reciprocal",[_c]],["ReduceMin",[Ta]],["ReduceMean",[Fu]],["ReduceMax",[Du]],["ReduceSum",[Ru]],["ReduceProd",[Lu]],["ReduceL1",[zu]],["ReduceL2",[Ma]],["ReduceLogSum",[Bu]],["ReduceLogSumExp",[Ou]],["ReduceSumSquare",[ka]],["Relu",[za]],["Resize",[D0,L0]],["RotaryEmbedding",[N0]],["Sigmoid",[yc]],["Sin",[vc]],["Sinh",[bc]],["Slice",[K0,Q0]],["SkipLayerNormalization",[V0]],["Split",[oy,sy]],["Sqrt",[Da]],["Softmax",[Z0,J0]],["Sub",[Lc]],["Tan",[xc]],["Tanh",[Ra]],["ThresholdedRelu",[Tc,wo]],["Tile",[Vd]],["Transpose",[uu,ha]],["Where",[uy]]])}),dy,ux=h(()=>{Z(),Rn(),or(),dy=class{constructor(r){this.backend=r,this.repo=new Map,this.attributesBound=!1}getArtifact(r){return this.repo.get(r)}setArtifact(r,i){this.repo.set(r,i)}run(r,i,s,u,c){tt(r.programInfo.name);let p=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let b=[];for(let E of i)b.push({binding:b.length,resource:{buffer:E.buffer}});for(let E of s)b.push({binding:b.length,resource:{buffer:E.buffer}});c&&b.push({binding:b.length,resource:c});let T=p.createBindGroup({layout:r.computePipeline.getBindGroupLayout(0),entries:b,label:r.programInfo.name});if(this.backend.sessionStatus==="capturing"){let E={kernelId:this.backend.currentKernelId,computePipeline:r.computePipeline,bindGroup:T,dispatchGroup:u};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(E)}d.setPipeline(r.computePipeline),d.setBindGroup(0,T),d.dispatchWorkgroups(...u),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),A(r.programInfo.name)}dispose(){}build(r,i){tt(r.name);let s=this.backend.device,u=[];s.features.has("shader-f16")&&u.push("enable f16;");let c=su(i,this.backend.device.limits),p=r.getShaderSource(c),d=`${u.join(` +`)} +${c.additionalImplementations} +${p}`,b=s.createShaderModule({code:d,label:r.name});Br("verbose",()=>`[WebGPU] ${r.name} shader code: ${d}`);let T=s.createComputePipeline({compute:{module:b,entryPoint:"main"},layout:"auto",label:r.name});return A(r.name),{programInfo:r,computePipeline:T,uniformVariablesInfo:c.variablesInfo}}normalizeDispatchGroupSize(r){let i=typeof r=="number"?r:r.x,s=typeof r=="number"?1:r.y||1,u=typeof r=="number"?1:r.z||1,c=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(i<=c&&s<=c&&u<=c)return[i,s,u];let p=i*s*u,d=Math.ceil(Math.sqrt(p));if(d>c){if(d=Math.ceil(Math.cbrt(p)),d>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),fy,py,hy,my,cx=h(()=>{Z(),Xt(),Rn(),W(),Pr(),lx(),ux(),fy=(r,i)=>{if(i.length!==r.length)throw new Error(`inputDependencies length ${i.length} is not equal to inputTensors length ${r.length}.`);let s=[];for(let u=0;u<r.length;++u){let c=r[u].dataType;switch(i[u]){case"none":{s.push("");break}case"type":{s.push(`${c}`);break}case"rank":{let p=r[u].dims.length;s.push(`${c};${p}`);break}case"dims":{let p=r[u].dims.join(",");s.push(`${c};${p}`);break}default:throw new Error(`unsupported input dependency: ${i[u]}`)}}return s.join("|")},py=(r,i,s)=>{var c,p;let u=r.name;return(c=r.shaderCache)!=null&&c.hint&&(u+="["+r.shaderCache.hint+"]"),u+=":"+s+`:${fy(i,((p=r.shaderCache)==null?void 0:p.inputDependencies)??new Array(i.length).fill("dims"))}`,u},hy=class{constructor(r){r&&(this.architecture=r.architecture,this.vendor=r.vendor)}isArchitecture(r){return this.architecture===r}isVendor(r){return this.vendor===r}},my=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let r=this.kernelCustomData.get(this.currentKernelId);return r||(r={},this.kernelCustomData.set(this.currentKernelId,r)),r}async initialize(r,i){this.env=r;let s=[],u={requiredLimits:{maxComputeWorkgroupStorageSize:i.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:i.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:i.limits.maxStorageBufferBindingSize,maxBufferSize:i.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:i.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:i.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:i.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:i.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s};i.features.has("chromium-experimental-timestamp-query-inside-passes")?s.push("chromium-experimental-timestamp-query-inside-passes"):i.features.has("timestamp-query")&&s.push("timestamp-query"),i.features.has("shader-f16")&&s.push("shader-f16"),this.device=await i.requestDevice(u),this.adapterInfo=new hy(i.info||await i.requestAdapterInfo()),this.gpuDataManager=Zt(this),this.programManager=new dy(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,mo(r.logLevel,!!r.debug),this.device.onuncapturederror=c=>{c.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${c.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:i,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let r=this.getCommandEncoder(),i={};this.queryType==="at-passes"&&(i.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=r.beginComputePass(i)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;tt(),this.endComputePass();let r;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),r=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(r,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,r,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&r.mapAsync(GPUMapMode.READ).then(()=>{var u;let i=new BigUint64Array(r.getMappedRange()),s=this.pendingQueries.get(r);for(let c=0;c<i.length/2;c++){let p=s[c],d=p.kernelId,b=this.kernels.get(d),T=b.kernelType,E=b.kernelName,q=p.programName,H=p.inputTensorViews,v=p.outputTensorViews,ne=i[c*2],re=i[c*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=ne);let ce=Number(ne-this.queryTimeBase),_e=Number(re-this.queryTimeBase);if(!Number.isSafeInteger(ce)||!Number.isSafeInteger(_e))throw new RangeError("incorrect timestamp range");if((u=this.env.webgpu.profiling)!=null&&u.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:H.map(be=>({dims:be.dims,dataType:di(be.dataType)})),outputsMetadata:v.map(be=>({dims:be.dims,dataType:di(be.dataType)})),kernelId:d,kernelType:T,kernelName:E,programName:q,startTime:ce,endTime:_e});else{let be="";H.forEach((Fe,xe)=>{be+=`input[${xe}]: [${Fe.dims}] | ${di(Fe.dataType)}, `});let he="";v.forEach((Fe,xe)=>{he+=`output[${xe}]: [${Fe.dims}] | ${di(Fe.dataType)}, `}),console.log(`[profiling] kernel "${d}|${T}|${E}|${q}" ${be}${he}execution time: ${_e-ce} ns`)}je("GPU",`${q}::${ne}::${re}`)}r.unmap(),this.pendingQueries.delete(r)}),A()}run(r,i,s,u,c,p){tt(r.name);let d=[];for(let he=0;he<i.length;++he){let Fe=i[he].data;if(Fe===0)continue;let xe=this.gpuDataManager.get(Fe);if(!xe)throw new Error(`no GPU data for input: ${Fe}`);d.push(xe)}let{outputs:b,dispatchGroup:T,programUniforms:E}=r.getRunData(i),q=s.length===0?b.map((he,Fe)=>Fe):s;if(q.length!==b.length)throw new Error(`Output size ${q.length} must be equal to ${b.length}.`);let H=[],v=[];for(let he=0;he<b.length;++he){if(!Number.isInteger(q[he])||q[he]<-3||q[he]>=p)throw new Error(`Invalid output index: ${q[he]}`);if(q[he]===-3)continue;let Fe=q[he]===-1,xe=q[he]===-2,Ie=Fe||xe?c(b[he].dataType,b[he].dims):u(q[he],b[he].dataType,b[he].dims);if(H.push(Ie),Ie.data===0)continue;let ct=this.gpuDataManager.get(Ie.data);if(!ct)throw new Error(`no GPU data for output: ${Ie.data}`);if(Fe&&this.temporaryData.push(ct),xe){let et=this.kernelPersistentData.get(this.currentKernelId);et||(et=[],this.kernelPersistentData.set(this.currentKernelId,et)),et.push(ct)}v.push(ct)}if(d.length!==i.length||v.length!==H.length){if(v.length===0)return A(r.name),H;throw new Error(`Program ${r.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let ne;if(E){let he=0,Fe=[];E.forEach(et=>{let vt=typeof et.data=="number"?[et.data]:et.data;if(vt.length===0)return;let Ft=et.type===10?2:4,Lt,pr;et.type===10?(pr=vt.length>4?16:vt.length>2?8:vt.length*Ft,Lt=vt.length>4?16:Ft*vt.length):(pr=vt.length<=2?vt.length*Ft:16,Lt=16),he=Math.ceil(he/pr)*pr,Fe.push(he);let ar=et.type===10?8:4;he+=vt.length>4?Math.ceil(vt.length/ar)*Lt:vt.length*Ft});let xe=16;he=Math.ceil(he/xe)*xe;let Ie=new ArrayBuffer(he);E.forEach((et,vt)=>{let Ft=Fe[vt],Lt=typeof et.data=="number"?[et.data]:et.data;if(et.type===6)new Int32Array(Ie,Ft,Lt.length).set(Lt);else if(et.type===12)new Uint32Array(Ie,Ft,Lt.length).set(Lt);else if(et.type===10)new Uint16Array(Ie,Ft,Lt.length).set(Lt);else if(et.type===1)new Float32Array(Ie,Ft,Lt.length).set(Lt);else throw new Error(`Unsupported uniform type: ${di(et.type)}`)});let ct=this.gpuDataManager.create(he,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(ct.buffer,0,Ie,0,he),this.gpuDataManager.release(ct.id),ne={offset:0,size:he,buffer:ct.buffer}}let re=this.programManager.normalizeDispatchGroupSize(T),ce=re[1]===1&&re[2]===1,_e=py(r,i,ce),be=this.programManager.getArtifact(_e);if(be||(be=this.programManager.build(r,re),this.programManager.setArtifact(_e,be),Br("info",()=>`[artifact] key: ${_e}, programName: ${r.name}`)),E&&be.uniformVariablesInfo){if(E.length!==be.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${be.uniformVariablesInfo.length}, got ${E.length} in program "${be.programInfo.name}".`);for(let he=0;he<E.length;he++){let Fe=E[he],xe=Fe.type,Ie=typeof Fe.data=="number"?1:Fe.data.length,[ct,et]=be.uniformVariablesInfo[he];if(xe!==ct||Ie!==et)throw new Error(`Uniform variable ${he} mismatch: expect type ${ct} with size ${et}, got type ${xe} with size ${Ie} in program "${be.programInfo.name}".`)}}if(Br("info",()=>`[ProgramManager] run "${r.name}" (key=${_e}) with ${re[0]}x${re[1]}x${re[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let he={kernelId:this.currentKernelId,programName:be.programInfo.name,inputTensorViews:i,outputTensorViews:H};this.pendingKernels.push(he),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(he)}return this.programManager.run(be,d,v,re,ne),A(r.name),H}upload(r,i){this.gpuDataManager.upload(r,i)}memcpy(r,i){this.gpuDataManager.memcpy(r,i)}async download(r,i){await this.gpuDataManager.download(r,i)}alloc(r){return this.gpuDataManager.create(r).id}free(r){return this.gpuDataManager.release(r)}createKernel(r,i,s,u){let c=cy.get(r);if(!c)throw new Error(`kernel not implemented: ${r}`);let p={kernelType:r,kernelName:u,kernelEntry:c[0],attributes:[c[1],s]};this.kernels.set(i,p)}releaseKernel(r){let i=this.kernelPersistentData.get(r);if(i){for(let s of i)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(r)}this.kernelCustomData.delete(r),this.kernels.delete(r)}computeKernel(r,i,s){let u=this.kernels.get(r);if(!u)throw new Error(`kernel not created: ${r}`);let c=u.kernelType,p=u.kernelName,d=u.kernelEntry,b=u.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${p}" is not allowed to be called recursively`);this.currentKernelId=r,b[0]&&(b[1]=b[0](b[1]),b[0]=void 0),Br("info",()=>`[WebGPU] Start to run kernel "[${c}] ${p}"...`);let T=this.env.debug;this.temporaryData=[];try{return T&&this.device.pushErrorScope("validation"),d(i,b[1]),0}catch(E){return s.push(Promise.resolve(`[WebGPU] Kernel "[${c}] ${p}" failed. ${E}`)),1}finally{T&&s.push(this.device.popErrorScope().then(E=>E?`GPU validation error for kernel "[${c}] ${p}": ${E.message}`:null));for(let E of this.temporaryData)this.gpuDataManager.release(E.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(r,i,s,u){let c=this.sessionExternalDataMapping.get(r);c||(c=new Map,this.sessionExternalDataMapping.set(r,c));let p=c.get(i),d=this.gpuDataManager.registerExternalBuffer(s,u,p==null?void 0:p[1]);return c.set(i,[d,s]),d}unregisterBuffers(r){let i=this.sessionExternalDataMapping.get(r);i&&(i.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[1])),this.sessionExternalDataMapping.delete(r))}getBuffer(r){let i=this.gpuDataManager.get(r);if(!i)throw new Error(`no GPU data for buffer: ${r}`);return i.buffer}createDownloader(r,i,s){return async()=>{let u=await Tt(this,r,i);return Ue(u.buffer,s)}}writeTimestamp(r){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,r)}setQueryType(){var r;this.queryType="none",(((r=this.env.webgpu.profiling)==null?void 0:r.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Br("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Br("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Br("info","replay"),this.sessionStatus="replaying";let r=this.capturedCommandList.get(this.currentSessionId),i=this.capturedPendingKernels.get(this.currentSessionId),s=r.length;this.pendingKernels=[];for(let u=0;u<s;u++){let c=this.getComputePassEncoder(),p=r[u];this.writeTimestamp(this.pendingDispatchNumber*2),c.setPipeline(p.computePipeline),c.setBindGroup(0,p.bindGroup),c.dispatchWorkgroups(...p.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(i[u]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(r){this.unregisterBuffers(r),this.capturedCommandList.has(r)&&this.capturedCommandList.delete(r),this.capturedPendingKernels.has(r)&&this.capturedPendingKernels.delete(r),this.gpuDataManager.onReleaseSession(r)}onRunStart(r){this.currentSessionId=r,this.setQueryType()}}}),gy={};g(gy,{init:()=>yy});var Ep,_y,yy,dx=h(()=>{Xt(),cx(),Rn(),Yt(),Ep=class X2{constructor(i,s,u,c){this.module=i,this.dataType=s,this.data=u,this.dims=c}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let i=st.size(this.dims);return i===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,i)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let i=st.size(this.dims);return i===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,i)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let i=st.size(this.dims);return i===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,i)}reshape(i){if(st.size(i)!==st.size(this.dims))throw new Error("Invalid new shape");return new X2(this.module,this.dataType,this.data,i)}},_y=class{constructor(r,i,s){this.module=r,this.backend=i,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=i.adapterInfo;let u=r.HEAPU32,c=s>>>2;this.opKernelContext=u[c++];let p=u[c++];this.outputCount=u[c++],this.customDataOffset=u[c++],this.customDataSize=u[c++];let d=[];for(let b=0;b<p;b++){let T=u[c++],E=u[c++],q=u[c++],H=[];for(let v=0;v<q;v++)H.push(u[c++]);d.push(new Ep(r,T,E,H))}this.inputs=d}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}getMaxComputeWorkgroupSizes(){return[this.backend.device.limits.maxComputeWorkgroupSizeX,this.backend.device.limits.maxComputeWorkgroupSizeY,this.backend.device.limits.maxComputeWorkgroupSizeZ]}getMaxComputeWorkgroupStoragesize(){return this.backend.device.limits.maxComputeWorkgroupStorageSize}compute(r,i){var d;let s=((d=i==null?void 0:i.inputs)==null?void 0:d.map(b=>typeof b=="number"?this.inputs[b]:b))??this.inputs,u=(i==null?void 0:i.outputs)??[],c=(b,T,E)=>new Ep(this.module,T,this.output(b,E),E),p=(b,T)=>{let E=Mi(b,T);if(!E)throw new Error(`Unsupported data type: ${b}`);let q=E>0?this.backend.gpuDataManager.create(E).id:0;return new Ep(this.module,b,q,T)};return this.backend.run(r,s,u,c,p,this.outputCount)}output(r,i){let s=this.module.stackSave();try{let u=this.module.stackAlloc((1+i.length)*4),c=u>>2;this.module.HEAPU32[c++]=i.length;for(let p=0;p<i.length;p++)this.module.HEAPU32[c++]=i[p];return this.module._JsepOutput(this.opKernelContext,r,u)}catch(u){throw new Error(`Failed to generate kernel's output[${r}] with dims [${i}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${u}`)}finally{this.module.stackRestore(s)}}},yy=async(r,i,s,u)=>{let c=i.jsepInit;if(!c)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(r==="webgpu"){let p=new my;await p.initialize(s,u),c("webgpu",[p,d=>p.alloc(d),d=>p.free(d),(d,b,T,E=!1)=>{if(E)Br("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${b}, size=${T}`),p.memcpy(d,b);else{Br("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${b}, size=${T}`);let q=i.HEAPU8.subarray(d>>>0,(d>>>0)+T);p.upload(b,q)}},async(d,b,T)=>{Br("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${b}, size=${T}`),await p.download(d,()=>i.HEAPU8.subarray(b>>>0,(b>>>0)+T))},(d,b,T)=>p.createKernel(d,b,T,i.UTF8ToString(i._JsepGetNodeName(b))),d=>p.releaseKernel(d),(d,b,T,E)=>{Br("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${T}, kernel=${d}, contextDataOffset=${b}`);let q=new _y(i,p,b);return p.computeKernel(d,q,E)},()=>p.captureBegin(),()=>p.captureEnd(),()=>p.replay()])}else c("webnn")}}),wy,wm,vm,Zo,vy,Cp,bm,xm,Mm,Tm,km,Sm,by=h(()=>{ks(),Ss(),Xt(),mn(),Ri(),Bo(),wy=(r,i)=>{Nr()._OrtInit(r,i)!==0&&Fr("Can't initialize onnxruntime.")},wm=async r=>{wy(r.wasm.numThreads,Yi(r.logLevel))},vm=async(r,i)=>{{let s=(dx(),w(gy)).init;if(i==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let u=r.webgpu.adapter;if(u){if(typeof u.limits!="object"||typeof u.features!="object"||typeof u.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let c=r.webgpu.powerPreference;if(c!==void 0&&c!=="low-power"&&c!=="high-performance")throw new Error(`Invalid powerPreference setting: "${c}"`);let p=r.webgpu.forceFallbackAdapter;if(p!==void 0&&typeof p!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${p}"`);if(u=await navigator.gpu.requestAdapter({powerPreference:c,forceFallbackAdapter:p}),!u)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await s("webgpu",Nr(),r,u)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Nr(),r)}}},Zo=new Map,vy=r=>{let i=Nr(),s=i.stackSave();try{let u=i.stackAlloc(8);return i._OrtGetInputOutputCount(r,u,u+4)!==0&&Fr("Can't get session input/output count."),[i.HEAP32[u/4],i.HEAP32[u/4+1]]}finally{i.stackRestore(s)}},Cp=r=>{let i=Nr(),s=i._malloc(r.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${r.byteLength}.`);return i.HEAPU8.set(r,s),[s,r.byteLength]},bm=async(r,i)=>{var H,v;let s,u,c=Nr();Array.isArray(r)?[s,u]=r:r.buffer===c.HEAPU8.buffer?[s,u]=[r.byteOffset,r.byteLength]:[s,u]=Cp(r);let p=0,d=0,b=0,T=[],E=[],q=[];try{if([d,T]=Bi(i),(i==null?void 0:i.externalData)&&c.mountExternalData){let xe=[];for(let Ie of i.externalData){let ct=typeof Ie=="string"?Ie:Ie.path;xe.push(Zi(typeof Ie=="string"?Ie:Ie.data).then(et=>{c.mountExternalData(ct,et)}))}await Promise.all(xe)}for(let xe of(i==null?void 0:i.executionProviders)??[])if((typeof xe=="string"?xe:xe.name)==="webnn"){if(c.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof xe!="string"){let Ie=xe,ct=Ie==null?void 0:Ie.context,et=Ie==null?void 0:Ie.gpuDevice,vt=Ie==null?void 0:Ie.deviceType,Ft=Ie==null?void 0:Ie.numThreads,Lt=Ie==null?void 0:Ie.powerPreference;ct?c.currentContext=ct:et?c.currentContext=await navigator.ml.createContext(et):c.currentContext=await navigator.ml.createContext({deviceType:vt,numThreads:Ft,powerPreference:Lt})}else c.currentContext=await navigator.ml.createContext();break}p=await c._OrtCreateSession(s,u,d),p===0&&Fr("Can't create a session."),c.currentContext&&(c.currentContext=void 0);let[ne,re]=vy(p),ce=!!(i!=null&&i.enableGraphCapture),_e=[],be=[],he=[];for(let xe=0;xe<ne;xe++){let Ie=c._OrtGetInputName(p,xe);Ie===0&&Fr("Can't get an input name."),E.push(Ie),_e.push(c.UTF8ToString(Ie))}for(let xe=0;xe<re;xe++){let Ie=c._OrtGetOutputName(p,xe);Ie===0&&Fr("Can't get an output name."),q.push(Ie);let ct=c.UTF8ToString(Ie);be.push(ct);{if(ce&&(i==null?void 0:i.preferredOutputLocation)===void 0){he.push("gpu-buffer");continue}let et=typeof(i==null?void 0:i.preferredOutputLocation)=="string"?i.preferredOutputLocation:((H=i==null?void 0:i.preferredOutputLocation)==null?void 0:H[ct])??"cpu";if(et!=="cpu"&&et!=="cpu-pinned"&&et!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${et}.`);if(ce&&et!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${et}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);he.push(et)}}let Fe=null;return he.some(xe=>xe==="gpu-buffer")&&(b=c._OrtCreateBinding(p),b===0&&Fr("Can't create IO binding."),Fe={handle:b,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(xe=>po(xe))}),Zo.set(p,[p,E,q,Fe,ce,!1]),[p,_e,be]}catch(ne){throw E.forEach(re=>c._OrtFree(re)),q.forEach(re=>c._OrtFree(re)),b!==0&&c._OrtReleaseBinding(b),p!==0&&c._OrtReleaseSession(p),ne}finally{c._free(s),d!==0&&c._OrtReleaseSessionOptions(d),T.forEach(ne=>c._free(ne)),(v=c.unmountExternalData)==null||v.call(c)}},xm=r=>{var T;let i=Nr(),s=Zo.get(r);if(!s)throw new Error(`cannot release session. invalid session id: ${r}`);let[u,c,p,d,b]=s;d&&(b&&i._OrtClearBoundOutputs(d.handle),i._OrtReleaseBinding(d.handle)),(T=i.jsepOnReleaseSession)==null||T.call(i,r),c.forEach(E=>i._OrtFree(E)),p.forEach(E=>i._OrtFree(E)),i._OrtReleaseSession(u),Zo.delete(r)},Mm=(r,i,s,u,c,p=!1)=>{if(!r){i.push(0);return}let d=Nr(),b=r[0],T=r[1],E=r[3],q,H;if(b==="string"&&E==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(p&&E!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${c} when enableGraphCapture is true.`);if(E==="gpu-buffer"){let re=r[2].gpuBuffer;H=Mi(co(b),T);let ce=d.jsepRegisterBuffer;if(!ce)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');q=ce(u,c,re,H)}else{let re=r[2];if(Array.isArray(re)){H=4*re.length,q=d._malloc(H),s.push(q);let ce=q/4;for(let _e=0;_e<re.length;_e++){if(typeof re[_e]!="string")throw new TypeError(`tensor data at index ${_e} is not a string`);d.HEAPU32[ce++]=Wr(re[_e],s)}}else H=re.byteLength,q=d._malloc(H),s.push(q),d.HEAPU8.set(new Uint8Array(re.buffer,re.byteOffset,H),q)}let v=d.stackSave(),ne=d.stackAlloc(4*T.length);try{let re=ne/4;T.forEach(_e=>d.HEAP32[re++]=_e);let ce=d._OrtCreateTensor(co(b),q,H,ne,T.length,po(E));ce===0&&Fr(`Can't create tensor for input/output. session=${u}, index=${c}.`),i.push(ce)}finally{d.stackRestore(v)}},Tm=async(r,i,s,u,c,p)=>{var Lt,pr;let d=Nr(),b=Zo.get(r);if(!b)throw new Error(`cannot run inference. invalid session id: ${r}`);let T=b[0],E=b[1],q=b[2],H=b[3],v=b[4],ne=b[5],re=i.length,ce=u.length,_e=0,be=[],he=[],Fe=[],xe=[],Ie=d.stackSave(),ct=d.stackAlloc(re*4),et=d.stackAlloc(re*4),vt=d.stackAlloc(ce*4),Ft=d.stackAlloc(ce*4);try{[_e,be]=xi(p);for(let It=0;It<re;It++)Mm(s[It],he,xe,r,i[It],v);for(let It=0;It<ce;It++)Mm(c[It],Fe,xe,r,re+u[It],v);let ar=ct/4,nr=et/4,yr=vt/4,qr=Ft/4;for(let It=0;It<re;It++)d.HEAPU32[ar++]=he[It],d.HEAPU32[nr++]=E[i[It]];for(let It=0;It<ce;It++)d.HEAPU32[yr++]=Fe[It],d.HEAPU32[qr++]=q[u[It]];if(H&&!ne){let{handle:It,outputPreferredLocations:tr,outputPreferredLocationsEncoded:er}=H;if(E.length!==re)throw new Error(`input count from feeds (${re}) is expected to be always equal to model's input count (${E.length}).`);for(let pt=0;pt<re;pt++){let zt=i[pt];await d._OrtBindInput(It,E[zt],he[pt])!==0&&Fr(`Can't bind input[${pt}] for session=${r}.`)}for(let pt=0;pt<ce;pt++){let zt=u[pt];(Lt=c[pt])!=null&&Lt[3]?d._OrtBindOutput(It,q[zt],Fe[pt],0)!==0&&Fr(`Can't bind pre-allocated output[${pt}] for session=${r}.`):d._OrtBindOutput(It,q[zt],0,er[zt])!==0&&Fr(`Can't bind output[${pt}] to ${tr[pt]} for session=${r}.`)}Zo.set(r,[T,E,q,H,v,!0])}(pr=d.jsepOnRunStart)==null||pr.call(d,T);let Sr;H?Sr=await d._OrtRunWithBinding(T,H.handle,ce,vt,_e):Sr=await d._OrtRun(T,et,ct,re,Ft,ce,vt,_e),Sr!==0&&Fr("failed to call OrtRun().");let jr=[];for(let It=0;It<ce;It++){let tr=d.HEAPU32[vt/4+It];if(tr===Fe[It]){jr.push(c[It]);continue}let er=d.stackSave(),pt=d.stackAlloc(4*4),zt=!1,ir,Hr=0;try{d._OrtGetTensorData(tr,pt,pt+4,pt+8,pt+12)!==0&&Fr(`Can't access output tensor data on index ${It}.`);let un=pt/4,xn=d.HEAPU32[un++];Hr=d.HEAPU32[un++];let Yn=d.HEAPU32[un++],Ap=d.HEAPU32[un++],hi=[];for(let Fn=0;Fn<Ap;Fn++)hi.push(d.HEAPU32[Yn/4+Fn]);d._OrtFree(Yn);let In=hi.reduce((Fn,Zn)=>Fn*Zn,1);ir=di(xn);let sf=H==null?void 0:H.outputPreferredLocations[u[It]];if(ir==="string"){if(sf==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Fn=[],Zn=Hr/4;for(let Ci=0;Ci<In;Ci++){let es=d.HEAPU32[Zn++],Ip=Ci===In-1?void 0:d.HEAPU32[Zn]-es;Fn.push(d.UTF8ToString(es,Ip))}jr.push([ir,hi,Fn,"cpu"])}else if(sf==="gpu-buffer"&&In>0){let Fn=d.jsepGetBuffer;if(!Fn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Zn=Fn(Hr),Ci=Mi(xn,In);if(Ci===void 0||!fo(ir))throw new Error(`Unsupported data type: ${ir}`);zt=!0,jr.push([ir,hi,{gpuBuffer:Zn,download:d.jsepCreateDownloader(Zn,Ci,ir),dispose:()=>{d._OrtReleaseTensor(tr)}},"gpu-buffer"])}else{let Fn=Ti(ir),Zn=new Fn(In);new Uint8Array(Zn.buffer,Zn.byteOffset,Zn.byteLength).set(d.HEAPU8.subarray(Hr,Hr+Zn.byteLength)),jr.push([ir,hi,Zn,"cpu"])}}finally{d.stackRestore(er),ir==="string"&&Hr&&d._free(Hr),zt||d._OrtReleaseTensor(tr)}}return H&&!v&&(d._OrtClearBoundOutputs(H.handle),Zo.set(r,[T,E,q,H,v,!1])),jr}finally{d.stackRestore(Ie),he.forEach(ar=>d._OrtReleaseTensor(ar)),Fe.forEach(ar=>d._OrtReleaseTensor(ar)),xe.forEach(ar=>d._free(ar)),_e!==0&&d._OrtReleaseRunOptions(_e),be.forEach(ar=>d._free(ar))}},km=r=>{let i=Nr(),s=Zo.get(r);if(!s)throw new Error("invalid session id");let u=s[0],c=i._OrtEndProfiling(u);c===0&&Fr("Can't get an profile file name."),i._OrtFree(c)},Sm=r=>{let i=[];for(let s of r){let u=s[2];!Array.isArray(u)&&"buffer"in u&&i.push(u.buffer)}return i}}),Jo,ii,Tl,nf,of,Pp,Em,$p,qs,Hs,xy,My,Ty,ky,Sy,Ey,Cy,Py,$y=h(()=>{Z(),by(),mn(),Qr(),Jo=()=>!!D.wasm.proxy&&typeof document<"u",Tl=!1,nf=!1,of=!1,$p=new Map,qs=(r,i)=>{let s=$p.get(r);s?s.push(i):$p.set(r,[i])},Hs=()=>{if(Tl||!nf||of||!ii)throw new Error("worker not ready")},xy=r=>{switch(r.data.type){case"init-wasm":Tl=!1,r.data.err?(of=!0,Em[1](r.data.err)):(nf=!0,Em[0]()),Pp&&(URL.revokeObjectURL(Pp),Pp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=$p.get(r.data.type);r.data.err?i.shift()[1](r.data.err):i.shift()[0](r.data.out);break}}},My=async()=>{if(!nf){if(Tl)throw new Error("multiple calls to 'initWasm()' detected.");if(of)throw new Error("previous call to 'initWasm()' failed.");if(Tl=!0,Jo())return new Promise((r,i)=>{ii==null||ii.terminate(),Jt().then(([s,u])=>{try{ii=u,ii.onerror=p=>i(p),ii.onmessage=xy,Em=[r,i];let c={type:"init-wasm",in:D};ii.postMessage(c),Pp=s}catch(c){i(c)}},i)});try{await bi(D.wasm),await wm(D),nf=!0}catch(r){throw of=!0,r}finally{Tl=!1}}},Ty=async r=>{if(Jo())return Hs(),new Promise((i,s)=>{qs("init-ep",[i,s]);let u={type:"init-ep",in:{epName:r,env:D}};ii.postMessage(u)});await vm(D,r)},ky=async r=>Jo()?(Hs(),new Promise((i,s)=>{qs("copy-from",[i,s]);let u={type:"copy-from",in:{buffer:r}};ii.postMessage(u,[r.buffer])})):Cp(r),Sy=async(r,i)=>{if(Jo()){if(i!=null&&i.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Hs(),new Promise((s,u)=>{qs("create",[s,u]);let c={type:"create",in:{model:r,options:{...i}}},p=[];r instanceof Uint8Array&&p.push(r.buffer),ii.postMessage(c,p)})}else return bm(r,i)},Ey=async r=>{if(Jo())return Hs(),new Promise((i,s)=>{qs("release",[i,s]);let u={type:"release",in:r};ii.postMessage(u)});xm(r)},Cy=async(r,i,s,u,c,p)=>{if(Jo()){if(s.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(c.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Hs(),new Promise((d,b)=>{qs("run",[d,b]);let T=s,E={type:"run",in:{sessionId:r,inputIndices:i,inputs:T,outputIndices:u,options:p}};ii.postMessage(E,Sm(T))})}else return Tm(r,i,s,u,c,p)},Py=async r=>{if(Jo())return Hs(),new Promise((i,s)=>{qs("end-profiling",[i,s]);let u={type:"end-profiling",in:r};ii.postMessage(u)});km(r)}}),Cm,Ay,Iy,fx=h(()=>{Z(),$y(),Xt(),ve(),Bo(),Cm=(r,i)=>{switch(r.location){case"cpu":return[r.type,r.dims,r.data,"cpu"];case"gpu-buffer":return[r.type,r.dims,{gpuBuffer:r.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${r.location} for ${i()}`)}},Ay=r=>{switch(r[3]){case"cpu":return new Ge(r[0],r[2],r[1]);case"gpu-buffer":{let i=r[0];if(!fo(i))throw new Error(`not supported data type: ${i} for deserializing GPU tensor`);let{gpuBuffer:s,download:u,dispose:c}=r[2];return Ge.fromGpuBuffer(s,{dataType:i,dims:r[1],download:u,dispose:c})}default:throw new Error(`invalid data location: ${r[3]}`)}},Iy=class{async fetchModelAndCopyToWasmMemory(r){return ky(await Zi(r))}async loadModel(r,i){tt();let s;typeof r=="string"?s=await this.fetchModelAndCopyToWasmMemory(r):s=r,[this.sessionId,this.inputNames,this.outputNames]=await Sy(s,i),A()}async dispose(){return Ey(this.sessionId)}async run(r,i,s){tt();let u=[],c=[];Object.entries(r).forEach(H=>{let v=H[0],ne=H[1],re=this.inputNames.indexOf(v);if(re===-1)throw new Error(`invalid input '${v}'`);u.push(ne),c.push(re)});let p=[],d=[];Object.entries(i).forEach(H=>{let v=H[0],ne=H[1],re=this.outputNames.indexOf(v);if(re===-1)throw new Error(`invalid output '${v}'`);p.push(ne),d.push(re)});let b=u.map((H,v)=>Cm(H,()=>`input "${this.inputNames[c[v]]}"`)),T=p.map((H,v)=>H?Cm(H,()=>`output "${this.outputNames[d[v]]}"`):null),E=await Cy(this.sessionId,c,b,d,T,s),q={};for(let H=0;H<E.length;H++)q[this.outputNames[d[H]]]=p[H]??Ay(E[H]);return A(),q}startProfiling(){}endProfiling(){Py(this.sessionId)}}}),Fy,zy,px=h(()=>{Z(),$y(),fx(),Qr(),Fy=()=>{if((typeof D.wasm.initTimeout!="number"||D.wasm.initTimeout<0)&&(D.wasm.initTimeout=0),D.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof D.wasm.proxy!="boolean"&&(D.wasm.proxy=!1),typeof D.wasm.trace!="boolean"&&(D.wasm.trace=!1),typeof D.wasm.numThreads!="number"||!Number.isInteger(D.wasm.numThreads)||D.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)D.wasm.numThreads=1;else{let r=typeof navigator>"u"?_("node:os").cpus().length:navigator.hardwareConcurrency;D.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},zy=class{async init(r){Fy(),await My(),await Ty(r)}async createInferenceSessionHandler(r,i){let s=new Iy;return await s.loadModel(r,i),Promise.resolve(s)}}}),Oy={};g(Oy,{wasmBackend:()=>Dy});var Dy,hx=h(()=>{px(),Dy=new zy});Z(),Z(),Z();var mx="1.20.0-dev.20240821-009209e016",gx=Ve;{let r=(hx(),w(Oy)).wasmBackend;z("webgpu",r,5),z("webnn",r,5),z("cpu",r,10),z("wasm",r,10)}Object.defineProperty(D.versions,"web",{value:mx,enumerable:!0});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */},"./src/backends/onnx.js":(e,t,n)=>{var o;n.r(t),n.d(t,{Tensor:()=>_.Tensor,createInferenceSession:()=>S,deviceToExecutionProviders:()=>k,isONNXProxy:()=>x,isONNXTensor:()=>P});var a=n("./src/env.js"),l=n("?2ce3"),f=n("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),_=n("./node_modules/onnxruntime-common/dist/esm/index.js");const h=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),g=[];let M,w;if(a.apis.IS_NODE_ENV){switch(w=l??(o||(o=n.t(l,2))),process.platform){case"win32":g.push("dml");break;case"linux":process.arch==="x64"&&g.push("cuda");break}g.push("cpu"),M=["cpu"]}else w=f,a.apis.IS_WEBNN_AVAILABLE&&g.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),a.apis.IS_WEBGPU_AVAILABLE&&g.push("webgpu"),g.push("wasm"),M=["wasm"];const C=w.InferenceSession;function k(I=null){if(!I)return M;switch(I){case"auto":return g;case"gpu":return g.filter(U=>["webgpu","cuda","dml","webnn-gpu"].includes(U))}if(g.includes(I))return[h[I]??I];throw new Error(`Unsupported device: "${I}". Should be one of: ${g.join(", ")}.`)}let z=null;async function S(I,U){z&&await z;const O=C.create(I,U);return z??(z=O),await O}function P(I){return I instanceof w.Tensor}const y=w==null?void 0:w.env;y!=null&&y.wasm&&(y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${a.env.version}/dist/`,y.wasm.proxy=!a.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(y.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(y.wasm.simd=!1)),y!=null&&y.webgpu&&(y.webgpu.powerPreference="high-performance");function x(){var I;return(I=y==null?void 0:y.wasm)==null?void 0:I.proxy}a.env.backends.onnx=y},"./src/configs.js":(e,t,n)=>{n.r(t),n.d(t,{AutoConfig:()=>g,PretrainedConfig:()=>h,getKeyValueShapes:()=>_});var o=n("./src/utils/core.js"),a=n("./src/utils/hub.js");async function l(M,w){return await(0,a.getModelJSON)(M,"config.json",!0,w)}function f(M){const w={};let C={};switch(M.model_type){case"llava":case"paligemma":case"florence2":C=f(M.text_config);break;case"moondream1":C=f(M.phi_config);break;case"musicgen":C=f(M.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":w.num_heads="n_head",w.num_layers="n_layer",w.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":w.num_heads="num_attention_heads",w.num_layers="num_hidden_layers",w.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":w.num_heads="num_key_value_heads",w.num_layers="num_hidden_layers",w.hidden_size="hidden_size",w.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":w.num_heads="num_key_value_heads",w.num_layers="num_hidden_layers",w.dim_kv="head_dim";break;case"openelm":w.num_heads="num_kv_heads",w.num_layers="num_transformer_layers",w.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":w.num_heads="num_heads",w.num_layers="num_layers",w.hidden_size="hidden_size";break;case"bloom":w.num_heads="n_head",w.num_layers="n_layer",w.hidden_size="hidden_size";break;case"mpt":w.num_heads="n_heads",w.num_layers="n_layers",w.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":w.num_decoder_layers="num_decoder_layers",w.num_decoder_heads="num_heads",w.decoder_dim_kv="d_kv",w.num_encoder_layers="num_layers",w.num_encoder_heads="num_heads",w.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":w.num_decoder_layers="decoder_layers",w.num_decoder_heads="decoder_attention_heads",w.decoder_hidden_size="d_model",w.num_encoder_layers="encoder_layers",w.num_encoder_heads="encoder_attention_heads",w.encoder_hidden_size="d_model";break;case"speecht5":w.num_decoder_layers="decoder_layers",w.num_decoder_heads="decoder_attention_heads",w.decoder_hidden_size="hidden_size",w.num_encoder_layers="encoder_layers",w.num_encoder_heads="encoder_attention_heads",w.encoder_hidden_size="hidden_size";break;case"trocr":w.num_encoder_layers=w.num_decoder_layers="decoder_layers",w.num_encoder_heads=w.num_decoder_heads="decoder_attention_heads",w.encoder_hidden_size=w.decoder_hidden_size="d_model";break;case"musicgen_decoder":w.num_encoder_layers=w.num_decoder_layers="num_hidden_layers",w.num_encoder_heads=w.num_decoder_heads="num_attention_heads",w.encoder_hidden_size=w.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const z=f(M.decoder),S="num_decoder_layers"in z,P=(0,o.pick)(M,["model_type","is_encoder_decoder"]);return S?(P.num_decoder_layers=z.num_decoder_layers,P.num_decoder_heads=z.num_decoder_heads,P.decoder_hidden_size=z.decoder_hidden_size,P.num_encoder_layers=z.num_encoder_layers,P.num_encoder_heads=z.num_encoder_heads,P.encoder_hidden_size=z.encoder_hidden_size):(P.num_layers=z.num_layers,P.num_heads=z.num_heads,P.hidden_size=z.hidden_size),P}const k={...C,...(0,o.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const z in w)k[z]=M[w[z]];return k}function _(M,{prefix:w="past_key_values"}={}){const C={},k=M.normalized_config,z=1;if(k.is_encoder_decoder&&"num_encoder_heads"in k&&"num_decoder_heads"in k){const S=k.encoder_dim_kv??k.encoder_hidden_size/k.num_encoder_heads,P=k.decoder_dim_kv??k.decoder_hidden_size/k.num_decoder_heads,y=[z,k.num_encoder_heads,0,S],x=[z,k.num_decoder_heads,0,P];for(let I=0;I<k.num_decoder_layers;++I)C[`${w}.${I}.encoder.key`]=y,C[`${w}.${I}.encoder.value`]=y,C[`${w}.${I}.decoder.key`]=x,C[`${w}.${I}.decoder.value`]=x}else{const S=k.num_heads,P=k.num_layers,y=k.dim_kv??k.hidden_size/(k.num_attention_heads??S);if(k.model_type==="falcon"){const x=[z*S,0,y];for(let I=0;I<P;++I)C[`${w}.${I}.key`]=x,C[`${w}.${I}.value`]=x}else if(k.multi_query){const x=[z*S,0,2*y];for(let I=0;I<P;++I)C[`${w}.${I}.key_value`]=x}else if(k.model_type==="bloom"){const x=[z*S,y,0],I=[z*S,0,y];for(let U=0;U<P;++U)C[`${w}.${U}.key`]=x,C[`${w}.${U}.value`]=I}else if(k.model_type==="openelm")for(let x=0;x<P;++x){const I=[z,S[x],0,y];C[`${w}.${x}.key`]=I,C[`${w}.${x}.value`]=I}else{const x=[z,S,0,y];for(let I=0;I<P;++I)C[`${w}.${I}.key`]=x,C[`${w}.${I}.value`]=x}}return C}class h{constructor(w){qe(this,"max_position_embeddings");this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,w),this.normalized_config=f(this)}static async from_pretrained(w,{progress_callback:C=null,config:k=null,cache_dir:z=null,local_files_only:S=!1,revision:P="main"}={}){k&&!(k instanceof h)&&(k=new h(k));const y=k??await l(w,{progress_callback:C,config:k,cache_dir:z,local_files_only:S,revision:P});return new this(y)}}class g{static async from_pretrained(...w){return h.from_pretrained(...w)}}},"./src/env.js":(e,t,n)=>{var D;n.r(t),n.d(t,{apis:()=>P,env:()=>N});var o=n("?569f"),a=n("?3f59"),l=n("?154a");const f="3.0.0-alpha.9",_=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope",g=_&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,w=typeof navigator<"u"&&"ml"in navigator,C=typeof process<"u",k=C&&((D=process==null?void 0:process.release)==null?void 0:D.name)==="node",z=!j(o),S=!j(a),P=Object.freeze({IS_BROWSER_ENV:_,IS_WEBWORKER_ENV:h,IS_WEB_CACHE_AVAILABLE:g,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:w,IS_PROCESS_AVAILABLE:C,IS_NODE_ENV:k,IS_FS_AVAILABLE:z,IS_PATH_AVAILABLE:S}),y=z&&S,x=y?a.dirname(a.dirname(l.fileURLToPath(import.meta.url))):"./",I=y?a.join(x,"/.cache/"):null,U="/models/",O=y?a.join(x,U):U,N={version:f,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!_,localModelPath:O,useFS:z,useBrowserCache:g,useFSCache:z,cacheDir:I,useCustomCache:!1,customCache:null};function j(Y){return Object.keys(Y).length===0}},"./src/generation/configuration_utils.js":(e,t,n)=>{n.r(t),n.d(t,{GenerationConfig:()=>a});var o=n("./src/utils/core.js");class a{constructor(f){qe(this,"max_length",20);qe(this,"max_new_tokens",null);qe(this,"min_length",0);qe(this,"min_new_tokens",null);qe(this,"early_stopping",!1);qe(this,"max_time",null);qe(this,"do_sample",!1);qe(this,"num_beams",1);qe(this,"num_beam_groups",1);qe(this,"penalty_alpha",null);qe(this,"use_cache",!0);qe(this,"temperature",1);qe(this,"top_k",50);qe(this,"top_p",1);qe(this,"typical_p",1);qe(this,"epsilon_cutoff",0);qe(this,"eta_cutoff",0);qe(this,"diversity_penalty",0);qe(this,"repetition_penalty",1);qe(this,"encoder_repetition_penalty",1);qe(this,"length_penalty",1);qe(this,"no_repeat_ngram_size",0);qe(this,"bad_words_ids",null);qe(this,"force_words_ids",null);qe(this,"renormalize_logits",!1);qe(this,"constraints",null);qe(this,"forced_bos_token_id",null);qe(this,"forced_eos_token_id",null);qe(this,"remove_invalid_values",!1);qe(this,"exponential_decay_length_penalty",null);qe(this,"suppress_tokens",null);qe(this,"begin_suppress_tokens",null);qe(this,"forced_decoder_ids",null);qe(this,"guidance_scale",null);qe(this,"num_return_sequences",1);qe(this,"output_attentions",!1);qe(this,"output_hidden_states",!1);qe(this,"output_scores",!1);qe(this,"return_dict_in_generate",!1);qe(this,"pad_token_id",null);qe(this,"bos_token_id",null);qe(this,"eos_token_id",null);qe(this,"encoder_no_repeat_ngram_size",0);qe(this,"decoder_start_token_id",null);qe(this,"generation_kwargs",{});Object.assign(this,(0,o.pick)(f,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,n)=>{n.r(t),n.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>y,ForcedBOSTokenLogitsProcessor:()=>h,ForcedEOSTokenLogitsProcessor:()=>g,LogitsProcessor:()=>l,LogitsProcessorList:()=>_,LogitsWarper:()=>f,MinLengthLogitsProcessor:()=>z,MinNewTokensLengthLogitsProcessor:()=>S,NoBadWordsLogitsProcessor:()=>P,NoRepeatNGramLogitsProcessor:()=>C,RepetitionPenaltyLogitsProcessor:()=>k,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>x,TopKLogitsWarper:()=>U,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>w});var o=n("./src/utils/generic.js");n("./src/utils/tensor.js");var a=n("./src/utils/maths.js");class l extends o.Callable{_call(N,j){throw Error("`_call` should be implemented in a subclass")}}class f extends o.Callable{_call(N,j){throw Error("`_call` should be implemented in a subclass")}}class _ extends o.Callable{constructor(){super(),this.processors=[]}push(N){this.processors.push(N)}extend(N){this.processors.push(...N)}_call(N,j){let D=j;for(const Y of this.processors)D=Y(N,D);return D}[Symbol.iterator](){return this.processors.values()}}class h extends l{constructor(N){super(),this.bos_token_id=N}_call(N,j){for(let D=0;D<N.length;++D)if(N[D].length===1){const Y=j[D];Y.data.fill(-1/0),Y.data[this.bos_token_id]=0}return j}}class g extends l{constructor(N,j){super(),this.max_length=N,this.eos_token_id=Array.isArray(j)?j:[j]}_call(N,j){for(let D=0;D<N.length;++D)if(N[D].length===this.max_length-1){const Y=j[D];Y.data.fill(-1/0);for(const de of this.eos_token_id)Y.data[de]=0}return j}}class M extends l{constructor(N,j){super(),this.begin_suppress_tokens=N,this.begin_index=j}_call(N,j){for(let D=0;D<N.length;++D)if(N[D].length===this.begin_index){const Y=j[D];for(const de of this.begin_suppress_tokens)Y.data[de]=-1/0}return j}}class w extends l{constructor(N,j){super(),this.eos_token_id=Array.isArray(N.eos_token_id)?N.eos_token_id[0]:N.eos_token_id,this.no_timestamps_token_id=N.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=j.length,j.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=N.max_initial_timestamp_index}_call(N,j){for(let D=0;D<N.length;++D){const de=j[D].data;if(de[this.no_timestamps_token_id]=-1/0,N[D].length===this.begin_index-1){de.fill(-1/0),de[this.timestamp_begin]=0;continue}const Ce=N[D].slice(this.begin_index),ee=Ce.length>=1&&Ce[Ce.length-1]>=this.timestamp_begin,ye=Ce.length<2||Ce[Ce.length-2]>=this.timestamp_begin;if(ee&&(ye?de.subarray(this.timestamp_begin).fill(-1/0):de.subarray(0,this.eos_token_id).fill(-1/0)),N[D].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ge=this.timestamp_begin+this.max_initial_timestamp_index;de.subarray(ge+1).fill(-1/0)}const R=(0,a.log_softmax)(de),Me=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((ge,Q)=>ge+Q)),Qe=(0,a.max)(R.subarray(0,this.timestamp_begin))[0];Me>Qe&&de.subarray(0,this.timestamp_begin).fill(-1/0)}return j}}class C extends l{constructor(N){super(),this.no_repeat_ngram_size=N}getNgrams(N){const j=N.length,D=[];for(let de=0;de<j+1-this.no_repeat_ngram_size;++de){const Ce=[];for(let ee=0;ee<this.no_repeat_ngram_size;++ee)Ce.push(N[de+ee]);D.push(Ce.map(Number))}const Y=new Map;for(const de of D){const Ce=de.slice(0,de.length-1),ee=JSON.stringify(Ce),ye=Y.get(ee)??[];ye.push(de[de.length-1]),Y.set(ee,ye)}return Y}getGeneratedNgrams(N,j){const D=j.slice(j.length+1-this.no_repeat_ngram_size,j.length);return N.get(JSON.stringify(D.map(Number)))??[]}calcBannedNgramTokens(N){const j=[];if(N.length+1<this.no_repeat_ngram_size)return j;{const D=this.getNgrams(N);return this.getGeneratedNgrams(D,N)}}_call(N,j){for(let D=0;D<N.length;++D){const Y=j[D],de=this.calcBannedNgramTokens(N[D]);for(const Ce of de)Y.data[Ce]=-1/0}return j}}class k extends l{constructor(N){super(),this.penalty=N}_call(N,j){for(let D=0;D<N.length;++D){const Y=j[D];for(const de of N[D])Y.data[de]<0?Y.data[de]*=this.penalty:Y.data[de]/=this.penalty}return j}}class z extends l{constructor(N,j){super(),this.min_length=N,this.eos_token_id=Array.isArray(j)?j:[j]}_call(N,j){for(let D=0;D<N.length;++D)if(N[D].length<this.min_length){const Y=j[D];for(const de of this.eos_token_id)Y.data[de]=-1/0}return j}}class S extends l{constructor(N,j,D){super(),this.prompt_length_to_skip=N,this.min_new_tokens=j,this.eos_token_id=Array.isArray(D)?D:[D]}_call(N,j){for(let D=0;D<N.length;++D)if(N[D].length-this.prompt_length_to_skip<this.min_new_tokens){const de=j[D];for(const Ce of this.eos_token_id)de[Ce]=-1/0}return j}}class P extends l{constructor(N,j){super(),this.bad_words_ids=N,this.eos_token_id=Array.isArray(j)?j:[j]}_call(N,j){for(let D=0;D<N.length;++D){const Y=j[D];for(const de of this.bad_words_ids){let Ce=!0;for(let ee=1;ee<=de.length-1&&de.length<N[ee].length;++ee)if(de.at(-ee-1)!==Number(N[ee].at(-ee))){Ce=!1;break}Ce&&(Y[de.at(-1)]=-1/0)}}return j}}class y extends l{constructor(N){if(super(),N<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${N}.`);this.guidance_scale=N}_call(N,j){if(j.dims[0]!==2*N.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${j.dims[0]} for the logits and ${N.length} for the input ids.`);const D=N.length,Y=j.slice([0,D],null),de=j.slice([D,j.dims[0]],null);for(let Ce=0;Ce<de.data.length;++Ce)de.data[Ce]+=(Y.data[Ce]-de.data[Ce])*this.guidance_scale;return de}}class x extends f{constructor(N){super(),this.temperature=N}_call(N,j){const D=j.data;for(let Y=0;Y<D.length;++Y)D[Y]/=this.temperature;return j}}class I extends f{constructor(N,{filter_value:j=-1/0,min_tokens_to_keep:D=1}={}){if(super(),N<0||N>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${N}`);if(!Number.isInteger(D)||D<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${D}`);this.top_p=N,this.filter_value=j,this.min_tokens_to_keep=D}}class U extends f{constructor(N,{filter_value:j=-1/0,min_tokens_to_keep:D=1}={}){if(super(),!Number.isInteger(N)||N<0)throw new Error(`\`top_k\` must be a positive integer, but is ${N}`);this.top_k=Math.max(N,D),this.filter_value=j}}},"./src/generation/logits_sampler.js":(e,t,n)=>{n.r(t),n.d(t,{LogitsSampler:()=>f});var o=n("./src/utils/generic.js"),a=n("./src/utils/tensor.js"),l=n("./src/utils/maths.js");n("./src/generation/configuration_utils.js");class f extends o.Callable{constructor(w){super(),this.generation_config=w}async _call(w){return this.sample(w)}async sample(w){throw Error("sample should be implemented in subclasses.")}getLogits(w,C){let k=w.dims.at(-1),z=w.data;if(C===-1)z=z.slice(-k);else{let S=C*k;z=z.slice(S,S+k)}return z}randomSelect(w){let C=0;for(let z=0;z<w.length;++z)C+=w[z];let k=Math.random()*C;for(let z=0;z<w.length;++z)if(k-=w[z],k<=0)return z;return 0}static getSampler(w){if(w.do_sample)return new h(w);if(w.num_beams>1)return new g(w);if(w.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${w.num_return_sequences}.`);return new _(w)}}class _ extends f{async sample(w){const C=(0,l.max)(w.data)[1];return[[BigInt(C),0]]}}class h extends f{async sample(w){let C=w.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[k,z]=await(0,a.topk)(w,C),S=(0,l.softmax)(k.data);return Array.from({length:this.generation_config.num_beams},()=>{const P=this.randomSelect(S);return[z.data[P],Math.log(S[P])]})}}class g extends f{async sample(w){let C=w.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[k,z]=await(0,a.topk)(w,C),S=(0,l.softmax)(k.data);return Array.from({length:this.generation_config.num_beams},(P,y)=>[z.data[y],Math.log(S[y])])}}},"./src/generation/stopping_criteria.js":(e,t,n)=>{n.r(t),n.d(t,{EosTokenCriteria:()=>_,InterruptableStoppingCriteria:()=>h,MaxLengthCriteria:()=>f,StoppingCriteria:()=>a,StoppingCriteriaList:()=>l});var o=n("./src/utils/generic.js");class a extends o.Callable{_call(M,w){throw Error("StoppingCriteria needs to be subclassed")}}class l extends o.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof l?M=M.criteria:M instanceof a&&(M=[M]),this.criteria.push(...M)}_call(M,w){const C=new Array(M.length).fill(!1);for(const k of this.criteria){const z=k(M,w);for(let S=0;S<C.length;++S)C[S]||(C[S]=z[S])}return C}[Symbol.iterator](){return this.criteria.values()}}class f extends a{constructor(M,w=null){super(),this.max_length=M,this.max_position_embeddings=w}_call(M){return M.map(w=>w.length>=this.max_length)}}class _ extends a{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,w){return M.map(C=>{const k=C.at(-1);return this.eos_token_id.some(z=>k==z)})}}class h extends a{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,w){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,n)=>{n.r(t),n.d(t,{BaseStreamer:()=>f,TextStreamer:()=>h,WhisperTextStreamer:()=>g});var o=n("./src/utils/core.js"),a=n("./src/tokenizers.js"),l=n("./src/env.js");class f{put(w){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const _=l.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class h extends f{constructor(w,{skip_prompt:C=!1,callback_function:k=null,token_callback_function:z=null,decode_kwargs:S={},...P}={}){super(),this.tokenizer=w,this.skip_prompt=C,this.callback_function=k??_,this.token_callback_function=z,this.decode_kwargs={...S,...P},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(w){var S;if(w.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const C=w[0];(S=this.token_callback_function)==null||S.call(this,C),this.token_cache=(0,o.mergeArrays)(this.token_cache,C);const k=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let z;k.endsWith(` +`)?(z=k.slice(this.print_len),this.token_cache=[],this.print_len=0):k.length>0&&(0,a.is_chinese_char)(k.charCodeAt(k.length-1))?(z=k.slice(this.print_len),this.print_len+=z.length):(z=k.slice(this.print_len,k.lastIndexOf(" ")+1),this.print_len+=z.length),this.on_finalized_text(z,!1)}end(){let w;this.token_cache.length>0?(w=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):w="",this.next_tokens_are_prompt=!0,this.on_finalized_text(w,!0)}on_finalized_text(w,C){var k,z;w.length>0&&((k=this.callback_function)==null||k.call(this,w)),C&&this.callback_function===_&&l.apis.IS_PROCESS_AVAILABLE&&((z=this.callback_function)==null||z.call(this,` +`))}}class g extends h{constructor(w,{skip_prompt:C=!1,callback_function:k=null,token_callback_function:z=null,on_chunk_start:S=null,on_chunk_end:P=null,on_finalize:y=null,time_precision:x=.02,skip_special_tokens:I=!0,decode_kwargs:U={}}={}){super(w,{skip_prompt:C,callback_function:k,token_callback_function:z,decode_kwargs:{skip_special_tokens:I,...U}}),this.timestamp_begin=w.timestamp_begin,this.on_chunk_start=S,this.on_chunk_end=P,this.on_finalize=y,this.time_precision=x,this.waiting_for_timestamp=!1}put(w){var k,z;if(w.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const C=w[0];if(C.length===1){const S=Number(C[0])-this.timestamp_begin;if(S>=0){const P=S*this.time_precision;this.waiting_for_timestamp?(k=this.on_chunk_end)==null||k.call(this,P):(z=this.on_chunk_start)==null||z.call(this,P),this.waiting_for_timestamp=!this.waiting_for_timestamp,w=[[]]}}return super.put(w)}end(){var w;super.end(),(w=this.on_finalize)==null||w.call(this)}}},"./src/models.js":(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>Es,ASTModel:()=>Dt,ASTPreTrainedModel:()=>Nn,AlbertForMaskedLM:()=>Xt,AlbertForQuestionAnswering:()=>po,AlbertForSequenceClassification:()=>fo,AlbertModel:()=>Yi,AlbertPreTrainedModel:()=>Ti,AutoModel:()=>Od,AutoModelForAudioClassification:()=>Hd,AutoModelForAudioFrameClassification:()=>Kd,AutoModelForCTC:()=>qd,AutoModelForCausalLM:()=>Bd,AutoModelForDepthEstimation:()=>Yd,AutoModelForDocumentQuestionAnswering:()=>bp,AutoModelForImageClassification:()=>Ud,AutoModelForImageFeatureExtraction:()=>Zd,AutoModelForImageMatting:()=>Qd,AutoModelForImageSegmentation:()=>vl,AutoModelForImageToImage:()=>Xd,AutoModelForMaskGeneration:()=>bl,AutoModelForMaskedLM:()=>Nd,AutoModelForObjectDetection:()=>Wd,AutoModelForQuestionAnswering:()=>wl,AutoModelForSemanticSegmentation:()=>Vd,AutoModelForSeq2SeqLM:()=>Ld,AutoModelForSequenceClassification:()=>Sn,AutoModelForSpeechSeq2Seq:()=>yl,AutoModelForTextToSpectrogram:()=>Rd,AutoModelForTextToWaveform:()=>Xo,AutoModelForTokenClassification:()=>Dd,AutoModelForVision2Seq:()=>jd,AutoModelForXVector:()=>xl,AutoModelForZeroShotObjectDetection:()=>Gd,BartForConditionalGeneration:()=>W,BartForSequenceClassification:()=>fe,BartModel:()=>Ue,BartPretrainedModel:()=>Rn,BaseModelOutput:()=>Ke,BeitForImageClassification:()=>sc,BeitModel:()=>oc,BeitPreTrainedModel:()=>$a,BertForMaskedLM:()=>We,BertForQuestionAnswering:()=>Ge,BertForSequenceClassification:()=>ot,BertForTokenClassification:()=>dt,BertModel:()=>Be,BertPreTrainedModel:()=>De,BlenderbotForConditionalGeneration:()=>At,BlenderbotModel:()=>Tt,BlenderbotPreTrainedModel:()=>kt,BlenderbotSmallForConditionalGeneration:()=>rr,BlenderbotSmallModel:()=>Pr,BlenderbotSmallPreTrainedModel:()=>Zt,BloomForCausalLM:()=>ju,BloomModel:()=>Nu,BloomPreTrainedModel:()=>$s,CLIPModel:()=>lu,CLIPPreTrainedModel:()=>Wo,CLIPSegForImageSegmentation:()=>mu,CLIPSegModel:()=>hu,CLIPSegPreTrainedModel:()=>ma,CLIPTextModelWithProjection:()=>fi,CLIPVisionModelWithProjection:()=>uu,CamembertForMaskedLM:()=>Re,CamembertForQuestionAnswering:()=>rt,CamembertForSequenceClassification:()=>He,CamembertForTokenClassification:()=>Xe,CamembertModel:()=>ve,CamembertPreTrainedModel:()=>Z,CausalLMOutput:()=>Ji,CausalLMOutputWithPast:()=>xp,ChineseCLIPModel:()=>pu,ChineseCLIPPreTrainedModel:()=>fu,ClapAudioModelWithProjection:()=>ld,ClapModel:()=>sd,ClapPreTrainedModel:()=>qo,ClapTextModelWithProjection:()=>ad,CodeGenForCausalLM:()=>Cs,CodeGenModel:()=>ku,CodeGenPreTrainedModel:()=>Kn,CohereForCausalLM:()=>Cu,CohereModel:()=>Eu,CoherePreTrainedModel:()=>va,ConvBertForMaskedLM:()=>B,ConvBertForQuestionAnswering:()=>ue,ConvBertForSequenceClassification:()=>J,ConvBertForTokenClassification:()=>L,ConvBertModel:()=>we,ConvBertPreTrainedModel:()=>te,ConvNextForImageClassification:()=>Pc,ConvNextModel:()=>Cc,ConvNextPreTrainedModel:()=>Va,ConvNextV2ForImageClassification:()=>Ic,ConvNextV2Model:()=>Ac,ConvNextV2PreTrainedModel:()=>$c,DPTForDepthEstimation:()=>Na,DPTModel:()=>Ba,DPTPreTrainedModel:()=>Ra,DebertaForMaskedLM:()=>Mt,DebertaForQuestionAnswering:()=>Rt,DebertaForSequenceClassification:()=>wt,DebertaForTokenClassification:()=>St,DebertaModel:()=>ht,DebertaPreTrainedModel:()=>ft,DebertaV2ForMaskedLM:()=>Ut,DebertaV2ForQuestionAnswering:()=>Jt,DebertaV2ForSequenceClassification:()=>Kt,DebertaV2ForTokenClassification:()=>Qt,DebertaV2Model:()=>Ot,DebertaV2PreTrainedModel:()=>at,DeiTForImageClassification:()=>_c,DeiTModel:()=>gc,DeiTPreTrainedModel:()=>Fa,DepthAnythingForDepthEstimation:()=>Tc,DepthAnythingPreTrainedModel:()=>Mc,DetrForObjectDetection:()=>lc,DetrForSegmentation:()=>uc,DetrModel:()=>ac,DetrObjectDetectionOutput:()=>Aa,DetrPreTrainedModel:()=>Fs,DetrSegmentationOutput:()=>cc,Dinov2ForImageClassification:()=>zc,Dinov2Model:()=>Fc,Dinov2PreTrainedModel:()=>Xn,DistilBertForMaskedLM:()=>Pt,DistilBertForQuestionAnswering:()=>mt,DistilBertForSequenceClassification:()=>Qr,DistilBertForTokenClassification:()=>Cr,DistilBertModel:()=>Er,DistilBertPreTrainedModel:()=>qt,DonutSwinModel:()=>Ua,DonutSwinPreTrainedModel:()=>Ec,EfficientNetForImageClassification:()=>pd,EfficientNetModel:()=>fd,EfficientNetPreTrainedModel:()=>ul,ElectraForMaskedLM:()=>Ne,ElectraForQuestionAnswering:()=>Ve,ElectraForSequenceClassification:()=>ut,ElectraForTokenClassification:()=>Je,ElectraModel:()=>ke,ElectraPreTrainedModel:()=>le,EsmForMaskedLM:()=>Li,EsmForSequenceClassification:()=>bi,EsmForTokenClassification:()=>Nr,EsmModel:()=>sn,EsmPreTrainedModel:()=>Bt,FalconForCausalLM:()=>od,FalconModel:()=>id,FalconPreTrainedModel:()=>ol,FastViTForImageClassification:()=>Ku,FastViTModel:()=>Hu,FastViTPreTrainedModel:()=>Is,Florence2ForConditionalGeneration:()=>pa,Florence2PreTrainedModel:()=>au,GLPNForDepthEstimation:()=>Sc,GLPNModel:()=>kc,GLPNPreTrainedModel:()=>ja,GPT2LMHeadModel:()=>_u,GPT2Model:()=>gu,GPT2PreTrainedModel:()=>ga,GPTBigCodeForCausalLM:()=>ep,GPTBigCodeModel:()=>Tu,GPTBigCodePreTrainedModel:()=>wa,GPTJForCausalLM:()=>Mu,GPTJModel:()=>xu,GPTJPreTrainedModel:()=>ya,GPTNeoForCausalLM:()=>wu,GPTNeoModel:()=>yu,GPTNeoPreTrainedModel:()=>Hn,GPTNeoXForCausalLM:()=>bu,GPTNeoXModel:()=>vu,GPTNeoXPreTrainedModel:()=>_a,Gemma2ForCausalLM:()=>Iu,Gemma2Model:()=>Au,Gemma2PreTrainedModel:()=>xa,GemmaForCausalLM:()=>$u,GemmaModel:()=>Pu,GemmaPreTrainedModel:()=>ba,HubertForCTC:()=>Qc,HubertForSequenceClassification:()=>Za,HubertModel:()=>sp,HubertPreTrainedModel:()=>op,ImageMattingOutput:()=>ef,LlamaForCausalLM:()=>Su,LlamaModel:()=>ni,LlamaPreTrainedModel:()=>Ps,LlavaForConditionalGeneration:()=>go,LlavaPreTrainedModel:()=>su,LongT5ForConditionalGeneration:()=>Uo,LongT5Model:()=>jo,LongT5PreTrainedModel:()=>ho,M2M100ForConditionalGeneration:()=>Vc,M2M100Model:()=>Uc,M2M100PreTrainedModel:()=>qa,MBartForCausalLM:()=>xt,MBartForConditionalGeneration:()=>Oe,MBartForSequenceClassification:()=>nt,MBartModel:()=>ze,MBartPreTrainedModel:()=>Pe,MPNetForMaskedLM:()=>Oo,MPNetForQuestionAnswering:()=>Ro,MPNetForSequenceClassification:()=>Do,MPNetForTokenClassification:()=>Lo,MPNetModel:()=>ks,MPNetPreTrainedModel:()=>xi,MT5ForConditionalGeneration:()=>Br,MT5Model:()=>Vo,MT5PreTrainedModel:()=>mo,MarianMTModel:()=>jc,MarianModel:()=>np,MarianPreTrainedModel:()=>Ga,MaskedLMOutput:()=>yn,MistralForCausalLM:()=>Ns,MistralModel:()=>Bs,MistralPreTrainedModel:()=>rl,MobileBertForMaskedLM:()=>ci,MobileBertForQuestionAnswering:()=>Ri,MobileBertForSequenceClassification:()=>Fr,MobileBertModel:()=>Wr,MobileBertPreTrainedModel:()=>mn,MobileNetV1ForImageClassification:()=>cp,MobileNetV1Model:()=>hd,MobileNetV1PreTrainedModel:()=>fl,MobileNetV2ForImageClassification:()=>gd,MobileNetV2Model:()=>md,MobileNetV2PreTrainedModel:()=>pl,MobileNetV3ForImageClassification:()=>dp,MobileNetV3Model:()=>_d,MobileNetV3PreTrainedModel:()=>hl,MobileNetV4ForImageClassification:()=>ml,MobileNetV4Model:()=>Qo,MobileNetV4PreTrainedModel:()=>Ko,MobileViTForImageClassification:()=>Ju,MobileViTModel:()=>Zu,MobileViTPreTrainedModel:()=>Yu,MobileViTV2ForImageClassification:()=>ec,MobileViTV2Model:()=>rp,MobileViTV2PreTrainedModel:()=>Ca,ModelOutput:()=>me,Moondream1ForConditionalGeneration:()=>or,MptForCausalLM:()=>Uu,MptModel:()=>tp,MptPreTrainedModel:()=>As,MusicgenForCausalLM:()=>pm,MusicgenForConditionalGeneration:()=>dl,MusicgenModel:()=>up,MusicgenPreTrainedModel:()=>cl,NomicBertModel:()=>je,NomicBertPreTrainedModel:()=>Te,OPTForCausalLM:()=>Wu,OPTModel:()=>Vu,OPTPreTrainedModel:()=>Ea,OpenELMForCausalLM:()=>zu,OpenELMModel:()=>Fu,OpenELMPreTrainedModel:()=>Qn,OwlViTForObjectDetection:()=>rc,OwlViTModel:()=>tc,OwlViTPreTrainedModel:()=>vr,Owlv2ForObjectDetection:()=>ic,Owlv2Model:()=>nc,Owlv2PreTrainedModel:()=>Pa,Phi3ForCausalLM:()=>Sa,Phi3Model:()=>Bu,Phi3PreTrainedModel:()=>ka,PhiForCausalLM:()=>Ru,PhiModel:()=>Lu,PhiPreTrainedModel:()=>Ta,PreTrainedModel:()=>X,PretrainedMixin:()=>Or,PyAnnoteForAudioFrameClassification:()=>Vi,PyAnnoteModel:()=>Ha,PyAnnotePreTrainedModel:()=>ki,QuestionAnsweringModelOutput:()=>wn,Qwen2ForCausalLM:()=>Du,Qwen2Model:()=>Ou,Qwen2PreTrainedModel:()=>Ma,RTDetrForObjectDetection:()=>zs,RTDetrModel:()=>dc,RTDetrObjectDetectionOutput:()=>fc,RTDetrPreTrainedModel:()=>wo,ResNetForImageClassification:()=>wc,ResNetModel:()=>yc,ResNetPreTrainedModel:()=>za,RoFormerForMaskedLM:()=>A,RoFormerForQuestionAnswering:()=>se,RoFormerForSequenceClassification:()=>Ae,RoFormerForTokenClassification:()=>$e,RoFormerModel:()=>tt,RoFormerPreTrainedModel:()=>Ye,RobertaForMaskedLM:()=>kn,RobertaForQuestionAnswering:()=>qn,RobertaForSequenceClassification:()=>pn,RobertaForTokenClassification:()=>st,RobertaModel:()=>mr,RobertaPreTrainedModel:()=>Gt,SamImageSegmentationOutput:()=>Nc,SamModel:()=>Bc,SamPreTrainedModel:()=>Rc,SegformerForImageClassification:()=>ud,SegformerForSemanticSegmentation:()=>cd,SegformerModel:()=>fm,SegformerPreTrainedModel:()=>Ho,Seq2SeqLMOutput:()=>mm,SequenceClassifierOutput:()=>ur,SiglipModel:()=>_o,SiglipPreTrainedModel:()=>ha,SiglipTextModel:()=>cu,SiglipVisionModel:()=>du,SpeechT5ForSpeechToText:()=>td,SpeechT5ForTextToSpeech:()=>ap,SpeechT5HifiGan:()=>tl,SpeechT5Model:()=>ed,SpeechT5PreTrainedModel:()=>el,SqueezeBertForMaskedLM:()=>co,SqueezeBertForQuestionAnswering:()=>Mi,SqueezeBertForSequenceClassification:()=>di,SqueezeBertModel:()=>Ss,SqueezeBertPreTrainedModel:()=>Bi,StableLmForCausalLM:()=>dd,StableLmModel:()=>ll,StableLmPreTrainedModel:()=>al,Starcoder2ForCausalLM:()=>il,Starcoder2Model:()=>js,Starcoder2PreTrainedModel:()=>nl,Swin2SRForImageSuperResolution:()=>La,Swin2SRModel:()=>xc,Swin2SRPreTrainedModel:()=>Da,SwinForImageClassification:()=>bc,SwinModel:()=>vc,SwinPreTrainedModel:()=>Oa,T5ForConditionalGeneration:()=>No,T5Model:()=>Bo,T5PreTrainedModel:()=>Zi,TableTransformerForObjectDetection:()=>hc,TableTransformerModel:()=>pc,TableTransformerObjectDetectionOutput:()=>mc,TableTransformerPreTrainedModel:()=>Ia,TokenClassifierOutput:()=>dn,TrOCRForCausalLM:()=>nd,TrOCRPreTrainedModel:()=>rd,UniSpeechForCTC:()=>Gc,UniSpeechForSequenceClassification:()=>qc,UniSpeechModel:()=>Qa,UniSpeechPreTrainedModel:()=>vo,UniSpeechSatForAudioFrameClassification:()=>Ds,UniSpeechSatForCTC:()=>Xa,UniSpeechSatForSequenceClassification:()=>Hc,UniSpeechSatModel:()=>Os,UniSpeechSatPreTrainedModel:()=>Go,ViTForImageClassification:()=>qu,ViTModel:()=>Gu,ViTPreTrainedModel:()=>yo,VisionEncoderDecoderModel:()=>fa,VitMatteForImageMatting:()=>Xu,VitMattePreTrainedModel:()=>Qu,VitsModel:()=>sl,VitsModelOutput:()=>Mp,VitsPreTrainedModel:()=>lp,Wav2Vec2BertForCTC:()=>Rs,Wav2Vec2BertForSequenceClassification:()=>Kc,Wav2Vec2BertModel:()=>Ya,Wav2Vec2BertPreTrainedModel:()=>Ls,Wav2Vec2ForAudioFrameClassification:()=>Ui,Wav2Vec2ForCTC:()=>ip,Wav2Vec2ForSequenceClassification:()=>ji,Wav2Vec2Model:()=>Wc,Wav2Vec2PreTrainedModel:()=>Ni,WavLMForAudioFrameClassification:()=>Jc,WavLMForCTC:()=>Ja,WavLMForSequenceClassification:()=>Yc,WavLMForXVector:()=>Zc,WavLMModel:()=>Xc,WavLMPreTrainedModel:()=>Si,WeSpeakerResNetModel:()=>Ka,WeSpeakerResNetPreTrainedModel:()=>_n,WhisperForConditionalGeneration:()=>da,WhisperModel:()=>Vt,WhisperPreTrainedModel:()=>gt,XLMForQuestionAnswering:()=>gn,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>Bn,XLMModel:()=>an,XLMPreTrainedModel:()=>xr,XLMRobertaForMaskedLM:()=>Ct,XLMRobertaForQuestionAnswering:()=>Gr,XLMRobertaForSequenceClassification:()=>wr,XLMRobertaForTokenClassification:()=>zr,XLMRobertaModel:()=>kr,XLMRobertaPreTrainedModel:()=>Tr,XLMWithLMHeadModel:()=>$n,XVectorOutput:()=>Jd,YolosForObjectDetection:()=>Dc,YolosModel:()=>Oc,YolosObjectDetectionOutput:()=>Lc,YolosPreTrainedModel:()=>Wa});var o=n("./src/configs.js"),a=n("./src/backends/onnx.js"),l=n("./src/utils/dtypes.js"),f=n("./src/utils/generic.js"),_=n("./src/utils/core.js"),h=n("./src/utils/hub.js"),g=n("./src/generation/logits_process.js"),M=n("./src/generation/configuration_utils.js"),w=n("./src/utils/tensor.js"),C=n("./src/utils/maths.js"),k=n("./src/generation/stopping_criteria.js"),z=n("./src/generation/logits_sampler.js"),S=n("./src/env.js"),P=n("./src/models/whisper/generation_whisper.js"),y=n("./src/models/whisper/common_whisper.js");const x={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},I=new Map,U=new Map,O=new Map;async function N(V,G,ie){let Ee=ie.device;Ee&&typeof Ee!="string"&&(Ee.hasOwnProperty(G)?Ee=Ee[G]:(console.warn(`device not specified for "${G}". Using the default device.`),Ee=null));const Ze=Ee??(S.apis.IS_NODE_ENV?"cpu":"wasm"),it=(0,a.deviceToExecutionProviders)(Ze);let _t=ie.dtype;typeof _t!="string"&&(_t&&_t.hasOwnProperty(G)?_t=_t[G]:(_t=l.DEFAULT_DEVICE_DTYPE_MAPPING[Ze]??l.DATA_TYPES.fp32,console.warn(`dtype not specified for "${G}". Using the default dtype (${_t}) for this device (${Ze}).`)));const Et=_t;if(l.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Et)){if(Et===l.DATA_TYPES.fp16&&Ze==="webgpu"&&!await(0,l.isWebGpuFp16Supported)())throw new Error(`The device (${Ze}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Et}. Should be one of: ${Object.keys(l.DATA_TYPES).join(", ")}`);const Wt=l.DEFAULT_DTYPE_SUFFIX_MAPPING[Et],cr=`${ie.subfolder??""}/${G}${Wt}.onnx`,sr={...ie.session_options};sr.executionProviders??(sr.executionProviders=it);const $r=(0,h.getModelFile)(V,cr,!0,ie);let dr=[];if(ie.use_external_data_format&&(ie.use_external_data_format===!0||typeof ie.use_external_data_format=="object"&&ie.use_external_data_format.hasOwnProperty(G)&&ie.use_external_data_format[G]===!0)){if(S.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const fr=`${G}${Wt}.onnx_data`,gr=`${ie.subfolder??""}/${fr}`;dr.push(new Promise(async(br,Dr)=>{const En=await(0,h.getModelFile)(V,gr,!0,ie);br({path:fr,data:En})}))}else sr.externalData!==void 0&&(dr=sr.externalData.map(async fr=>{if(typeof fr.data=="string"){const gr=await(0,h.getModelFile)(V,fr.data,!0,ie);return{...fr,data:gr}}return fr}));if(dr.length>0&&(sr.externalData=await Promise.all(dr)),Ze==="webgpu"){const fr=(0,o.getKeyValueShapes)(ie.config,{prefix:"present"});if(Object.keys(fr).length>0&&!(0,a.isONNXProxy)()){const gr={};for(const br in fr)gr[br]="gpu-buffer";sr.preferredOutputLocation=gr}}return{buffer:await $r,session_options:sr}}async function j(V,G,ie){return Object.fromEntries(await Promise.all(Object.keys(G).map(async Ee=>{const{buffer:Ze,session_options:it}=await N(V,G[Ee],ie),_t=await(0,a.createInferenceSession)(Ze,it);return[Ee,_t]})))}function D(V,G){const ie=Object.create(null),Ee=[];for(const _t of V.inputNames){const Et=G[_t];if(!(Et instanceof w.Tensor)){Ee.push(_t);continue}ie[_t]=(0,a.isONNXProxy)()?Et.clone():Et}if(Ee.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Ee.join(", ")}.`);const Ze=Object.keys(G).length,it=V.inputNames.length;if(Ze>it){let _t=Object.keys(G).filter(Et=>!V.inputNames.includes(Et));console.warn(`WARNING: Too many inputs were provided (${Ze} > ${it}). The following inputs will be ignored: "${_t.join(", ")}".`)}return ie}async function Y(V,G){const ie=D(V,G);try{const Ee=Object.fromEntries(Object.entries(ie).map(([it,_t])=>[it,_t.ort_tensor]));let Ze=await V.run(Ee);return Ze=de(Ze),Ze}catch(Ee){throw console.error(`An error occurred during model execution: "${Ee}".`),console.error("Inputs given to model:",ie),Ee}}function de(V){for(let G in V)(0,a.isONNXTensor)(V[G])?V[G]=new w.Tensor(V[G]):typeof V[G]=="object"&&de(V[G]);return V}function Ce(V){if(V instanceof w.Tensor)return V;if(V.length===0)throw Error("items must be non-empty");if(Array.isArray(V[0])){if(V.some(G=>G.length!==V[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new w.Tensor("int64",BigInt64Array.from(V.flat().map(G=>BigInt(G))),[V.length,V[0].length])}else return new w.Tensor("int64",BigInt64Array.from(V.map(G=>BigInt(G))),[1,V.length])}function ee(V){return new w.Tensor("bool",[V],[1])}async function ye(V,G){let{encoder_outputs:ie,input_ids:Ee,decoder_input_ids:Ze,...it}=G;if(!ie){const Et=(0,_.pick)(G,V.sessions.model.inputNames);ie=(await R(V,Et)).last_hidden_state}return it.input_ids=Ze,it.encoder_hidden_states=ie,V.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(it.encoder_attention_mask=G.attention_mask),await Me(V,it,!0)}async function R(V,G){const ie=V.sessions.model,Ee=(0,_.pick)(G,ie.inputNames);if(ie.inputNames.includes("inputs_embeds")&&!Ee.inputs_embeds){if(!G.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Ee.inputs_embeds=await V.encode_text({input_ids:G.input_ids})}return ie.inputNames.includes("token_type_ids")&&!Ee.token_type_ids&&(Ee.token_type_ids=new w.Tensor("int64",new BigInt64Array(Ee.input_ids.data.length),Ee.input_ids.dims)),await Y(ie,Ee)}async function Me(V,G,ie=!1){const Ee=V.sessions[ie?"decoder_model_merged":"model"],{past_key_values:Ze,...it}=G;Ee.inputNames.includes("use_cache_branch")&&(it.use_cache_branch=ee(!!Ze)),Ee.inputNames.includes("position_ids")&&it.attention_mask&&!it.position_ids&&(it.position_ids=ge(it,Ze)),V.addPastKeyValues(it,Ze);const _t=(0,_.pick)(it,Ee.inputNames);return await Y(Ee,_t)}async function Qe(V,{input_ids:G=null,attention_mask:ie=null,pixel_values:Ee=null,position_ids:Ze=null,inputs_embeds:it=null,past_key_values:_t=null,generation_config:Et=null,logits_processor:Wt=null,...cr}){if(!it){if(it=await V.encode_text({input_ids:G}),Ee&&G.dims[1]!==1){const $r=await V.encode_image({pixel_values:Ee});({inputs_embeds:it,attention_mask:ie}=V._merge_input_ids_with_image_features({image_features:$r,inputs_embeds:it,input_ids:G,attention_mask:ie}))}else if(_t&&Ee&&G.dims[1]===1){const $r=G.dims[1],dr=Object.values(_t)[0].dims.at(-2);ie=(0,w.cat)([(0,w.ones)([G.dims[0],dr]),ie.slice(null,[ie.dims[1]-$r,ie.dims[1]])],1)}}return await Me(V,{inputs_embeds:it,past_key_values:_t,attention_mask:ie,position_ids:Ze,generation_config:Et,logits_processor:Wt},!0)}function ge(V,G=null){const{input_ids:ie,inputs_embeds:Ee,attention_mask:Ze}=V,[it,_t]=Ze.dims,Et=new BigInt64Array(Ze.data.length);for(let cr=0;cr<it;++cr){const sr=cr*_t;let $r=BigInt(0);for(let dr=0;dr<_t;++dr){const _r=sr+dr;Ze.data[_r]===0n?Et[_r]=BigInt(1):(Et[_r]=$r,$r+=Ze.data[_r])}}let Wt=new w.Tensor("int64",Et,Ze.dims);if(G){const cr=-(ie??Ee).dims.at(1);Wt=Wt.slice(null,[cr,null])}return Wt}function Q(V,G,ie,Ee){if(ie.past_key_values){const Ze=Object.values(ie.past_key_values)[0].dims.at(-2),{input_ids:it,attention_mask:_t}=ie;if(!(_t&&_t.dims[1]>it.dims[1])){if(Ze<it.dims[1])ie.input_ids=it.slice(null,[Ze,null]);else if(V.config.image_token_index!=null&&it.data.some(Et=>Et==V.config.image_token_index)){const Et=V.config.num_image_tokens;if(!Et)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=it.dims[1]-(Ze-Et);ie.input_ids=it.slice(null,[-Wt,null]),ie.attention_mask=(0,w.ones)([1,Ze+Wt])}}}return ie}function ae(V,G,ie,Ee){return ie.past_key_values&&(G=G.map(Ze=>[Ze.at(-1)])),{...ie,decoder_input_ids:Ce(G)}}function Se(V,...G){return V.config.is_encoder_decoder?ae(V,...G):Q(V,...G)}class X extends f.Callable{constructor(ie,Ee){super();qe(this,"main_input_name","input_ids");qe(this,"forward_params",["input_ids","attention_mask"]);this.config=ie,this.sessions=Ee;const Ze=O.get(this.constructor),it=I.get(Ze);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,it){case x.DecoderOnly:this.can_generate=!0,this._forward=Me,this._prepare_inputs_for_generation=Q;break;case x.Seq2Seq:case x.Vision2Seq:case x.Musicgen:this.can_generate=!0,this._forward=ye,this._prepare_inputs_for_generation=ae;break;case x.EncoderDecoder:this._forward=ye;break;case x.ImageTextToText:this.can_generate=!0,this._forward=Qe,this._prepare_inputs_for_generation=Se;break;default:this._forward=R;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Ee;const ie=[];for(const Ze of Object.values(this.sessions))(Ee=Ze==null?void 0:Ze.handler)!=null&&Ee.dispose&&ie.push(Ze.handler.dispose());return await Promise.all(ie)}static async from_pretrained(ie,{progress_callback:Ee=null,config:Ze=null,cache_dir:it=null,local_files_only:_t=!1,revision:Et="main",model_file_name:Wt=null,subfolder:cr="onnx",device:sr=null,dtype:$r=null,use_external_data_format:dr=null,session_options:_r={}}={}){let fr={progress_callback:Ee,config:Ze,cache_dir:it,local_files_only:_t,revision:Et,model_file_name:Wt,subfolder:cr,device:sr,dtype:$r,use_external_data_format:dr,session_options:_r};const gr=O.get(this),br=I.get(gr);Ze=fr.config=await o.AutoConfig.from_pretrained(ie,fr);let Dr;if(br===x.DecoderOnly)Dr=await Promise.all([j(ie,{model:fr.model_file_name??"model"},fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)]);else if(br===x.Seq2Seq||br===x.Vision2Seq)Dr=await Promise.all([j(ie,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)]);else if(br===x.MaskGeneration)Dr=await Promise.all([j(ie,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},fr)]);else if(br===x.EncoderDecoder)Dr=await Promise.all([j(ie,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},fr)]);else if(br===x.ImageTextToText){const En={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ze.is_encoder_decoder&&(En.model="encoder_model"),Dr=await Promise.all([j(ie,En,fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)])}else br===x.Musicgen?Dr=await Promise.all([j(ie,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)]):(br!==x.EncoderOnly&&console.warn(`Model type for '${gr??(Ze==null?void 0:Ze.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Dr=await Promise.all([j(ie,{model:fr.model_file_name??"model"},fr)]));return new this(Ze,...Dr)}async _call(ie){return await this.forward(ie)}async forward(ie){return await this._forward(this,ie)}_get_logits_warper(ie){const Ee=new g.LogitsProcessorList;return ie.temperature!==null&&ie.temperature!==1&&Ee.push(new g.TemperatureLogitsWarper(ie.temperature)),ie.top_k!==null&&ie.top_k!==0&&Ee.push(new g.TopKLogitsWarper(ie.top_k)),ie.top_p!==null&&ie.top_p<1&&Ee.push(new g.TopPLogitsWarper(ie.top_p)),Ee}_get_logits_processor(ie,Ee,Ze=null){const it=new g.LogitsProcessorList;if(ie.repetition_penalty!==null&&ie.repetition_penalty!==1&&it.push(new g.RepetitionPenaltyLogitsProcessor(ie.repetition_penalty)),ie.no_repeat_ngram_size!==null&&ie.no_repeat_ngram_size>0&&it.push(new g.NoRepeatNGramLogitsProcessor(ie.no_repeat_ngram_size)),ie.bad_words_ids!==null&&it.push(new g.NoBadWordsLogitsProcessor(ie.bad_words_ids,ie.eos_token_id)),ie.min_length!==null&&ie.eos_token_id!==null&&ie.min_length>0&&it.push(new g.MinLengthLogitsProcessor(ie.min_length,ie.eos_token_id)),ie.min_new_tokens!==null&&ie.eos_token_id!==null&&ie.min_new_tokens>0&&it.push(new g.MinNewTokensLengthLogitsProcessor(Ee,ie.min_new_tokens,ie.eos_token_id)),ie.forced_bos_token_id!==null&&it.push(new g.ForcedBOSTokenLogitsProcessor(ie.forced_bos_token_id)),ie.forced_eos_token_id!==null&&it.push(new g.ForcedEOSTokenLogitsProcessor(ie.max_length,ie.forced_eos_token_id)),ie.begin_suppress_tokens!==null){const _t=Ee>1||ie.forced_bos_token_id===null?Ee:Ee+1;it.push(new g.SuppressTokensAtBeginLogitsProcessor(ie.begin_suppress_tokens,_t))}return ie.guidance_scale!==null&&ie.guidance_scale>1&&it.push(new g.ClassifierFreeGuidanceLogitsProcessor(ie.guidance_scale)),Ze!==null&&it.extend(Ze),it}_prepare_generation_config(ie,Ee,Ze=M.GenerationConfig){const it={...this.config};for(const Et of["decoder","generator","text_config"])Et in it&&Object.assign(it,it[Et]);const _t=new Ze(it);return"generation_config"in this&&Object.assign(_t,this.generation_config),ie&&Object.assign(_t,ie),Ee&&Object.assign(_t,(0,_.pick)(Ee,Object.getOwnPropertyNames(_t))),_t}_get_stopping_criteria(ie,Ee=null){const Ze=new k.StoppingCriteriaList;return ie.max_length!==null&&Ze.push(new k.MaxLengthCriteria(ie.max_length,this.config.max_position_embeddings??null)),ie.eos_token_id!==null&&Ze.push(new k.EosTokenCriteria(ie.eos_token_id)),Ee&&Ze.extend(Ee),Ze}_validate_model_class(){if(!this.can_generate){const ie=[Vs,_l,gl,Us],Ee=O.get(this.constructor),Ze=new Set,it=this.config.model_type;for(const Et of ie){const Wt=Et.get(it);Wt&&Ze.add(Wt[0])}let _t=`The current model class (${Ee}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ze.size>0&&(_t+=` Please use the following class instead: ${[...Ze].join(", ")}`),Error(_t)}}prepare_inputs_for_generation(...ie){return this._prepare_inputs_for_generation(this,...ie)}_update_model_kwargs_for_generation({generated_input_ids:ie,outputs:Ee,model_inputs:Ze,is_encoder_decoder:it}){return Ze.past_key_values=this.getPastKeyValues(Ee,Ze.past_key_values),Ze.input_ids=new w.Tensor("int64",ie.flat(),[ie.length,1]),it||(Ze.attention_mask=(0,w.cat)([Ze.attention_mask,(0,w.ones)([Ze.attention_mask.dims[0],1])],1)),Ze.position_ids=null,Ze}_prepare_model_inputs({inputs:ie,bos_token_id:Ee,model_kwargs:Ze}){const it=(0,_.pick)(Ze,this.forward_params),_t=this.main_input_name;if(_t in it){if(ie)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else it[_t]=ie;return{inputs_tensor:it[_t],model_inputs:it,model_input_name:_t}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ie,model_inputs:Ee,model_input_name:Ze,generation_config:it}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Ee.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Et,pixel_values:Wt,attention_mask:cr,...sr}=Ee,$r=await this._prepare_inputs_embeds(Ee);Ee={...sr,...(0,_.pick)($r,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_t}=await R(this,Ee);if(it.guidance_scale!==null&&it.guidance_scale>1)_t=(0,w.cat)([_t,(0,w.full_like)(_t,0)],0),"attention_mask"in Ee&&(Ee.attention_mask=(0,w.cat)([Ee.attention_mask,(0,w.zeros_like)(Ee.attention_mask)],0));else if(Ee.decoder_input_ids){const Et=Ce(Ee.decoder_input_ids).dims[0];if(Et!==_t.dims[0]){if(_t.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_t.dims[0]}) than the decoder inputs (${Et}).`);_t=(0,w.cat)(Array.from({length:Et},()=>_t),0)}}return Ee.encoder_outputs=_t,Ee}_prepare_decoder_input_ids_for_generation({batch_size:ie,model_input_name:Ee,model_kwargs:Ze,decoder_start_token_id:it,bos_token_id:_t,generation_config:Et}){let{decoder_input_ids:Wt,...cr}=Ze;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:ie},()=>Wt));else if(it??(it=_t),this.config.model_type==="musicgen")Wt=Array.from({length:ie*this.config.decoder.num_codebooks},()=>[it]);else if(Array.isArray(it)){if(it.length!==ie)throw new Error(`\`decoder_start_token_id\` expcted to have length ${ie} but got ${it.length}`);Wt=it}else Wt=Array.from({length:ie},()=>[it]);return Wt=Ce(Wt),Ze.decoder_attention_mask=(0,w.ones_like)(Wt),{input_ids:Wt,model_inputs:cr}}async generate({inputs:ie=null,generation_config:Ee=null,logits_processor:Ze=null,stopping_criteria:it=null,streamer:_t=null,...Et}){this._validate_model_class(),Ee=this._prepare_generation_config(Ee,Et);let{inputs_tensor:Wt,model_inputs:cr,model_input_name:sr}=this._prepare_model_inputs({inputs:ie,model_kwargs:Et});const $r=this.config.is_encoder_decoder;$r&&("encoder_outputs"in cr||(cr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:cr,model_input_name:sr,generation_config:Ee})));let dr;$r?{input_ids:dr,model_inputs:cr}=this._prepare_decoder_input_ids_for_generation({batch_size:cr[sr].dims.at(0),model_input_name:sr,model_kwargs:cr,decoder_start_token_id:Ee.decoder_start_token_id,bos_token_id:Ee.bos_token_id,generation_config:Ee}):dr=cr[sr];let _r=dr.dims.at(-1);Ee.max_new_tokens!==null&&(Ee.max_length=_r+Ee.max_new_tokens);const fr=this._get_logits_processor(Ee,_r,Ze),gr=this._get_stopping_criteria(Ee,it),br=cr[sr].dims.at(0),Dr=z.LogitsSampler.getSampler(Ee),En=new Array(br).fill(0),An=dr.tolist();_t&&_t.put(An);let Ei=null,vn={};for(;;){cr=this.prepare_inputs_for_generation(An,cr,Ee);const bn=await this.forward(cr);if(Ee.output_attentions&&Ee.return_dict_in_generate){const pi=this.getAttentions(bn);for(const Yo in pi)Yo in vn||(vn[Yo]=[]),vn[Yo].push(pi[Yo])}const Ws=bn.logits.slice(null,-1,null),Gs=fr(An,Ws),Ml=[];for(let pi=0;pi<Gs.dims.at(0);++pi){const Yo=Gs[pi],Tp=await Dr(Yo);for(const[kp,Sp]of Tp){const tf=BigInt(kp);En[pi]+=Sp,An[pi].push(tf),Ml.push([tf]);break}}if(_t&&_t.put(Ml),gr(An).every(pi=>pi)){Ee.return_dict_in_generate&&(Ei=this.getPastKeyValues(bn,cr.past_key_values,!1));break}cr=this._update_model_kwargs_for_generation({generated_input_ids:Ml,outputs:bn,model_inputs:cr,is_encoder_decoder:$r})}_t&&_t.end();const ln=new w.Tensor("int64",An.flat(),[An.length,An[0].length]);return Ee.return_dict_in_generate?{sequences:ln,past_key_values:Ei,...vn}:ln}getPastKeyValues(ie,Ee,Ze=!0){const it=Object.create(null);for(const _t in ie)if(_t.startsWith("present")){const Et=_t.replace("present","past_key_values");if(Ee&&_t.includes("encoder"))it[Et]=Ee[Et];else{if(Ze&&Ee){const Wt=Ee[Et];Wt.location==="gpu-buffer"&&Wt.dispose()}it[Et]=ie[_t]}}return it}getAttentions(ie){const Ee={};for(const Ze of["cross_attentions","encoder_attentions","decoder_attentions"])for(const it in ie)it.startsWith(Ze)&&(Ze in Ee||(Ee[Ze]=[]),Ee[Ze].push(ie[it]));return Ee}addPastKeyValues(ie,Ee){if(Ee)Object.assign(ie,Ee);else{const Ze=this.custom_config.kv_cache_dtype??"float32",it=Ze==="float16"?new Uint16Array:[],_t=(0,o.getKeyValueShapes)(this.config);for(const Et in _t)ie[Et]=new w.Tensor(Ze,it,_t[Et])}}async encode_image({pixel_values:ie}){const Ee=(await Y(this.sessions.vision_encoder,{pixel_values:ie})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${Ee.dims[1]}).`),this.config.num_image_tokens=Ee.dims[1]),Ee}async encode_text({input_ids:ie}){return(await Y(this.sessions.embed_tokens,{input_ids:ie})).inputs_embeds}}class me{}class Ke extends me{constructor({last_hidden_state:G,hidden_states:ie=null,attentions:Ee=null}){super(),this.last_hidden_state=G,this.hidden_states=ie,this.attentions=Ee}}class De extends X{}class Be extends De{}class We extends De{async _call(G){return new yn(await super._call(G))}}class ot extends De{async _call(G){return new ur(await super._call(G))}}class dt extends De{async _call(G){return new dn(await super._call(G))}}class Ge extends De{async _call(G){return new wn(await super._call(G))}}class Te extends X{}class je extends Te{}class Ye extends X{}class tt extends Ye{}class A extends Ye{async _call(G){return new yn(await super._call(G))}}class Ae extends Ye{async _call(G){return new ur(await super._call(G))}}class $e extends Ye{async _call(G){return new dn(await super._call(G))}}class se extends Ye{async _call(G){return new wn(await super._call(G))}}class te extends X{}class we extends te{}class B extends te{async _call(G){return new yn(await super._call(G))}}class J extends te{async _call(G){return new ur(await super._call(G))}}class L extends te{async _call(G){return new dn(await super._call(G))}}class ue extends te{async _call(G){return new wn(await super._call(G))}}class le extends X{}class ke extends le{}class Ne extends le{async _call(G){return new yn(await super._call(G))}}class ut extends le{async _call(G){return new ur(await super._call(G))}}class Je extends le{async _call(G){return new dn(await super._call(G))}}class Ve extends le{async _call(G){return new wn(await super._call(G))}}class Z extends X{}class ve extends Z{}class Re extends Z{async _call(G){return new yn(await super._call(G))}}class He extends Z{async _call(G){return new ur(await super._call(G))}}class Xe extends Z{async _call(G){return new dn(await super._call(G))}}class rt extends Z{async _call(G){return new wn(await super._call(G))}}class ft extends X{}class ht extends ft{}class Mt extends ft{async _call(G){return new yn(await super._call(G))}}class wt extends ft{async _call(G){return new ur(await super._call(G))}}class St extends ft{async _call(G){return new dn(await super._call(G))}}class Rt extends ft{async _call(G){return new wn(await super._call(G))}}class at extends X{}class Ot extends at{}class Ut extends at{async _call(G){return new yn(await super._call(G))}}class Kt extends at{async _call(G){return new ur(await super._call(G))}}class Qt extends at{async _call(G){return new dn(await super._call(G))}}class Jt extends at{async _call(G){return new wn(await super._call(G))}}class qt extends X{}class Er extends qt{}class Qr extends qt{async _call(G){return new ur(await super._call(G))}}class Cr extends qt{async _call(G){return new dn(await super._call(G))}}class mt extends qt{async _call(G){return new wn(await super._call(G))}}class Pt extends qt{async _call(G){return new yn(await super._call(G))}}class Bt extends X{}class sn extends Bt{}class Li extends Bt{async _call(G){return new yn(await super._call(G))}}class bi extends Bt{async _call(G){return new ur(await super._call(G))}}class Nr extends Bt{async _call(G){return new dn(await super._call(G))}}class mn extends X{}class Wr extends mn{}class ci extends mn{async _call(G){return new yn(await super._call(G))}}class Fr extends mn{async _call(G){return new ur(await super._call(G))}}class Ri extends mn{async _call(G){return new wn(await super._call(G))}}class xi extends X{}class ks extends xi{}class Oo extends xi{async _call(G){return new yn(await super._call(G))}}class Do extends xi{async _call(G){return new ur(await super._call(G))}}class Lo extends xi{async _call(G){return new dn(await super._call(G))}}class Ro extends xi{async _call(G){return new wn(await super._call(G))}}class Bi extends X{}class Ss extends Bi{}class co extends Bi{async _call(G){return new yn(await super._call(G))}}class di extends Bi{async _call(G){return new ur(await super._call(G))}}class Mi extends Bi{async _call(G){return new wn(await super._call(G))}}class Ti extends X{}class Yi extends Ti{}class fo extends Ti{async _call(G){return new ur(await super._call(G))}}class po extends Ti{async _call(G){return new wn(await super._call(G))}}class Xt extends Ti{async _call(G){return new yn(await super._call(G))}}class Zi extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class Bo extends Zi{}class No extends Zi{}class ho extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class jo extends ho{}class Uo extends ho{}class mo extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Vo extends mo{}class Br extends mo{}class Rn extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Ue extends Rn{}class W extends Rn{}class fe extends Rn{async _call(G){return new ur(await super._call(G))}}class Pe extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ze extends Pe{}class Oe extends Pe{}class nt extends Pe{async _call(G){return new ur(await super._call(G))}}class xt extends Pe{}class kt extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Tt extends kt{}class At extends kt{}class Zt extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Pr extends Zt{}class rr extends Zt{}class Gt extends X{}class mr extends Gt{}class kn extends Gt{async _call(G){return new yn(await super._call(G))}}class pn extends Gt{async _call(G){return new ur(await super._call(G))}}class st extends Gt{async _call(G){return new dn(await super._call(G))}}class qn extends Gt{async _call(G){return new wn(await super._call(G))}}class xr extends X{}class an extends xr{}class $n extends xr{async _call(G){return new yn(await super._call(G))}}class Yt extends xr{async _call(G){return new ur(await super._call(G))}}class Bn extends xr{async _call(G){return new dn(await super._call(G))}}class gn extends xr{async _call(G){return new wn(await super._call(G))}}class Tr extends X{}class kr extends Tr{}class Ct extends Tr{async _call(G){return new yn(await super._call(G))}}class wr extends Tr{async _call(G){return new ur(await super._call(G))}}class zr extends Tr{async _call(G){return new dn(await super._call(G))}}class Gr extends Tr{async _call(G){return new wn(await super._call(G))}}class Nn extends X{}class Dt extends Nn{}class Es extends Nn{}class gt extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"requires_attention_mask",!1);qe(this,"main_input_name","input_features");qe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class Vt extends gt{}class da extends gt{_prepare_generation_config(G,ie){return super._prepare_generation_config(G,ie,P.WhisperGenerationConfig)}_retrieve_init_tokens(G){const ie=[G.decoder_start_token_id];let Ee=G.language;const Ze=G.task;if(G.is_multilingual){Ee||(console.warn("No language specified - defaulting to English (en)."),Ee="en");const _t=`<|${(0,y.whisper_language_to_code)(Ee)}|>`;ie.push(G.lang_to_id[_t]),ie.push(G.task_to_id[Ze??"transcribe"])}else if(Ee||Ze)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!G.return_timestamps&&G.no_timestamps_token_id&&ie.at(-1)!==G.no_timestamps_token_id?ie.push(G.no_timestamps_token_id):G.return_timestamps&&ie.at(-1)===G.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),ie.pop()),ie.filter(it=>it!=null)}async generate({inputs:G=null,generation_config:ie=null,logits_processor:Ee=null,stopping_criteria:Ze=null,...it}){ie=this._prepare_generation_config(ie,it);const _t=it.decoder_input_ids??this._retrieve_init_tokens(ie);if(ie.return_timestamps&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.WhisperTimeStampLogitsProcessor(ie,_t))),ie.begin_suppress_tokens&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.SuppressTokensAtBeginLogitsProcessor(ie.begin_suppress_tokens,_t.length))),ie.return_token_timestamps){if(!ie.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");ie.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),ie.output_attentions=!0,ie.return_dict_in_generate=!0}const Et=await super.generate({inputs:G,generation_config:ie,logits_processor:Ee,decoder_input_ids:_t,...it});return ie.return_token_timestamps&&(Et.token_timestamps=this._extract_token_timestamps(Et,ie.alignment_heads,ie.num_frames)),Et}_extract_token_timestamps(G,ie,Ee=null,Ze=.02){if(!G.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");Ee==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let it=this.config.median_filter_width;it===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),it=7);const _t=G.cross_attentions,Et=Array.from({length:this.config.decoder_layers},(gr,br)=>(0,w.cat)(_t.map(Dr=>Dr[br]),2)),Wt=(0,w.stack)(ie.map(([gr,br])=>{if(gr>=Et.length)throw new Error(`Layer index ${gr} is out of bounds for cross attentions (length ${Et.length}).`);return Ee?Et[gr].slice(null,br,null,[0,Ee]):Et[gr].slice(null,br)})).transpose(1,0,2,3),[cr,sr]=(0,w.std_mean)(Wt,-2,0,!0),$r=Wt.clone();for(let gr=0;gr<$r.dims[0];++gr){const br=$r[gr];for(let Dr=0;Dr<br.dims[0];++Dr){const En=br[Dr],An=cr[gr][Dr][0].data,Ei=sr[gr][Dr][0].data;for(let vn=0;vn<En.dims[0];++vn){let ln=En[vn].data;for(let bn=0;bn<ln.length;++bn)ln[bn]=(ln[bn]-Ei[bn])/An[bn];ln.set((0,C.medianFilter)(ln,it))}}}const dr=[(0,w.mean)($r,1)],_r=G.sequences.dims,fr=new w.Tensor("float32",new Float32Array(_r[0]*_r[1]),_r);for(let gr=0;gr<_r[0];++gr){const br=dr[gr].neg().squeeze_(0),[Dr,En]=(0,C.dynamic_time_warping)(br.tolist()),An=Array.from({length:Dr.length-1},(ln,bn)=>Dr[bn+1]-Dr[bn]),Ei=(0,_.mergeArrays)([1],An).map(ln=>!!ln),vn=[];for(let ln=0;ln<Ei.length;++ln)Ei[ln]&&vn.push(En[ln]*Ze);fr[gr].data.set(vn,1)}return fr}}class fa extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"main_input_name","pixel_values");qe(this,"forward_params",["pixel_values","input_ids","encoder_hidden_states","past_key_values"]);this.generation_config=Ze}}class su extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"forward_params",["input_ids","pixel_values","attention_mask","position_ids","past_key_values"]);this.generation_config=Ze}}class go extends su{_merge_input_ids_with_image_features({inputs_embeds:G,image_features:ie,input_ids:Ee,attention_mask:Ze}){const it=this.config.image_token_index,Et=Ee.tolist().map(dr=>dr.findIndex(_r=>_r==it)),Wt=Et.every(dr=>dr===-1),cr=Et.every(dr=>dr!==-1);if(!Wt&&!cr)throw new Error("Every input should contain either 0 or 1 image token.");if(Wt)return{inputs_embeds:G,attention_mask:Ze};const sr=[],$r=[];for(let dr=0;dr<Et.length;++dr){const _r=Et[dr],fr=G[dr],gr=ie[dr],br=Ze[dr];sr.push((0,w.cat)([fr.slice([0,_r]),gr,fr.slice([_r+1,fr.dims[0]])],0)),$r.push((0,w.cat)([br.slice([0,_r]),(0,w.ones)([gr.dims[0]]),br.slice([_r+1,br.dims[0]])],0))}return{inputs_embeds:(0,w.stack)(sr,0),attention_mask:(0,w.stack)($r,0)}}}class or extends go{}class au extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);qe(this,"main_input_name","inputs_embeds");this.generation_config=Ze}}class pa extends au{_merge_input_ids_with_image_features({inputs_embeds:G,image_features:ie,input_ids:Ee,attention_mask:Ze}){return{inputs_embeds:(0,w.cat)([ie,G],1),attention_mask:(0,w.cat)([(0,w.ones)(ie.dims.slice(0,2)),Ze],1)}}async _prepare_inputs_embeds({input_ids:G,pixel_values:ie,inputs_embeds:Ee,attention_mask:Ze}){if(!G&&!ie)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let it,_t;return G&&(it=await this.encode_text({input_ids:G})),ie&&(_t=await this.encode_image({pixel_values:ie})),it&&_t?{inputs_embeds:Ee,attention_mask:Ze}=this._merge_input_ids_with_image_features({inputs_embeds:it,image_features:_t,input_ids:G,attention_mask:Ze}):Ee=it||_t,{inputs_embeds:Ee,attention_mask:Ze}}async forward({input_ids:G,pixel_values:ie,attention_mask:Ee,decoder_input_ids:Ze,decoder_attention_mask:it,encoder_outputs:_t,past_key_values:Et,inputs_embeds:Wt,decoder_inputs_embeds:cr}){if(Wt||({inputs_embeds:Wt,attention_mask:Ee}=await this._prepare_inputs_embeds({input_ids:G,pixel_values:ie,inputs_embeds:Wt,attention_mask:Ee})),!_t){let{last_hidden_state:dr}=await R(this,{inputs_embeds:Wt,attention_mask:Ee});_t=dr}if(!cr){if(!Ze)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");cr=await this.encode_text({input_ids:Ze})}return await Me(this,{inputs_embeds:cr,attention_mask:it,encoder_attention_mask:Ee,encoder_hidden_states:_t,past_key_values:Et},!0)}}class Wo extends X{}class lu extends Wo{}class fi extends Wo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="text_model"),super.from_pretrained(G,ie)}}class uu extends Wo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="vision_model"),super.from_pretrained(G,ie)}}class ha extends X{}class _o extends ha{}class cu extends ha{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="text_model"),super.from_pretrained(G,ie)}}class du extends Wo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="vision_model"),super.from_pretrained(G,ie)}}class fu extends X{}class pu extends fu{}class ma extends X{}class hu extends ma{}class mu extends ma{}class ga extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class gu extends ga{}class _u extends ga{}class Hn extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class yu extends Hn{}class wu extends Hn{}class _a extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class vu extends _a{}class bu extends _a{}class ya extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class xu extends ya{}class Mu extends ya{}class wa extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Tu extends wa{}class ep extends wa{}class Kn extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ku extends Kn{}class Cs extends Kn{}class Ps extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ni extends Ps{}class Su extends Ps{}class va extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Eu extends va{}class Cu extends va{}class ba extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Pu extends ba{}class $u extends ba{}class xa extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Au extends xa{}class Iu extends xa{}class Qn extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Fu extends Qn{}class zu extends Qn{}class Ma extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Ou extends Ma{}class Du extends Ma{}class Ta extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Lu extends Ta{}class Ru extends Ta{}class ka extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Bu extends ka{}class Sa extends ka{}class $s extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Nu extends $s{}class ju extends $s{}class As extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class tp extends As{}class Uu extends As{}class Ea extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Vu extends Ea{}class Wu extends Ea{}class yo extends X{}class Gu extends yo{}class qu extends yo{async _call(G){return new ur(await super._call(G))}}class Is extends X{}class Hu extends Is{}class Ku extends Is{async _call(G){return new ur(await super._call(G))}}class Qu extends X{}class Xu extends Qu{async _call(G){return new ef(await super._call(G))}}class Yu extends X{}class Zu extends Yu{}class Ju extends Yu{async _call(G){return new ur(await super._call(G))}}class Ca extends X{}class rp extends Ca{}class ec extends Ca{async _call(G){return new ur(await super._call(G))}}class vr extends X{}class tc extends vr{}class rc extends vr{}class Pa extends X{}class nc extends Pa{}class ic extends Pa{}class $a extends X{}class oc extends $a{}class sc extends $a{async _call(G){return new ur(await super._call(G))}}class Fs extends X{}class ac extends Fs{}class lc extends Fs{async _call(G){return new Aa(await super._call(G))}}class uc extends Fs{async _call(G){return new cc(await super._call(G))}}class Aa extends me{constructor({logits:G,pred_boxes:ie}){super(),this.logits=G,this.pred_boxes=ie}}class cc extends me{constructor({logits:G,pred_boxes:ie,pred_masks:Ee}){super(),this.logits=G,this.pred_boxes=ie,this.pred_masks=Ee}}class wo extends X{}class dc extends wo{}class zs extends wo{async _call(G){return new fc(await super._call(G))}}class fc extends me{constructor({logits:G,pred_boxes:ie}){super(),this.logits=G,this.pred_boxes=ie}}class Ia extends X{}class pc extends Ia{}class hc extends Ia{async _call(G){return new mc(await super._call(G))}}class mc extends Aa{}class Fa extends X{}class gc extends Fa{}class _c extends Fa{async _call(G){return new ur(await super._call(G))}}class za extends X{}class yc extends za{}class wc extends za{async _call(G){return new ur(await super._call(G))}}class Oa extends X{}class vc extends Oa{}class bc extends Oa{async _call(G){return new ur(await super._call(G))}}class Da extends X{}class xc extends Da{}class La extends Da{}class Ra extends X{}class Ba extends Ra{}class Na extends Ra{}class Mc extends X{}class Tc extends Mc{}class ja extends X{}class kc extends ja{}class Sc extends ja{}class Ec extends X{}class Ua extends Ec{}class Va extends X{}class Cc extends Va{}class Pc extends Va{async _call(G){return new ur(await super._call(G))}}class $c extends X{}class Ac extends $c{}class Ic extends $c{async _call(G){return new ur(await super._call(G))}}class Xn extends X{}class Fc extends Xn{}class zc extends Xn{async _call(G){return new ur(await super._call(G))}}class Wa extends X{}class Oc extends Wa{}class Dc extends Wa{async _call(G){return new Lc(await super._call(G))}}class Lc extends me{constructor({logits:G,pred_boxes:ie}){super(),this.logits=G,this.pred_boxes=ie}}class Rc extends X{}class Bc extends Rc{async get_image_embeddings({pixel_values:G}){return await R(this,{pixel_values:G})}async forward(G){if((!G.image_embeddings||!G.image_positional_embeddings)&&(G={...G,...await this.get_image_embeddings(G)}),!G.input_labels&&G.input_points){const Ee=G.input_points.dims.slice(0,-1),Ze=Ee.reduce((it,_t)=>it*_t,1);G.input_labels=new w.Tensor("int64",new BigInt64Array(Ze).fill(1n),Ee)}const ie={image_embeddings:G.image_embeddings,image_positional_embeddings:G.image_positional_embeddings};return G.input_points&&(ie.input_points=G.input_points),G.input_labels&&(ie.input_labels=G.input_labels),G.input_boxes&&(ie.input_boxes=G.input_boxes),await Y(this.sessions.prompt_encoder_mask_decoder,ie)}async _call(G){return new Nc(await super._call(G))}}class Nc extends me{constructor({iou_scores:G,pred_masks:ie}){super(),this.iou_scores=G,this.pred_masks=ie}}class Ga extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class np extends Ga{}class jc extends Ga{}class qa extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Uc extends qa{}class Vc extends qa{}class Ni extends X{}class Wc extends Ni{}class ip extends Ni{async _call(G){return new Ji(await super._call(G))}}class ji extends Ni{async _call(G){return new ur(await super._call(G))}}class Ui extends Ni{async _call(G){return new dn(await super._call(G))}}class ki extends X{}class Ha extends ki{}class Vi extends ki{async _call(G){return new dn(await super._call(G))}}class _n extends X{}class Ka extends _n{}class vo extends X{}class Qa extends vo{}class Gc extends vo{async _call(G){return new Ji(await super._call(G))}}class qc extends vo{async _call(G){return new ur(await super._call(G))}}class Go extends X{}class Os extends Go{}class Xa extends Go{async _call(G){return new Ji(await super._call(G))}}class Hc extends Go{async _call(G){return new ur(await super._call(G))}}class Ds extends Go{async _call(G){return new dn(await super._call(G))}}class Ls extends X{}class Ya extends Ls{}class Rs extends Ls{async _call(G){return new Ji(await super._call(G))}}class Kc extends Ls{async _call(G){return new ur(await super._call(G))}}class op extends X{}class sp extends Ni{}class Qc extends Ni{async _call(G){return new Ji(await super._call(G))}}class Za extends Ni{async _call(G){return new ur(await super._call(G))}}class Si extends X{}class Xc extends Si{}class Ja extends Si{async _call(G){return new Ji(await super._call(G))}}class Yc extends Si{async _call(G){return new ur(await super._call(G))}}class Zc extends Si{async _call(G){return new Jd(await super._call(G))}}class Jc extends Si{async _call(G){return new dn(await super._call(G))}}class el extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ed extends el{}class td extends el{}class ap extends el{async generate_speech(G,ie,{threshold:Ee=.5,minlenratio:Ze=0,maxlenratio:it=20,vocoder:_t=null}={}){const Et={input_ids:G},{encoder_outputs:Wt,encoder_attention_mask:cr}=await R(this,Et),sr=Wt.dims[1]/this.config.reduction_factor,$r=Math.floor(sr*it),dr=Math.floor(sr*Ze),_r=this.config.num_mel_bins;let fr=[],gr=null,br=null,Dr=0;for(;;){++Dr;const Ei=ee(!!br);let vn;br?vn=br.output_sequence_out:vn=new w.Tensor("float32",new Float32Array(_r),[1,1,_r]);let ln={use_cache_branch:Ei,output_sequence:vn,encoder_attention_mask:cr,speaker_embeddings:ie,encoder_hidden_states:Wt};this.addPastKeyValues(ln,gr),br=await Y(this.sessions.decoder_model_merged,ln),gr=this.getPastKeyValues(br,gr);const{prob:bn,spectrum:Ws}=br;if(fr.push(Ws),Dr>=dr&&(Array.from(bn.data).filter(Gs=>Gs>=Ee).length>0||Dr>=$r))break}const En=(0,w.cat)(fr),{waveform:An}=await Y(_t.sessions.model,{spectrogram:En});return{spectrogram:En,waveform:An}}}class tl extends X{constructor(){super(...arguments);qe(this,"main_input_name","spectrogram")}}class rd extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class nd extends rd{}class rl extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Bs extends rl{}class Ns extends rl{}class nl extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class js extends nl{}class il extends nl{}class ol extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class id extends ol{}class od extends ol{}class qo extends X{}class sd extends qo{}class ad extends qo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="text_model"),super.from_pretrained(G,ie)}}class ld extends qo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="audio_model"),super.from_pretrained(G,ie)}}class lp extends X{}class sl extends lp{async _call(G){return new Mp(await super._call(G))}}class Ho extends X{}class fm extends Ho{}class ud extends Ho{}class cd extends Ho{}class al extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ll extends al{}class dd extends al{}class ul extends X{}class fd extends ul{}class pd extends ul{async _call(G){return new ur(await super._call(G))}}class cl extends X{}class up extends cl{}class pm extends cl{}class dl extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}_apply_and_filter_by_delay_pattern_mask(ie){const[Ee,Ze]=ie.dims,it=this.config.decoder.num_codebooks,_t=Ze-it;let Et=0;for(let sr=0;sr<ie.size;++sr){if(ie.data[sr]===this.config.decoder.pad_token_id)continue;const $r=sr%Ze,dr=Math.floor(sr/Ze)%it,_r=$r-dr;_r>0&&_r<=_t&&(ie.data[Et++]=ie.data[sr])}const Wt=Math.floor(Ee/it),cr=Et/(Wt*it);return new w.Tensor(ie.type,ie.data.slice(0,Et),[Wt,it,cr])}prepare_inputs_for_generation(ie,Ee,Ze){let it=structuredClone(ie);for(let Et=0;Et<it.length;++Et)for(let Wt=0;Wt<it[Et].length;++Wt)Et%this.config.decoder.num_codebooks>=Wt&&(it[Et][Wt]=BigInt(this.config.decoder.pad_token_id));return Ze.guidance_scale!==null&&Ze.guidance_scale>1&&(it=it.concat(it)),super.prepare_inputs_for_generation(it,Ee,Ze)}async generate(ie){const Ee=await super.generate(ie),Ze=this._apply_and_filter_by_delay_pattern_mask(Ee).unsqueeze_(0),{audio_values:it}=await Y(this.sessions.encodec_decode,{audio_codes:Ze});return it}}class fl extends X{}class hd extends fl{}class cp extends fl{async _call(G){return new ur(await super._call(G))}}class pl extends X{}class md extends pl{}class gd extends pl{async _call(G){return new ur(await super._call(G))}}class hl extends X{}class _d extends hl{}class dp extends hl{async _call(G){return new ur(await super._call(G))}}class Ko extends X{}class Qo extends Ko{}class ml extends Ko{async _call(G){return new ur(await super._call(G))}}class Or{static async from_pretrained(G,{progress_callback:ie=null,config:Ee=null,cache_dir:Ze=null,local_files_only:it=!1,revision:_t="main",model_file_name:Et=null,subfolder:Wt="onnx",device:cr=null,dtype:sr=null,use_external_data_format:$r=null,session_options:dr={}}={}){let _r={progress_callback:ie,config:Ee,cache_dir:Ze,local_files_only:it,revision:_t,model_file_name:Et,subfolder:Wt,device:cr,dtype:sr,use_external_data_format:$r,session_options:dr};if(_r.config=await o.AutoConfig.from_pretrained(G,_r),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let fr of this.MODEL_CLASS_MAPPINGS){const gr=fr.get(_r.config.model_type);if(gr)return await gr[1].from_pretrained(G,_r)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_r.config.model_type}", attempting to construct from base class.`),await X.from_pretrained(G,_r);throw Error(`Unsupported model type: ${_r.config.model_type}`)}}qe(Or,"MODEL_CLASS_MAPPINGS",null),qe(Or,"BASE_IF_FAIL",!1);const fp=new Map([["bert",["BertModel",Be]],["nomic_bert",["NomicBertModel",je]],["roformer",["RoFormerModel",tt]],["electra",["ElectraModel",ke]],["esm",["EsmModel",sn]],["convbert",["ConvBertModel",we]],["camembert",["CamembertModel",ve]],["deberta",["DebertaModel",ht]],["deberta-v2",["DebertaV2Model",Ot]],["mpnet",["MPNetModel",ks]],["albert",["AlbertModel",Yi]],["distilbert",["DistilBertModel",Er]],["roberta",["RobertaModel",mr]],["xlm",["XLMModel",an]],["xlm-roberta",["XLMRobertaModel",kr]],["clap",["ClapModel",sd]],["clip",["CLIPModel",lu]],["clipseg",["CLIPSegModel",hu]],["chinese_clip",["ChineseCLIPModel",pu]],["siglip",["SiglipModel",_o]],["mobilebert",["MobileBertModel",Wr]],["squeezebert",["SqueezeBertModel",Ss]],["wav2vec2",["Wav2Vec2Model",Wc]],["wav2vec2-bert",["Wav2Vec2BertModel",Ya]],["unispeech",["UniSpeechModel",Qa]],["unispeech-sat",["UniSpeechSatModel",Os]],["hubert",["HubertModel",sp]],["wavlm",["WavLMModel",Xc]],["audio-spectrogram-transformer",["ASTModel",Dt]],["vits",["VitsModel",sl]],["pyannote",["PyAnnoteModel",Ha]],["wespeaker-resnet",["WeSpeakerResNetModel",Ka]],["detr",["DetrModel",ac]],["rt_detr",["RTDetrModel",dc]],["table-transformer",["TableTransformerModel",pc]],["vit",["ViTModel",Gu]],["fastvit",["FastViTModel",Hu]],["mobilevit",["MobileViTModel",Zu]],["mobilevitv2",["MobileViTV2Model",rp]],["owlvit",["OwlViTModel",tc]],["owlv2",["Owlv2Model",nc]],["beit",["BeitModel",oc]],["deit",["DeiTModel",gc]],["convnext",["ConvNextModel",Cc]],["convnextv2",["ConvNextV2Model",Ac]],["dinov2",["Dinov2Model",Fc]],["resnet",["ResNetModel",yc]],["swin",["SwinModel",vc]],["swin2sr",["Swin2SRModel",xc]],["donut-swin",["DonutSwinModel",Ua]],["yolos",["YolosModel",Oc]],["dpt",["DPTModel",Ba]],["glpn",["GLPNModel",kc]],["hifigan",["SpeechT5HifiGan",tl]],["efficientnet",["EfficientNetModel",fd]],["mobilenet_v1",["MobileNetV1Model",hd]],["mobilenet_v2",["MobileNetV2Model",md]],["mobilenet_v3",["MobileNetV3Model",_d]],["mobilenet_v4",["MobileNetV4Model",Qo]]]),pp=new Map([["t5",["T5Model",Bo]],["longt5",["LongT5Model",jo]],["mt5",["MT5Model",Vo]],["bart",["BartModel",Ue]],["mbart",["MBartModel",ze]],["marian",["MarianModel",np]],["whisper",["WhisperModel",Vt]],["m2m_100",["M2M100Model",Uc]],["blenderbot",["BlenderbotModel",Tt]],["blenderbot-small",["BlenderbotSmallModel",Pr]]]),hp=new Map([["bloom",["BloomModel",Nu]],["gpt2",["GPT2Model",gu]],["gptj",["GPTJModel",xu]],["gpt_bigcode",["GPTBigCodeModel",Tu]],["gpt_neo",["GPTNeoModel",yu]],["gpt_neox",["GPTNeoXModel",vu]],["codegen",["CodeGenModel",ku]],["llama",["LlamaModel",ni]],["cohere",["CohereModel",Eu]],["gemma",["GemmaModel",Pu]],["gemma2",["Gemma2Model",Au]],["openelm",["OpenELMModel",Fu]],["qwen2",["Qwen2Model",Ou]],["phi",["PhiModel",Lu]],["phi3",["Phi3Model",Bu]],["mpt",["MptModel",tp]],["opt",["OPTModel",Vu]],["mistral",["MistralModel",Bs]],["starcoder2",["Starcoder2Model",js]],["falcon",["FalconModel",id]],["stablelm",["StableLmModel",ll]]]),Us=new Map([["speecht5",["SpeechT5ForSpeechToText",td]],["whisper",["WhisperForConditionalGeneration",da]]]),yd=new Map([["speecht5",["SpeechT5ForTextToSpeech",ap]]]),wd=new Map([["vits",["VitsModel",sl]],["musicgen",["MusicgenForConditionalGeneration",dl]]]),vd=new Map([["bert",["BertForSequenceClassification",ot]],["roformer",["RoFormerForSequenceClassification",Ae]],["electra",["ElectraForSequenceClassification",ut]],["esm",["EsmForSequenceClassification",bi]],["convbert",["ConvBertForSequenceClassification",J]],["camembert",["CamembertForSequenceClassification",He]],["deberta",["DebertaForSequenceClassification",wt]],["deberta-v2",["DebertaV2ForSequenceClassification",Kt]],["mpnet",["MPNetForSequenceClassification",Do]],["albert",["AlbertForSequenceClassification",fo]],["distilbert",["DistilBertForSequenceClassification",Qr]],["roberta",["RobertaForSequenceClassification",pn]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",wr]],["bart",["BartForSequenceClassification",fe]],["mbart",["MBartForSequenceClassification",nt]],["mobilebert",["MobileBertForSequenceClassification",Fr]],["squeezebert",["SqueezeBertForSequenceClassification",di]]]),mp=new Map([["bert",["BertForTokenClassification",dt]],["roformer",["RoFormerForTokenClassification",$e]],["electra",["ElectraForTokenClassification",Je]],["esm",["EsmForTokenClassification",Nr]],["convbert",["ConvBertForTokenClassification",L]],["camembert",["CamembertForTokenClassification",Xe]],["deberta",["DebertaForTokenClassification",St]],["deberta-v2",["DebertaV2ForTokenClassification",Qt]],["mpnet",["MPNetForTokenClassification",Lo]],["distilbert",["DistilBertForTokenClassification",Cr]],["roberta",["RobertaForTokenClassification",st]],["xlm",["XLMForTokenClassification",Bn]],["xlm-roberta",["XLMRobertaForTokenClassification",zr]]]),gl=new Map([["t5",["T5ForConditionalGeneration",No]],["longt5",["LongT5ForConditionalGeneration",Uo]],["mt5",["MT5ForConditionalGeneration",Br]],["bart",["BartForConditionalGeneration",W]],["mbart",["MBartForConditionalGeneration",Oe]],["marian",["MarianMTModel",jc]],["m2m_100",["M2M100ForConditionalGeneration",Vc]],["blenderbot",["BlenderbotForConditionalGeneration",At]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",rr]]]),Vs=new Map([["bloom",["BloomForCausalLM",ju]],["gpt2",["GPT2LMHeadModel",_u]],["gptj",["GPTJForCausalLM",Mu]],["gpt_bigcode",["GPTBigCodeForCausalLM",ep]],["gpt_neo",["GPTNeoForCausalLM",wu]],["gpt_neox",["GPTNeoXForCausalLM",bu]],["codegen",["CodeGenForCausalLM",Cs]],["llama",["LlamaForCausalLM",Su]],["cohere",["CohereForCausalLM",Cu]],["gemma",["GemmaForCausalLM",$u]],["gemma2",["Gemma2ForCausalLM",Iu]],["openelm",["OpenELMForCausalLM",zu]],["qwen2",["Qwen2ForCausalLM",Du]],["phi",["PhiForCausalLM",Ru]],["phi3",["Phi3ForCausalLM",Sa]],["mpt",["MptForCausalLM",Uu]],["opt",["OPTForCausalLM",Wu]],["mbart",["MBartForCausalLM",xt]],["mistral",["MistralForCausalLM",Ns]],["starcoder2",["Starcoder2ForCausalLM",il]],["falcon",["FalconForCausalLM",od]],["trocr",["TrOCRForCausalLM",nd]],["stablelm",["StableLmForCausalLM",dd]]]),bd=new Map([["bert",["BertForMaskedLM",We]],["roformer",["RoFormerForMaskedLM",A]],["electra",["ElectraForMaskedLM",Ne]],["esm",["EsmForMaskedLM",Li]],["convbert",["ConvBertForMaskedLM",B]],["camembert",["CamembertForMaskedLM",Re]],["deberta",["DebertaForMaskedLM",Mt]],["deberta-v2",["DebertaV2ForMaskedLM",Ut]],["mpnet",["MPNetForMaskedLM",Oo]],["albert",["AlbertForMaskedLM",Xt]],["distilbert",["DistilBertForMaskedLM",Pt]],["roberta",["RobertaForMaskedLM",kn]],["xlm",["XLMWithLMHeadModel",$n]],["xlm-roberta",["XLMRobertaForMaskedLM",Ct]],["mobilebert",["MobileBertForMaskedLM",ci]],["squeezebert",["SqueezeBertForMaskedLM",co]]]),xd=new Map([["bert",["BertForQuestionAnswering",Ge]],["roformer",["RoFormerForQuestionAnswering",se]],["electra",["ElectraForQuestionAnswering",Ve]],["convbert",["ConvBertForQuestionAnswering",ue]],["camembert",["CamembertForQuestionAnswering",rt]],["deberta",["DebertaForQuestionAnswering",Rt]],["deberta-v2",["DebertaV2ForQuestionAnswering",Jt]],["mpnet",["MPNetForQuestionAnswering",Ro]],["albert",["AlbertForQuestionAnswering",po]],["distilbert",["DistilBertForQuestionAnswering",mt]],["roberta",["RobertaForQuestionAnswering",qn]],["xlm",["XLMForQuestionAnswering",gn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Gr]],["mobilebert",["MobileBertForQuestionAnswering",Ri]],["squeezebert",["SqueezeBertForQuestionAnswering",Mi]]]),_l=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",fa]]]),hm=new Map([["llava",["LlavaForConditionalGeneration",go]],["moondream1",["Moondream1ForConditionalGeneration",or]],["florence2",["Florence2ForConditionalGeneration",pa]]]),gp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",fa]]]),Md=new Map([["vit",["ViTForImageClassification",qu]],["fastvit",["FastViTForImageClassification",Ku]],["mobilevit",["MobileViTForImageClassification",Ju]],["mobilevitv2",["MobileViTV2ForImageClassification",ec]],["beit",["BeitForImageClassification",sc]],["deit",["DeiTForImageClassification",_c]],["convnext",["ConvNextForImageClassification",Pc]],["convnextv2",["ConvNextV2ForImageClassification",Ic]],["dinov2",["Dinov2ForImageClassification",zc]],["resnet",["ResNetForImageClassification",wc]],["swin",["SwinForImageClassification",bc]],["segformer",["SegformerForImageClassification",ud]],["efficientnet",["EfficientNetForImageClassification",pd]],["mobilenet_v1",["MobileNetV1ForImageClassification",cp]],["mobilenet_v2",["MobileNetV2ForImageClassification",gd]],["mobilenet_v3",["MobileNetV3ForImageClassification",dp]],["mobilenet_v4",["MobileNetV4ForImageClassification",ml]]]),_p=new Map([["detr",["DetrForObjectDetection",lc]],["rt_detr",["RTDetrForObjectDetection",zs]],["table-transformer",["TableTransformerForObjectDetection",hc]],["yolos",["YolosForObjectDetection",Dc]]]),Td=new Map([["owlvit",["OwlViTForObjectDetection",rc]],["owlv2",["Owlv2ForObjectDetection",ic]]]),kd=new Map([["detr",["DetrForSegmentation",uc]],["clipseg",["CLIPSegForImageSegmentation",mu]]]),Sd=new Map([["segformer",["SegformerForSemanticSegmentation",cd]]]),Ed=new Map([["sam",["SamModel",Bc]]]),yp=new Map([["wav2vec2",["Wav2Vec2ForCTC",ip]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Rs]],["unispeech",["UniSpeechForCTC",Gc]],["unispeech-sat",["UniSpeechSatForCTC",Xa]],["wavlm",["WavLMForCTC",Ja]],["hubert",["HubertForCTC",Qc]]]),Cd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ji]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Kc]],["unispeech",["UniSpeechForSequenceClassification",qc]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Hc]],["wavlm",["WavLMForSequenceClassification",Yc]],["hubert",["HubertForSequenceClassification",Za]],["audio-spectrogram-transformer",["ASTForAudioClassification",Es]]]),Pd=new Map([["wavlm",["WavLMForXVector",Zc]]]),$d=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ds]],["wavlm",["WavLMForAudioFrameClassification",Jc]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ui]],["pyannote",["PyAnnoteForAudioFrameClassification",Vi]]]),Ad=new Map([["vitmatte",["VitMatteForImageMatting",Xu]]]),wp=new Map([["swin2sr",["Swin2SRForImageSuperResolution",La]]]),Id=new Map([["dpt",["DPTForDepthEstimation",Na]],["depth_anything",["DepthAnythingForDepthEstimation",Tc]],["glpn",["GLPNForDepthEstimation",Sc]]]),Fd=new Map([["clip",["CLIPVisionModelWithProjection",uu]],["siglip",["SiglipVisionModel",du]]]),zd=[[fp,x.EncoderOnly],[pp,x.EncoderDecoder],[hp,x.DecoderOnly],[vd,x.EncoderOnly],[mp,x.EncoderOnly],[gl,x.Seq2Seq],[Us,x.Seq2Seq],[Vs,x.DecoderOnly],[bd,x.EncoderOnly],[xd,x.EncoderOnly],[_l,x.Vision2Seq],[hm,x.ImageTextToText],[Md,x.EncoderOnly],[kd,x.EncoderOnly],[Sd,x.EncoderOnly],[Ad,x.EncoderOnly],[wp,x.EncoderOnly],[Id,x.EncoderOnly],[_p,x.EncoderOnly],[Td,x.EncoderOnly],[Ed,x.MaskGeneration],[yp,x.EncoderOnly],[Cd,x.EncoderOnly],[yd,x.Seq2Seq],[wd,x.EncoderOnly],[Pd,x.EncoderOnly],[$d,x.EncoderOnly],[Fd,x.EncoderOnly]];for(const[V,G]of zd)for(const[ie,Ee]of V.values())I.set(ie,G),O.set(Ee,ie),U.set(ie,Ee);const vp=[["MusicgenForConditionalGeneration",dl,x.Musicgen],["CLIPTextModelWithProjection",fi,x.EncoderOnly],["SiglipTextModel",cu,x.EncoderOnly],["ClapTextModelWithProjection",ad,x.EncoderOnly],["ClapAudioModelWithProjection",ld,x.EncoderOnly]];for(const[V,G,ie]of vp)I.set(V,ie),O.set(G,V),U.set(V,G);class Od extends Or{}qe(Od,"MODEL_CLASS_MAPPINGS",zd.map(G=>G[0])),qe(Od,"BASE_IF_FAIL",!0);class Sn extends Or{}qe(Sn,"MODEL_CLASS_MAPPINGS",[vd]);class Dd extends Or{}qe(Dd,"MODEL_CLASS_MAPPINGS",[mp]);class Ld extends Or{}qe(Ld,"MODEL_CLASS_MAPPINGS",[gl]);class yl extends Or{}qe(yl,"MODEL_CLASS_MAPPINGS",[Us]);class Rd extends Or{}qe(Rd,"MODEL_CLASS_MAPPINGS",[yd]);class Xo extends Or{}qe(Xo,"MODEL_CLASS_MAPPINGS",[wd]);class Bd extends Or{}qe(Bd,"MODEL_CLASS_MAPPINGS",[Vs]);class Nd extends Or{}qe(Nd,"MODEL_CLASS_MAPPINGS",[bd]);class wl extends Or{}qe(wl,"MODEL_CLASS_MAPPINGS",[xd]);class jd extends Or{}qe(jd,"MODEL_CLASS_MAPPINGS",[_l]);class Ud extends Or{}qe(Ud,"MODEL_CLASS_MAPPINGS",[Md]);class vl extends Or{}qe(vl,"MODEL_CLASS_MAPPINGS",[kd]);class Vd extends Or{}qe(Vd,"MODEL_CLASS_MAPPINGS",[Sd]);class Wd extends Or{}qe(Wd,"MODEL_CLASS_MAPPINGS",[_p]);class Gd extends Or{}qe(Gd,"MODEL_CLASS_MAPPINGS",[Td]);class bl extends Or{}qe(bl,"MODEL_CLASS_MAPPINGS",[Ed]);class qd extends Or{}qe(qd,"MODEL_CLASS_MAPPINGS",[yp]);class Hd extends Or{}qe(Hd,"MODEL_CLASS_MAPPINGS",[Cd]);class xl extends Or{}qe(xl,"MODEL_CLASS_MAPPINGS",[Pd]);class Kd extends Or{}qe(Kd,"MODEL_CLASS_MAPPINGS",[$d]);class bp extends Or{}qe(bp,"MODEL_CLASS_MAPPINGS",[gp]);class Qd extends Or{}qe(Qd,"MODEL_CLASS_MAPPINGS",[Ad]);class Xd extends Or{}qe(Xd,"MODEL_CLASS_MAPPINGS",[wp]);class Yd extends Or{}qe(Yd,"MODEL_CLASS_MAPPINGS",[Id]);class Zd extends Or{}qe(Zd,"MODEL_CLASS_MAPPINGS",[Fd]);class mm extends me{constructor({logits:G,past_key_values:ie,encoder_outputs:Ee,decoder_attentions:Ze=null,cross_attentions:it=null}){super(),this.logits=G,this.past_key_values=ie,this.encoder_outputs=Ee,this.decoder_attentions=Ze,this.cross_attentions=it}}class ur extends me{constructor({logits:G}){super(),this.logits=G}}class Jd extends me{constructor({logits:G,embeddings:ie}){super(),this.logits=G,this.embeddings=ie}}class dn extends me{constructor({logits:G}){super(),this.logits=G}}class yn extends me{constructor({logits:G}){super(),this.logits=G}}class wn extends me{constructor({start_logits:G,end_logits:ie}){super(),this.start_logits=G,this.end_logits=ie}}class Ji extends me{constructor({logits:G}){super(),this.logits=G}}class xp extends me{constructor({logits:G,past_key_values:ie}){super(),this.logits=G,this.past_key_values=ie}}class ef extends me{constructor({alphas:G}){super(),this.alphas=G}}class Mp extends me{constructor({waveform:G,spectrogram:ie}){super(),this.waveform=G,this.spectrogram=ie}}},"./src/models/whisper/common_whisper.js":(e,t,n)=>{n.r(t),n.d(t,{WHISPER_LANGUAGE_MAPPING:()=>a,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>l,whisper_language_to_code:()=>f});const o=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],a=new Map(o),l=new Map([...o.map(([_,h])=>[h,_]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function f(_){_=_.toLowerCase();let h=l.get(_);if(h===void 0)if(a.has(_))h=_;else{const M=_.length===2?a.keys():a.values();throw new Error(`Language "${_}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return h}},"./src/models/whisper/generation_whisper.js":(e,t,n)=>{n.r(t),n.d(t,{WhisperGenerationConfig:()=>a});var o=n("./src/generation/configuration_utils.js");class a extends o.GenerationConfig{constructor(){super(...arguments);qe(this,"return_timestamps",null);qe(this,"return_token_timestamps",null);qe(this,"num_frames",null);qe(this,"alignment_heads",null);qe(this,"task",null);qe(this,"language",null);qe(this,"no_timestamps_token_id",null);qe(this,"prompt_ids",null);qe(this,"is_multilingual",null);qe(this,"lang_to_id",null);qe(this,"task_to_id",null);qe(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(e,t,n)=>{n.r(t),n.d(t,{TensorOpRegistry:()=>f});var o=n("./src/backends/onnx.js"),a=n("./src/utils/tensor.js");const l=async(_,h,g)=>{const M=await(0,o.createInferenceSession)(new Uint8Array(_),h);return async w=>{const C=Object.fromEntries(Object.entries(w).map(([z,S])=>[z,S.ort_tensor])),k=await M.run(C);return Array.isArray(g)?g.map(z=>new a.Tensor(k[z])):new a.Tensor(k[g])}};class f{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=l([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=l([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=l([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=l([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=l([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=l([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}qe(f,"session_options",{})},"./src/pipelines.js":(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>ee,AutomaticSpeechRecognitionPipeline:()=>R,DepthEstimationPipeline:()=>De,DocumentQuestionAnsweringPipeline:()=>X,FeatureExtractionPipeline:()=>de,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>Qe,ImageFeatureExtractionPipeline:()=>Ce,ImageSegmentationPipeline:()=>ge,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>Me,ObjectDetectionPipeline:()=>ae,Pipeline:()=>S,QuestionAnsweringPipeline:()=>x,SummarizationPipeline:()=>O,Text2TextGenerationPipeline:()=>U,TextClassificationPipeline:()=>P,TextGenerationPipeline:()=>D,TextToAudioPipeline:()=>me,TokenClassificationPipeline:()=>y,TranslationPipeline:()=>N,ZeroShotAudioClassificationPipeline:()=>ye,ZeroShotClassificationPipeline:()=>Y,ZeroShotImageClassificationPipeline:()=>Q,ZeroShotObjectDetectionPipeline:()=>Se,pipeline:()=>ot});var o=n("./src/tokenizers.js"),a=n("./src/models.js"),l=n("./src/processors.js"),f=n("./src/utils/generic.js"),_=n("./src/utils/core.js"),h=n("./src/utils/maths.js"),g=n("./src/utils/audio.js"),M=n("./src/utils/tensor.js"),w=n("./src/utils/image.js");async function C(Ge){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(Te=>w.RawImage.read(Te)))}async function k(Ge,Te){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(je=>typeof je=="string"||je instanceof URL?(0,g.read_audio)(je,Te):je instanceof Float64Array?new Float32Array(je):je))}function z(Ge,Te){Te&&(Ge=Ge.map(Ae=>Ae|0));const[je,Ye,tt,A]=Ge;return{xmin:je,ymin:Ye,xmax:tt,ymax:A}}class S extends f.Callable{constructor({task:Te,model:je,tokenizer:Ye=null,processor:tt=null}){super(),this.task=Te,this.model=je,this.tokenizer=Ye,this.processor=tt}async dispose(){await this.model.dispose()}}class P extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=1}={}){const Ye=this.tokenizer(Te,{padding:!0,truncation:!0}),tt=await this.model(Ye),A=this.model.config.problem_type==="multi_label_classification"?se=>se.sigmoid():se=>new M.Tensor("float32",(0,h.softmax)(se.data),se.dims),Ae=this.model.config.id2label,$e=[];for(const se of tt.logits){const te=A(se),we=await(0,M.topk)(te,je),B=we[0].tolist(),L=we[1].tolist().map((ue,le)=>({label:Ae?Ae[ue]:`LABEL_${ue}`,score:B[le]}));je===1?$e.push(...L):$e.push(L)}return Array.isArray(Te)||je===1?$e:$e[0]}}class y extends S{constructor(Te){super(Te)}async _call(Te,{ignore_labels:je=["O"]}={}){const Ye=Array.isArray(Te),tt=this.tokenizer(Ye?Te:[Te],{padding:!0,truncation:!0}),Ae=(await this.model(tt)).logits,$e=this.model.config.id2label,se=[];for(let te=0;te<Ae.dims[0];++te){const we=tt.input_ids[te],B=Ae[te],J=[];for(let L=0;L<B.dims[0];++L){const ue=B[L],le=(0,h.max)(ue.data)[1],ke=$e?$e[le]:`LABEL_${le}`;if(je.includes(ke))continue;const Ne=this.tokenizer.decode([we[L].item()],{skip_special_tokens:!0});if(Ne==="")continue;const ut=(0,h.softmax)(ue.data);J.push({entity:ke,score:ut[le],index:L,word:Ne})}se.push(J)}return Ye?se:se[0]}}class x extends S{constructor(Te){super(Te)}async _call(Te,je,{top_k:Ye=1}={}){const tt=this.tokenizer(Te,{text_pair:je,padding:!0,truncation:!0}),{start_logits:A,end_logits:Ae}=await this.model(tt),$e=tt.input_ids.tolist(),se=tt.attention_mask.tolist(),te=this.tokenizer.all_special_ids,we=[];for(let B=0;B<A.dims[0];++B){const J=$e[B],L=J.findIndex(Je=>Je==this.tokenizer.sep_token_id);se[B].map((Je,Ve)=>Je==1&&(Ve===0||Ve>L&&te.findIndex(Z=>Z==J[Ve])===-1));const ue=A[B].tolist(),le=Ae[B].tolist();for(let Je=1;Je<ue.length;++Je)(se[B]==0||Je<=L||te.findIndex(Ve=>Ve==J[Je])!==-1)&&(ue[Je]=-1/0,le[Je]=-1/0);const ke=(0,h.softmax)(ue).map((Je,Ve)=>[Je,Ve]),Ne=(0,h.softmax)(le).map((Je,Ve)=>[Je,Ve]);ke[0][0]=0,Ne[0][0]=0;const ut=(0,_.product)(ke,Ne).filter(Je=>Je[0][1]<=Je[1][1]).map(Je=>[Je[0][1],Je[1][1],Je[0][0]*Je[1][0]]).sort((Je,Ve)=>Ve[2]-Je[2]);for(let Je=0;Je<Math.min(ut.length,Ye);++Je){const[Ve,Z,ve]=ut[Je],Re=J.slice(Ve,Z+1),He=this.tokenizer.decode(Re,{skip_special_tokens:!0});we.push({answer:He,score:ve})}}return Ye===1?we[0]:we}}class I extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=this.tokenizer(Te,{padding:!0,truncation:!0}),{logits:tt}=await this.model(Ye),A=[],Ae=Ye.input_ids.tolist();for(let $e=0;$e<Ae.length;++$e){const se=Ae[$e],te=se.findIndex(ue=>ue==this.tokenizer.mask_token_id);if(te===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const we=tt[$e][te],B=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(we.data),we.dims),je),J=B[0].tolist(),L=B[1].tolist();A.push(L.map((ue,le)=>{const ke=se.slice();return ke[te]=ue,{score:J[le],token:Number(ue),token_str:this.tokenizer.model.vocab[ue],sequence:this.tokenizer.decode(ke,{skip_special_tokens:!0})}}))}return Array.isArray(Te)?A:A[0]}}class U extends S{constructor(je){super(je);qe(this,"_key","generated_text")}async _call(je,Ye={}){Array.isArray(je)||(je=[je]),this.model.config.prefix&&(je=je.map(te=>this.model.config.prefix+te));const tt=this.model.config.task_specific_params;tt&&tt[this.task]&&tt[this.task].prefix&&(je=je.map(te=>tt[this.task].prefix+te));const A=this.tokenizer,Ae={padding:!0,truncation:!0};let $e;this instanceof N&&"_build_translation_inputs"in A?$e=A._build_translation_inputs(je,Ae,Ye):$e=A(je,Ae);const se=await this.model.generate({...$e,...Ye});return A.batch_decode(se,{skip_special_tokens:!0}).map(te=>({[this._key]:te}))}}class O extends U{constructor(je){super(je);qe(this,"_key","summary_text")}}class N extends U{constructor(je){super(je);qe(this,"_key","translation_text")}}function j(Ge){return Array.isArray(Ge)&&Ge.every(Te=>"role"in Te&&"content"in Te)}class D extends S{constructor(Te){super(Te)}async _call(Te,je={}){let Ye=!1,tt=!1,A;if(typeof Te=="string")A=Te=[Te];else if(Array.isArray(Te)&&Te.every(L=>typeof L=="string"))Ye=!0,A=Te;else{if(j(Te))Te=[Te];else if(Array.isArray(Te)&&Te.every(j))Ye=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");tt=!0,A=Te.map(L=>this.tokenizer.apply_chat_template(L,{tokenize:!1,add_generation_prompt:!0}))}const Ae=je.add_special_tokens??!1,$e=tt?!1:je.return_full_text??!0;this.tokenizer.padding_side="left";const se=this.tokenizer(A,{add_special_tokens:Ae,padding:!0,truncation:!0}),te=await this.model.generate({...se,...je}),we=this.tokenizer.batch_decode(te,{skip_special_tokens:!0});let B;!$e&&se.input_ids.dims.at(-1)>0&&(B=this.tokenizer.batch_decode(se.input_ids,{skip_special_tokens:!0}).map(L=>L.length));const J=Array.from({length:Te.length},L=>[]);for(let L=0;L<we.length;++L){const ue=Math.floor(L/te.dims[0]*Te.length);B&&(we[L]=we[L].slice(B[ue])),J[ue].push({generated_text:tt?[...Te[ue],{role:"assistant",content:we[L]}]:we[L]})}return!Ye&&J.length===1?J[0]:J}}class Y extends S{constructor(Te){super(Te),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([je,Ye])=>[je.toLowerCase(),Ye])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(Te,je,{hypothesis_template:Ye="This example is {}.",multi_label:tt=!1}={}){const A=Array.isArray(Te);A||(Te=[Te]),Array.isArray(je)||(je=[je]);const Ae=je.map(te=>Ye.replace("{}",te)),$e=tt||je.length===1,se=[];for(const te of Te){const we=[];for(const L of Ae){const ue=this.tokenizer(te,{text_pair:L,padding:!0,truncation:!0}),le=await this.model(ue);$e?we.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):we.push(le.logits.data[this.entailment_id])}const J=($e?we.map(L=>(0,h.softmax)(L)[1]):(0,h.softmax)(we)).map((L,ue)=>[L,ue]).sort((L,ue)=>ue[0]-L[0]);se.push({sequence:te,labels:J.map(L=>je[L[1]]),scores:J.map(L=>L[0])})}return A?se:se[0]}}class de extends S{constructor(Te){super(Te)}async _call(Te,{pooling:je="none",normalize:Ye=!1,quantize:tt=!1,precision:A="binary"}={}){const Ae=this.tokenizer(Te,{padding:!0,truncation:!0}),$e=await this.model(Ae);let se=$e.last_hidden_state??$e.logits??$e.token_embeddings;if(je!=="none")if(je==="mean")se=(0,M.mean_pooling)(se,Ae.attention_mask);else if(je==="cls")se=se.slice(null,0);else throw Error(`Pooling method '${je}' not supported.`);return Ye&&(se=se.normalize(2,-1)),tt&&(se=(0,M.quantize_embeddings)(se,A)),se}}class Ce extends S{constructor(Te){super(Te)}async _call(Te,{pool:je=null}={}){const Ye=await C(Te),{pixel_values:tt}=await this.processor(Ye),A=await this.model({pixel_values:tt});let Ae;if(je){if(!("pooler_output"in A))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ae=A.pooler_output}else Ae=A.last_hidden_state??A.logits??A.image_embeds;return Ae}}class ee extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=this.processor.feature_extractor.config.sampling_rate,tt=await k(Te,Ye),A=this.model.config.id2label,Ae=[];for(const $e of tt){const se=await this.processor($e),we=(await this.model(se)).logits[0],B=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(we.data),we.dims),je),J=B[0].tolist(),ue=B[1].tolist().map((le,ke)=>({label:A?A[le]:`LABEL_${le}`,score:J[ke]}));Ae.push(ue)}return Array.isArray(Te)?Ae:Ae[0]}}class ye extends S{constructor(Te){super(Te)}async _call(Te,je,{hypothesis_template:Ye="This is a sound of {}."}={}){const tt=!Array.isArray(Te);tt&&(Te=[Te]);const A=je.map(we=>Ye.replace("{}",we)),Ae=this.tokenizer(A,{padding:!0,truncation:!0}),$e=this.processor.feature_extractor.config.sampling_rate,se=await k(Te,$e),te=[];for(const we of se){const B=await this.processor(we),J=await this.model({...Ae,...B}),L=(0,h.softmax)(J.logits_per_audio.data);te.push([...L].map((ue,le)=>({score:ue,label:je[le]})))}return tt?te[0]:te}}class R extends S{constructor(Te){super(Te)}async _call(Te,je={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(Te,je);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Te,je);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Te,je){je.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),je.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ye=!Array.isArray(Te);Ye&&(Te=[Te]);const tt=this.processor.feature_extractor.config.sampling_rate,A=await k(Te,tt),Ae=[];for(const $e of A){const se=await this.processor($e),we=(await this.model(se)).logits[0],B=[];for(const L of we)B.push((0,h.max)(L.data)[1]);const J=this.tokenizer.decode(B);Ae.push({text:J})}return Ye?Ae[0]:Ae}async _call_whisper(Te,je){const Ye=je.return_timestamps??!1,tt=je.chunk_length_s??0,A=je.force_full_sequences??!1;let Ae=je.stride_length_s??null;const $e={...je};Ye==="word"&&($e.return_token_timestamps=!0,$e.return_timestamps=!1);const se=!Array.isArray(Te);se&&(Te=[Te]);const te=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,we=this.processor.feature_extractor.config.hop_length,B=this.processor.feature_extractor.config.sampling_rate,J=await k(Te,B),L=[];for(const ue of J){let le=[];if(tt>0){if(Ae===null)Ae=tt/6;else if(tt<=Ae)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ut=B*tt,Je=B*Ae,Ve=ut-2*Je;let Z=0;for(;;){const ve=Z+ut,Re=ue.subarray(Z,ve),He=await this.processor(Re),Xe=Z===0,rt=ve>=ue.length;if(le.push({stride:[Re.length,Xe?0:Je,rt?0:Je],input_features:He.input_features,is_last:rt}),rt)break;Z+=Ve}}else le=[{stride:[ue.length,0,0],input_features:(await this.processor(ue)).input_features,is_last:!0}];for(const ut of le){$e.num_frames=Math.floor(ut.stride[0]/we);const Je=await this.model.generate({inputs:ut.input_features,...$e});Ye==="word"?(ut.tokens=Je.sequences.tolist()[0],ut.token_timestamps=Je.token_timestamps.tolist()[0].map(Ve=>(0,h.round)(Ve,2))):ut.tokens=Je[0].tolist(),ut.stride=ut.stride.map(Ve=>Ve/B)}const[ke,Ne]=this.tokenizer._decode_asr(le,{time_precision:te,return_timestamps:Ye,force_full_sequences:A});L.push({text:ke,...Ne})}return se?L[0]:L}}class Me extends S{constructor(Te){super(Te)}async _call(Te,je={}){const Ye=Array.isArray(Te),tt=await C(Te),{pixel_values:A}=await this.processor(tt),Ae=[];for(const $e of A){$e.dims=[1,...$e.dims];const se=await this.model.generate({inputs:$e,...je}),te=this.tokenizer.batch_decode(se,{skip_special_tokens:!0}).map(we=>({generated_text:we.trim()}));Ae.push(te)}return Ye?Ae:Ae[0]}}class Qe extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=await C(Te),{pixel_values:tt}=await this.processor(Ye),A=await this.model({pixel_values:tt}),Ae=this.model.config.id2label,$e=[];for(const se of A.logits){const te=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(se.data),se.dims),je),we=te[0].tolist(),J=te[1].tolist().map((L,ue)=>({label:Ae?Ae[L]:`LABEL_${L}`,score:we[ue]}));$e.push(J)}return Array.isArray(Te)?$e:$e[0]}}class ge extends S{constructor(Te){super(Te),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Te,{threshold:je=.5,mask_threshold:Ye=.5,overlap_mask_area_threshold:tt=.8,label_ids_to_fuse:A=null,target_sizes:Ae=null,subtask:$e=null}={}){if(Array.isArray(Te)&&Te.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const te=await C(Te),we=te.map(Ne=>[Ne.height,Ne.width]),{pixel_values:B,pixel_mask:J}=await this.processor(te),L=await this.model({pixel_values:B,pixel_mask:J});let ue=null;if($e!==null)ue=this.subtasks_mapping[$e];else for(let[Ne,ut]of Object.entries(this.subtasks_mapping))if(ut in this.processor.feature_extractor){ue=this.processor.feature_extractor[ut].bind(this.processor.feature_extractor),$e=Ne;break}const le=this.model.config.id2label,ke=[];if($e==="panoptic"||$e==="instance"){const Ne=ue(L,je,Ye,tt,A,Ae??we)[0],ut=Ne.segmentation;for(const Je of Ne.segments_info){const Ve=new Uint8ClampedArray(ut.data.length);for(let ve=0;ve<ut.data.length;++ve)ut.data[ve]===Je.id&&(Ve[ve]=255);const Z=new w.RawImage(Ve,ut.dims[1],ut.dims[0],1);ke.push({score:Je.score,label:le[Je.label_id],mask:Z})}}else if($e==="semantic"){const{segmentation:Ne,labels:ut}=ue(L,Ae??we)[0];for(const Je of ut){const Ve=new Uint8ClampedArray(Ne.data.length);for(let ve=0;ve<Ne.data.length;++ve)Ne.data[ve]===Je&&(Ve[ve]=255);const Z=new w.RawImage(Ve,Ne.dims[1],Ne.dims[0],1);ke.push({score:null,label:le[Je],mask:Z})}}else throw Error(`Subtask ${$e} not supported.`);return ke}}class Q extends S{constructor(Te){super(Te)}async _call(Te,je,{hypothesis_template:Ye="This is a photo of {}"}={}){const tt=Array.isArray(Te),A=await C(Te),Ae=je.map(J=>Ye.replace("{}",J)),$e=this.tokenizer(Ae,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:se}=await this.processor(A),te=await this.model({...$e,pixel_values:se}),we=this.model.config.model_type==="siglip"?J=>J.sigmoid().data:J=>(0,h.softmax)(J.data),B=[];for(const J of te.logits_per_image){const ue=[...we(J)].map((le,ke)=>({score:le,label:je[ke]}));ue.sort((le,ke)=>ke.score-le.score),B.push(ue)}return tt?B:B[0]}}class ae extends S{constructor(Te){super(Te)}async _call(Te,{threshold:je=.9,percentage:Ye=!1}={}){const tt=Array.isArray(Te);if(tt&&Te.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const A=await C(Te),Ae=Ye?null:A.map(L=>[L.height,L.width]),{pixel_values:$e,pixel_mask:se}=await this.processor(A),te=await this.model({pixel_values:$e,pixel_mask:se}),we=this.processor.feature_extractor.post_process_object_detection(te,je,Ae),B=this.model.config.id2label,J=we.map(L=>L.boxes.map((ue,le)=>({score:L.scores[le],label:B[L.classes[le]],box:z(ue,!Ye)})));return tt?J:J[0]}}class Se extends S{constructor(Te){super(Te)}async _call(Te,je,{threshold:Ye=.1,top_k:tt=null,percentage:A=!1}={}){const Ae=Array.isArray(Te),$e=await C(Te),se=this.tokenizer(je,{padding:!0,truncation:!0}),te=await this.processor($e),we=[];for(let B=0;B<$e.length;++B){const J=$e[B],L=A?null:[[J.height,J.width]],ue=te.pixel_values[B].unsqueeze_(0),le=await this.model({...se,pixel_values:ue}),ke=this.processor.feature_extractor.post_process_object_detection(le,Ye,L,!0)[0];let Ne=ke.boxes.map((ut,Je)=>({score:ke.scores[Je],label:je[ke.classes[Je]],box:z(ut,!A)})).sort((ut,Je)=>Je.score-ut.score);tt!==null&&(Ne=Ne.slice(0,tt)),we.push(Ne)}return Ae?we:we[0]}}class X extends S{constructor(Te){super(Te)}async _call(Te,je,Ye={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class me extends S{constructor(je){super(je);qe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=je.vocoder??null}async _call(je,{speaker_embeddings:Ye=null}={}){return this.processor?this._call_text_to_spectrogram(je,{speaker_embeddings:Ye}):this._call_text_to_waveform(je)}async _call_text_to_waveform(je){const Ye=this.tokenizer(je,{padding:!0,truncation:!0}),{waveform:tt}=await this.model(Ye),A=this.model.config.sampling_rate;return{audio:tt.data,sampling_rate:A}}async _call_text_to_spectrogram(je,{speaker_embeddings:Ye}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await a.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ye=="string"||Ye instanceof URL)&&(Ye=new Float32Array(await(await fetch(Ye)).arrayBuffer())),Ye instanceof Float32Array)Ye=new M.Tensor("float32",Ye,[1,Ye.length]);else if(!(Ye instanceof M.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:tt}=this.tokenizer(je,{padding:!0,truncation:!0}),{waveform:A}=await this.model.generate_speech(tt,Ye,{vocoder:this.vocoder}),Ae=this.processor.feature_extractor.config.sampling_rate;return{audio:A.data,sampling_rate:Ae}}}class Ke extends S{constructor(Te){super(Te)}async _call(Te){const je=await C(Te),Ye=await this.processor(je),tt=await this.model(Ye),A=[];for(const Ae of tt.reconstruction){const $e=Ae.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");A.push(w.RawImage.fromTensor($e))}return A.length>1?A:A[0]}}class De extends S{constructor(Te){super(Te)}async _call(Te){const je=await C(Te),Ye=await this.processor(je),{predicted_depth:tt}=await this.model(Ye),A=[];for(let Ae=0;Ae<je.length;++Ae){const $e=(0,M.interpolate)(tt[Ae],je[Ae].size.reverse(),"bilinear",!1),se=$e.mul_(255/(0,h.max)($e.data)[0]).to("uint8");A.push({predicted_depth:tt[Ae],depth:w.RawImage.fromTensor(se)})}return A.length>1?A:A[0]}}const Be=Object.freeze({"text-classification":{tokenizer:o.AutoTokenizer,pipeline:P,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:o.AutoTokenizer,pipeline:y,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:o.AutoTokenizer,pipeline:x,model:a.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:o.AutoTokenizer,pipeline:I,model:a.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:o.AutoTokenizer,pipeline:O,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:o.AutoTokenizer,pipeline:N,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:o.AutoTokenizer,pipeline:U,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:o.AutoTokenizer,pipeline:D,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:o.AutoTokenizer,pipeline:Y,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ee,model:a.AutoModelForAudioClassification,processor:l.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:o.AutoTokenizer,pipeline:ye,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:o.AutoTokenizer,pipeline:R,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:l.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:o.AutoTokenizer,pipeline:me,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[l.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:o.AutoTokenizer,pipeline:Me,model:a.AutoModelForVision2Seq,processor:l.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Qe,model:a.AutoModelForImageClassification,processor:l.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ge,model:[a.AutoModelForImageSegmentation,a.AutoModelForSemanticSegmentation],processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:o.AutoTokenizer,pipeline:Q,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:a.AutoModelForObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:o.AutoTokenizer,pipeline:Se,model:a.AutoModelForZeroShotObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:o.AutoTokenizer,pipeline:X,model:a.AutoModelForDocumentQuestionAnswering,processor:l.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Ke,model:a.AutoModelForImageToImage,processor:l.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:De,model:a.AutoModelForDepthEstimation,processor:l.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:o.AutoTokenizer,pipeline:de,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:l.AutoProcessor,pipeline:Ce,model:[a.AutoModelForImageFeatureExtraction,a.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),We=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ot(Ge,Te=null,{progress_callback:je=null,config:Ye=null,cache_dir:tt=null,local_files_only:A=!1,revision:Ae="main",device:$e=null,dtype:se=null,model_file_name:te=null,session_options:we={}}={}){Ge=We[Ge]??Ge;const B=Be[Ge.split("_",1)[0]];if(!B)throw Error(`Unsupported pipeline: ${Ge}. Must be one of [${Object.keys(Be)}]`);Te||(Te=B.default.model,console.log(`No model specified. Using default model: "${Te}".`));const J={progress_callback:je,config:Ye,cache_dir:tt,local_files_only:A,revision:Ae,device:$e,dtype:se,model_file_name:te,session_options:we},L=new Map([["tokenizer",B.tokenizer],["model",B.model],["processor",B.processor]]),ue=await dt(L,Te,J);ue.task=Ge,(0,_.dispatchCallback)(je,{status:"ready",task:Ge,model:Te});const le=B.pipeline;return new le(ue)}async function dt(Ge,Te,je){const Ye=Object.create(null),tt=[];for(let[A,Ae]of Ge.entries()){if(!Ae)continue;let $e;Array.isArray(Ae)?$e=new Promise(async(se,te)=>{var B,J;let we;for(let L of Ae){if(L===null){se(null);return}try{se(await L.from_pretrained(Te,je));return}catch(ue){if((B=ue.message)!=null&&B.includes("Unsupported model type"))we=ue;else if((J=ue.message)!=null&&J.includes("Could not locate file"))we=ue;else{te(ue);return}}}te(we)}):$e=Ae.from_pretrained(Te,je),Ye[A]=$e,tt.push($e)}await Promise.all(tt);for(let[A,Ae]of Object.entries(Ye))Ye[A]=await Ae;return Ye}},"./src/processors.js":(e,t,n)=>{n.r(t),n.d(t,{ASTFeatureExtractor:()=>Ae,AutoProcessor:()=>Je,BeitFeatureExtractor:()=>De,BitImageProcessor:()=>I,CLIPFeatureExtractor:()=>O,CLIPImageProcessor:()=>N,ChineseCLIPFeatureExtractor:()=>j,ClapFeatureExtractor:()=>$e,ConvNextFeatureExtractor:()=>Y,ConvNextImageProcessor:()=>de,DPTFeatureExtractor:()=>y,DPTImageProcessor:()=>x,DeiTFeatureExtractor:()=>Ke,DetrFeatureExtractor:()=>ot,DonutFeatureExtractor:()=>Be,EfficientNetImageProcessor:()=>ye,FeatureExtractor:()=>z,Florence2Processor:()=>ut,GLPNFeatureExtractor:()=>U,ImageFeatureExtractor:()=>S,MobileNetV1FeatureExtractor:()=>R,MobileNetV2FeatureExtractor:()=>Me,MobileNetV3FeatureExtractor:()=>Qe,MobileNetV4FeatureExtractor:()=>ge,MobileViTFeatureExtractor:()=>Q,MobileViTImageProcessor:()=>ae,NougatImageProcessor:()=>We,OwlViTFeatureExtractor:()=>Se,OwlViTProcessor:()=>Ne,Owlv2ImageProcessor:()=>X,Processor:()=>B,PyAnnoteFeatureExtractor:()=>se,PyAnnoteProcessor:()=>le,RTDetrImageProcessor:()=>me,SamImageProcessor:()=>Ge,SamProcessor:()=>J,SeamlessM4TFeatureExtractor:()=>A,SegformerFeatureExtractor:()=>P,SiglipImageProcessor:()=>D,SpeechT5FeatureExtractor:()=>we,SpeechT5Processor:()=>ke,Swin2SRImageProcessor:()=>Te,ViTFeatureExtractor:()=>Ce,ViTImageProcessor:()=>ee,VitMatteImageProcessor:()=>je,Wav2Vec2FeatureExtractor:()=>tt,Wav2Vec2ProcessorWithLM:()=>ue,WeSpeakerFeatureExtractor:()=>te,WhisperFeatureExtractor:()=>Ye,WhisperProcessor:()=>L,YolosFeatureExtractor:()=>dt});var o=n("./src/utils/generic.js"),a=n("./src/utils/core.js"),l=n("./src/utils/hub.js"),f=n("./src/utils/maths.js"),_=n("./src/utils/tensor.js");n("./src/utils/image.js");var h=n("./src/utils/audio.js");function g([Ve,Z,ve,Re]){return[Ve-ve/2,Z-Re/2,Ve+ve/2,Z+Re/2]}function M(Ve,Z=.5,ve=null,Re=!1){const He=Ve.logits,Xe=Ve.pred_boxes,[rt,ft,ht]=He.dims;if(ve!==null&&ve.length!==rt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Mt=[];for(let wt=0;wt<rt;++wt){let St=ve!==null?ve[wt]:null,Rt={boxes:[],classes:[],scores:[]},at=He[wt],Ot=Xe[wt];for(let Ut=0;Ut<ft;++Ut){let Kt=at[Ut],Qt=[],Jt;if(Re){Jt=Kt.sigmoid().data;for(let qt=0;qt<Jt.length;++qt)Jt[qt]>Z&&Qt.push(qt)}else{let qt=(0,f.max)(Kt.data)[1];if(qt===ht-1||(Jt=(0,f.softmax)(Kt.data),Jt[qt]<Z))continue;Qt.push(qt)}for(const qt of Qt){let Er=Ot[Ut].data;Er=g(Er),St!==null&&(Er=Er.map((Qr,Cr)=>Qr*St[(Cr+1)%2])),Rt.boxes.push(Er),Rt.classes.push(qt),Rt.scores.push(Jt[qt])}}Mt.push(Rt)}return Mt}function w(Ve,Z){var ve;if(!(Ve instanceof Float32Array||Ve instanceof Float64Array))throw new Error(`${Z} expects input to be a Float32Array or a Float64Array, but got ${((ve=Ve==null?void 0:Ve.constructor)==null?void 0:ve.name)??typeof Ve} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function C(Ve,Z,ve=0,Re=null){const He=Ve/Z;let Xe=(0,f.bankers_round)(He)*Z;return Re!==null&&Xe>Re&&(Xe=Math.floor(He)*Z),Xe<ve&&(Xe=Math.ceil(He)*Z),Xe}function k([Ve,Z],ve){return[Math.max(Math.floor(Ve/ve),1)*ve,Math.max(Math.floor(Z/ve),1)*ve]}class z extends o.Callable{constructor(Z){super(),this.config=Z}}class S extends z{constructor(Z){super(Z),this.image_mean=this.config.image_mean??this.config.mean,this.image_std=this.config.image_std??this.config.std,this.resample=this.config.resample??2,this.do_rescale=this.config.do_rescale??!0,this.rescale_factor=this.config.rescale_factor??1/255,this.do_normalize=this.config.do_normalize,this.do_resize=this.config.do_resize,this.do_thumbnail=this.config.do_thumbnail,this.size=this.config.size,this.size_divisibility=this.config.size_divisibility??this.config.size_divisor,this.do_center_crop=this.config.do_center_crop,this.crop_size=this.config.crop_size,this.do_convert_rgb=this.config.do_convert_rgb??!0,this.do_crop_margin=this.config.do_crop_margin,this.pad_size=this.config.pad_size,this.do_pad=this.config.do_pad,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=this.config.do_flip_channel_order??!1}async thumbnail(Z,ve,Re=2){const He=Z.height,Xe=Z.width,rt=ve.height,ft=ve.width;let ht=Math.min(He,rt),Mt=Math.min(Xe,ft);return ht===He&&Mt===Xe?Z:(He>Xe?Mt=Math.floor(Xe*ht/He):Xe>He&&(ht=Math.floor(He*Mt/Xe)),await Z.resize(Mt,ht,{resample:Re}))}async crop_margin(Z,ve=200){const Re=Z.clone().grayscale(),He=(0,f.min)(Re.data)[0],rt=(0,f.max)(Re.data)[0]-He;if(rt===0)return Z;const ft=ve/255;let ht=Re.width,Mt=Re.height,wt=0,St=0;const Rt=Re.data;for(let at=0;at<Re.height;++at){const Ot=at*Re.width;for(let Ut=0;Ut<Re.width;++Ut)(Rt[Ot+Ut]-He)/rt<ft&&(ht=Math.min(ht,Ut),Mt=Math.min(Mt,at),wt=Math.max(wt,Ut),St=Math.max(St,at))}return Z=await Z.crop([ht,Mt,wt,St]),Z}pad_image(Z,ve,Re,{mode:He="constant",center:Xe=!1,constant_values:rt=0}={}){const[ft,ht,Mt]=ve;let wt,St;if(typeof Re=="number"?(wt=Re,St=Re):(wt=Re.width,St=Re.height),wt!==ht||St!==ft){const Rt=new Float32Array(wt*St*Mt);if(Array.isArray(rt))for(let Ut=0;Ut<Rt.length;++Ut)Rt[Ut]=rt[Ut%Mt];else rt!==0&&Rt.fill(rt);const[at,Ot]=Xe?[Math.floor((wt-ht)/2),Math.floor((St-ft)/2)]:[0,0];for(let Ut=0;Ut<ft;++Ut){const Kt=(Ut+Ot)*wt,Qt=Ut*ht;for(let Jt=0;Jt<ht;++Jt){const qt=(Kt+Jt+at)*Mt,Er=(Qt+Jt)*Mt;for(let Qr=0;Qr<Mt;++Qr)Rt[qt+Qr]=Z[Er+Qr]}}if(He==="symmetric"){if(Xe)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const Ut=ft-1,Kt=ht-1;for(let Qt=0;Qt<St;++Qt){const Jt=Qt*wt,qt=(0,a.calculateReflectOffset)(Qt,Ut)*ht;for(let Er=0;Er<wt;++Er){if(Qt<ft&&Er<ht)continue;const Qr=(Jt+Er)*Mt,Cr=(qt+(0,a.calculateReflectOffset)(Er,Kt))*Mt;for(let mt=0;mt<Mt;++mt)Rt[Qr+mt]=Z[Cr+mt]}}}Z=Rt,ve=[St,wt,Mt]}return[Z,ve]}rescale(Z){for(let ve=0;ve<Z.length;++ve)Z[ve]=this.rescale_factor*Z[ve]}get_resize_output_image_size(Z,ve){const[Re,He]=Z.size;let Xe,rt;if(this.do_thumbnail){const{height:ft,width:ht}=ve;Xe=Math.min(ft,ht)}else Number.isInteger(ve)?(Xe=ve,rt=this.config.max_size??Xe):ve!==void 0&&(Xe=ve.shortest_edge,rt=ve.longest_edge);if(Xe!==void 0||rt!==void 0){const ft=Xe===void 0?1:Math.max(Xe/Re,Xe/He),ht=Re*ft,Mt=He*ft,wt=rt===void 0?1:Math.min(rt/ht,rt/Mt);let St=Math.floor(Number((ht*wt).toFixed(2))),Rt=Math.floor(Number((Mt*wt).toFixed(2)));return this.size_divisibility!==void 0&&([St,Rt]=k([St,Rt],this.size_divisibility)),[St,Rt]}else if(ve!==void 0&&ve.width!==void 0&&ve.height!==void 0){let ft=ve.width,ht=ve.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let Mt=ht/He,wt=ft/Re;Math.abs(1-wt)<Math.abs(1-Mt)?Mt=wt:wt=Mt,ht=C(Mt*He,this.config.ensure_multiple_of),ft=C(wt*Re,this.config.ensure_multiple_of)}return[ft,ht]}else{if(this.size_divisibility!==void 0)return k([Re,He],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(ve)}`)}}async resize(Z){const[ve,Re]=this.get_resize_output_image_size(Z,this.size);return await Z.resize(ve,Re,{resample:this.resample})}async preprocess(Z,{do_normalize:ve=null,do_pad:Re=null,do_convert_rgb:He=null,do_convert_grayscale:Xe=null,do_flip_channel_order:rt=null}={}){this.do_crop_margin&&(Z=await this.crop_margin(Z));const[ft,ht]=Z.size;if(He??this.do_convert_rgb?Z=Z.rgb():Xe&&(Z=Z.grayscale()),this.do_resize&&(Z=await this.resize(Z)),this.do_thumbnail&&(Z=await this.thumbnail(Z,this.size,this.resample)),this.do_center_crop){let at,Ot;Number.isInteger(this.crop_size)?(at=this.crop_size,Ot=this.crop_size):(at=this.crop_size.width,Ot=this.crop_size.height),Z=await Z.center_crop(at,Ot)}const Mt=[Z.height,Z.width];let wt=Float32Array.from(Z.data),St=[Z.height,Z.width,Z.channels];if(this.do_rescale&&this.rescale(wt),ve??this.do_normalize){let at=this.image_mean;Array.isArray(this.image_mean)||(at=new Array(Z.channels).fill(at));let Ot=this.image_std;if(Array.isArray(this.image_std)||(Ot=new Array(Z.channels).fill(at)),at.length!==Z.channels||Ot.length!==Z.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${at.length}) and \`image_std\` (${Ot.length}) must match the number of channels in the image (${Z.channels}).`);for(let Ut=0;Ut<wt.length;Ut+=Z.channels)for(let Kt=0;Kt<Z.channels;++Kt)wt[Ut+Kt]=(wt[Ut+Kt]-at[Kt])/Ot[Kt]}if(Re??this.do_pad){if(this.pad_size)[wt,St]=this.pad_image(wt,[Z.height,Z.width,Z.channels],this.pad_size);else if(this.size_divisibility){const[at,Ot]=k([St[1],St[0]],this.size_divisibility);[wt,St]=this.pad_image(wt,St,{width:at,height:Ot})}}if(rt??this.do_flip_channel_order){if(St[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let at=0;at<wt.length;at+=3){const Ot=wt[at];wt[at]=wt[at+2],wt[at+2]=Ot}}const Rt=new _.Tensor("float32",wt,St).permute(2,0,1);return{original_size:[ht,ft],reshaped_input_size:Mt,pixel_values:Rt}}async _call(Z,...ve){Array.isArray(Z)||(Z=[Z]);const Re=await Promise.all(Z.map(Xe=>this.preprocess(Xe)));return{pixel_values:(0,_.stack)(Re.map(Xe=>Xe.pixel_values),0),original_sizes:Re.map(Xe=>Xe.original_size),reshaped_input_sizes:Re.map(Xe=>Xe.reshaped_input_size)}}}class P extends S{post_process_semantic_segmentation(Z,ve=null){const Re=Z.logits,He=Re.dims[0];if(ve!==null&&ve.length!==He)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Xe=[];for(let rt=0;rt<He;++rt){const ft=ve!==null?ve[rt]:null;let ht=Re[rt];ft!==null&&(ht=(0,_.interpolate)(ht,ft,"bilinear",!1));const[Mt,wt]=ft??ht.dims.slice(-2),St=new _.Tensor("int32",new Int32Array(Mt*wt),[Mt,wt]),Rt=ht[0].data,at=St.data;for(let Qt=1;Qt<ht.dims[0];++Qt){const Jt=ht[Qt].data;for(let qt=0;qt<Jt.length;++qt)Jt[qt]>Rt[qt]&&(Rt[qt]=Jt[qt],at[qt]=Qt)}const Ot=new Array(ht.dims[0]),Ut=St.data;for(let Qt=0;Qt<Ut.length;++Qt){const Jt=Ut[Qt];Ot[Jt]=Jt}const Kt=Ot.filter(Qt=>Qt!==void 0);Xe.push({segmentation:St,labels:Kt})}return Xe}}class y extends S{}class x extends y{}class I extends S{}class U extends S{}class O extends S{}class N extends O{}class j extends S{}class D extends S{}class Y extends S{constructor(Z){super(Z),this.crop_pct=this.config.crop_pct??224/256}async resize(Z){var Re;const ve=(Re=this.size)==null?void 0:Re.shortest_edge;if(ve===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ve<384){const He=Math.floor(ve/this.crop_pct),[Xe,rt]=this.get_resize_output_image_size(Z,{shortest_edge:He});Z=await Z.resize(Xe,rt,{resample:this.resample}),Z=await Z.center_crop(ve,ve)}else Z=await Z.resize(ve,ve,{resample:this.resample});return Z}}class de extends Y{}class Ce extends S{}class ee extends S{}class ye extends S{constructor(Z){super(Z),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ve=>ve*ve))}}class R extends S{}class Me extends S{}class Qe extends S{}class ge extends S{}class Q extends S{}class ae extends Q{}class Se extends S{post_process_object_detection(...Z){return M(...Z)}}class X extends Se{}class me extends S{post_process_object_detection(...Z){return M(...Z)}}class Ke extends S{}class De extends S{}class Be extends S{pad_image(Z,ve,Re,He={}){const[Xe,rt,ft]=ve;let ht=this.image_mean;Array.isArray(this.image_mean)||(ht=new Array(ft).fill(ht));let Mt=this.image_std;Array.isArray(Mt)||(Mt=new Array(ft).fill(ht));const wt=ht.map((St,Rt)=>-St/Mt[Rt]);return super.pad_image(Z,ve,Re,{center:!0,constant_values:wt,...He})}}class We extends Be{}class ot extends S{async _call(Z){const ve=await super._call(Z),Re=[ve.pixel_values.dims[0],64,64],He=new _.Tensor("int64",new BigInt64Array(Re.reduce((Xe,rt)=>Xe*rt)).fill(1n),Re);return{...ve,pixel_mask:He}}post_process_object_detection(...Z){return M(...Z)}remove_low_and_no_objects(Z,ve,Re,He){let Xe=[],rt=[],ft=[];for(let ht=0;ht<Z.dims[0];++ht){let Mt=Z[ht],wt=ve[ht],St=(0,f.max)(Mt.data)[1];if(St===He)continue;let at=(0,f.softmax)(Mt.data)[St];at>Re&&(Xe.push(wt),rt.push(at),ft.push(St))}return[Xe,rt,ft]}check_segment_validity(Z,ve,Re,He=.5,Xe=.8){let rt=[],ft=0,ht=0;const Mt=ve[Re].data;for(let St=0;St<Z.length;++St)Z[St]===Re&&(rt.push(St),++ft),Mt[St]>=He&&++ht;let wt=ft>0&&ht>0;return wt&&(wt=ft/ht>Xe),[wt,rt]}compute_segments(Z,ve,Re,He,Xe,rt=null,ft=null){let[ht,Mt]=ft??Z[0].dims,wt=new _.Tensor("int32",new Int32Array(ht*Mt),[ht,Mt]),St=[];if(ft!==null)for(let Kt=0;Kt<Z.length;++Kt)Z[Kt]=(0,_.interpolate)(Z[Kt],ft,"bilinear",!1);let Rt=new Int32Array(Z[0].data.length),at=new Float32Array(Z[0].data.length);for(let Kt=0;Kt<Z.length;++Kt){let Qt=ve[Kt];const Jt=Z[Kt].data;for(let qt=0;qt<Jt.length;++qt)Jt[qt]*=Qt,Jt[qt]>at[qt]&&(Rt[qt]=Kt,at[qt]=Jt[qt])}let Ot=0;const Ut=wt.data;for(let Kt=0;Kt<Re.length;++Kt){let Qt=Re[Kt],[Jt,qt]=this.check_segment_validity(Rt,Z,Kt,He,Xe);if(Jt){++Ot;for(let Er of qt)Ut[Er]=Ot;St.push({id:Ot,label_id:Qt,score:ve[Kt]})}}return[wt,St]}post_process_panoptic_segmentation(Z,ve=.5,Re=.5,He=.8,Xe=null,rt=null){Xe===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),Xe=new Set);const ft=Z.logits,Mt=Z.pred_masks.sigmoid();let[wt,St,Rt]=ft.dims;if(Rt-=1,rt!==null&&rt.length!==wt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let at=[];for(let Ot=0;Ot<wt;++Ot){let Ut=rt!==null?rt[Ot]:null,Kt=ft[Ot],Qt=Mt[Ot],[Jt,qt,Er]=this.remove_low_and_no_objects(Kt,Qt,ve,Rt);if(Er.length===0){let[mt,Pt]=Ut??Qt.dims.slice(-2),Bt=new _.Tensor("int32",new Int32Array(mt*Pt).fill(-1),[mt,Pt]);at.push({segmentation:Bt,segments_info:[]});continue}let[Qr,Cr]=this.compute_segments(Jt,qt,Er,Re,He,Xe,Ut);at.push({segmentation:Qr,segments_info:Cr})}return at}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class dt extends S{post_process_object_detection(...Z){return M(...Z)}}class Ge extends S{reshape_input_points(Z,ve,Re,He=!1){Z=structuredClone(Z);let Xe=(0,a.calculateDimensions)(Z);if(Xe.length===3)He||(Xe=[1,...Xe]),Z=[Z];else if(Xe.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let rt=0;rt<Z.length;++rt){let ft=ve[rt],ht=Re[rt],Mt=[ht[0]/ft[0],ht[1]/ft[1]];for(let wt=0;wt<Z[rt].length;++wt)for(let St=0;St<Z[rt][wt].length;++St)for(let Rt=0;Rt<Z[rt][wt][St].length;++Rt)Z[rt][wt][St][Rt]*=Mt[Rt%2]}return new _.Tensor("float32",Float32Array.from(Z.flat(1/0)),Xe)}add_input_labels(Z,ve){let Re=(0,a.calculateDimensions)(Z);if(Re.length===2)Re=[1,...Re],Z=[Z];else if(Re.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(Re.some((He,Xe)=>He!==ve.dims[Xe]))throw Error(`The first ${Re.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new _.Tensor("int64",Z.flat(1/0).map(BigInt),Re)}async _call(Z,{input_points:ve=null,input_labels:Re=null,input_boxes:He=null}={}){const Xe=await super._call(Z);if(ve&&(Xe.input_points=this.reshape_input_points(ve,Xe.original_sizes,Xe.reshaped_input_sizes)),Re){if(!Xe.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Xe.input_labels=this.add_input_labels(Re,Xe.input_points)}return He&&(Xe.input_boxes=this.reshape_input_points(He,Xe.original_sizes,Xe.reshaped_input_sizes,!0)),Xe}async post_process_masks(Z,ve,Re,{mask_threshold:He=0,binarize:Xe=!0,pad_size:rt=null}={}){const ft=[];rt=rt??this.pad_size;const ht=[rt.height,rt.width];for(let Mt=0;Mt<ve.length;++Mt){const wt=ve[Mt],St=Re[Mt];let Rt=await(0,_.interpolate_4d)(Z[Mt],{mode:"bilinear",size:ht});if(Rt=Rt.slice(null,null,[0,St[0]],[0,St[1]]),Rt=await(0,_.interpolate_4d)(Rt,{mode:"bilinear",size:wt}),Xe){const at=Rt.data,Ot=new Uint8Array(at.length);for(let Ut=0;Ut<at.length;++Ut)at[Ut]>He&&(Ot[Ut]=1);Rt=new _.Tensor("bool",Ot,Rt.dims)}ft.push(Rt)}return ft}generate_crop_boxes(Z,ve,{crop_n_layers:Re=0,overlap_ratio:He=512/1500,points_per_crop:Xe=32,crop_n_points_downscale_factor:rt=1}={}){}}class Te extends S{pad_image(Z,ve,Re,He={}){const[Xe,rt,ft]=ve;return super.pad_image(Z,ve,{width:rt+(Re-rt%Re)%Re,height:Xe+(Re-Xe%Re)%Re},{mode:"symmetric",center:!1,constant_values:-1,...He})}}class je extends S{async _call(Z,ve){Array.isArray(Z)||(Z=[Z]),Array.isArray(ve)||(ve=[ve]);const Re=await Promise.all(Z.map(rt=>this.preprocess(rt))),He=await Promise.all(ve.map(rt=>this.preprocess(rt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,_.stack)(Re.map((rt,ft)=>(0,_.cat)([rt.pixel_values,He[ft].pixel_values],0)),0),original_sizes:Re.map(rt=>rt.original_size),reshaped_input_sizes:Re.map(rt=>rt.reshaped_input_size)}}}class Ye extends z{constructor(Z){var ve;super(Z),(ve=this.config).mel_filters??(ve.mel_filters=(0,h.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,h.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(Z){const ve=await(0,h.spectrogram)(Z,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),Re=ve.data,He=(0,f.max)(Re)[0];for(let Xe=0;Xe<Re.length;++Xe)Re[Xe]=(Math.max(Re[Xe],He-8)+4)/4;return ve}async _call(Z){w(Z,"WhisperFeatureExtractor");let ve;return Z.length>this.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),ve=Z.slice(0,this.config.n_samples)):(ve=new Float32Array(this.config.n_samples),ve.set(Z)),{input_features:(await this._extract_fbank_features(ve)).unsqueeze_(0)}}}class tt extends z{_zero_mean_unit_var_norm(Z){const Re=Z.reduce((Xe,rt)=>Xe+rt,0)/Z.length,He=Z.reduce((Xe,rt)=>Xe+(rt-Re)**2,0)/Z.length;return Z.map(Xe=>(Xe-Re)/Math.sqrt(He+1e-7))}async _call(Z){w(Z,"Wav2Vec2FeatureExtractor"),Z instanceof Float64Array&&(Z=new Float32Array(Z));let ve=Z;this.config.do_normalize&&(ve=this._zero_mean_unit_var_norm(ve));const Re=[1,ve.length];return{input_values:new _.Tensor("float32",ve,Re),attention_mask:new _.Tensor("int64",new BigInt64Array(ve.length).fill(1n),Re)}}}class A extends z{constructor(Z){super(Z);const ve=this.config.sampling_rate,Re=(0,h.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ve/2),ve,null,"kaldi",!0);for(let He=0;He<Re.length;++He)Re[He].push(0);this.mel_filters=Re,this.window=(0,h.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(Z,ve){return Z=Z.map(Re=>Re*32768),(0,h.spectrogram)(Z,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:ve,transpose:!0})}async _call(Z,{padding:ve=!0,pad_to_multiple_of:Re=2,do_normalize_per_mel_bins:He=!0,return_attention_mask:Xe=!0}={}){w(Z,"SeamlessM4TFeatureExtractor");let rt=await this._extract_fbank_features(Z,this.config.max_length);if(He){const[Ot,Ut]=rt.dims,Kt=rt.data;for(let Qt=0;Qt<Ut;++Qt){let Jt=0;for(let Cr=0;Cr<Ot;++Cr)Jt+=Kt[Cr*Ut+Qt];const qt=Jt/Ot;let Er=0;for(let Cr=0;Cr<Ot;++Cr)Er+=(Kt[Cr*Ut+Qt]-qt)**2;Er/=Ot-1;const Qr=Math.sqrt(Er+1e-7);for(let Cr=0;Cr<Ot;++Cr){const mt=Cr*Ut+Qt;Kt[mt]=(Kt[mt]-qt)/Qr}}}let ft;if(ve){const[Ot,Ut]=rt.dims,Kt=rt.data,Qt=Ot%Re;if(Qt>0){const Jt=new Float32Array(Ut*(Ot+Qt));Jt.set(Kt),Jt.fill(this.config.padding_value,Kt.length);const qt=Ot+Qt;rt=new _.Tensor(rt.type,Jt,[qt,Ut]),Xe&&(ft=new _.Tensor("int64",new BigInt64Array(qt),[1,qt]),ft.data.fill(1n,0,Ot))}}const[ht,Mt]=rt.dims,wt=this.config.stride;if(ht%wt!==0)throw new Error(`The number of frames (${ht}) must be a multiple of the stride (${wt}).`);const Rt=rt.view(1,Math.floor(ht/wt),Mt*wt),at={input_features:Rt};if(Xe){const Ot=Rt.dims[1],Ut=new BigInt64Array(Ot);if(ft){const Kt=ft.data;for(let Qt=1,Jt=0;Qt<ht;Qt+=wt,++Jt)Ut[Jt]=Kt[Qt]}else Ut.fill(1n);at.attention_mask=new _.Tensor("int64",Ut,[1,Ot])}return at}}class Ae extends z{constructor(Z){super(Z);const ve=this.config.sampling_rate,Re=(0,h.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ve/2),ve,null,"kaldi",!0);for(let He=0;He<Re.length;++He)Re[He].push(0);this.mel_filters=Re,this.window=(0,h.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(Z,ve){return(0,h.spectrogram)(Z,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:ve,transpose:!0})}async _call(Z){w(Z,"ASTFeatureExtractor");const ve=await this._extract_fbank_features(Z,this.config.max_length);if(this.config.do_normalize){const Re=this.std*2,He=ve.data;for(let Xe=0;Xe<He.length;++Xe)He[Xe]=(He[Xe]-this.mean)/Re}return{input_values:ve.unsqueeze_(0)}}}class $e extends z{constructor(Z){super(Z),this.mel_filters=(0,h.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,h.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,h.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(Z,ve,Re,He){let Xe;const rt=Z.length-ve;if(rt>0)if(Re==="rand_trunc"){const ft=Math.floor(Math.random()*(rt+1));Z=Z.subarray(ft,ft+ve),Xe=await this._extract_fbank_features(Z,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Re}" not implemented`);else{if(rt<0){let ft=new Float64Array(ve);if(ft.set(Z),He==="repeat")for(let ht=Z.length;ht<ve;ht+=Z.length)ft.set(Z.subarray(0,Math.min(Z.length,ve-ht)),ht);else if(He==="repeatpad")for(let ht=Z.length;ht<-rt;ht+=Z.length)ft.set(Z,ht);Z=ft}if(Re==="fusion")throw new Error(`Truncation strategy "${Re}" not implemented`);Xe=await this._extract_fbank_features(Z,this.mel_filters_slaney,this.config.nb_max_samples)}return Xe.unsqueeze_(0)}async _extract_fbank_features(Z,ve,Re=null){return(0,h.spectrogram)(Z,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:ve,log_mel:"dB",max_num_frames:Re,do_pad:!1,transpose:!0})}async _call(Z,{max_length:ve=null}={}){return w(Z,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(Z,ve??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}class se extends z{async _call(Z){w(Z,"PyAnnoteFeatureExtractor"),Z instanceof Float64Array&&(Z=new Float32Array(Z));const ve=[1,1,Z.length];return{input_values:new _.Tensor("float32",Z,ve)}}samples_to_frames(Z){return(Z-this.config.offset)/this.config.step}post_process_speaker_diarization(Z,ve){const Re=ve/this.samples_to_frames(ve)/this.config.sampling_rate,He=[];for(const Xe of Z.tolist()){const rt=[];let ft=-1;for(let ht=0;ht<Xe.length;++ht){const Mt=(0,f.softmax)(Xe[ht]),[wt,St]=(0,f.max)(Mt),[Rt,at]=[ht,ht+1];St!==ft?(ft=St,rt.push({id:St,start:Rt,end:at,score:wt})):(rt.at(-1).end=at,rt.at(-1).score+=wt)}He.push(rt.map(({id:ht,start:Mt,end:wt,score:St})=>({id:ht,start:Mt*Re,end:wt*Re,confidence:St/(wt-Mt)})))}return He}}class te extends z{constructor(Z){super(Z);const ve=this.config.sampling_rate,Re=(0,h.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ve/2),ve,null,"kaldi",!0);for(let He=0;He<Re.length;++He)Re[He].push(0);this.mel_filters=Re,this.window=(0,h.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(Z){return Z=Z.map(ve=>ve*32768),(0,h.spectrogram)(Z,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(Z){w(Z,"WeSpeakerFeatureExtractor");const ve=(await this._extract_fbank_features(Z)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Re=ve.mean(1).data,He=ve.data,[Xe,rt,ft]=ve.dims;for(let ht=0;ht<Xe;++ht){const Mt=ht*rt*ft,wt=ht*ft;for(let St=0;St<rt;++St){const Rt=Mt+St*ft;for(let at=0;at<ft;++at)He[Rt+at]-=Re[wt+at]}}}return{input_features:ve}}}class we extends z{}class B extends o.Callable{constructor(Z){super(),this.feature_extractor=Z}async _call(Z,...ve){return await this.feature_extractor(Z,...ve)}}class J extends B{async _call(...Z){return await this.feature_extractor(...Z)}post_process_masks(...Z){return this.feature_extractor.post_process_masks(...Z)}reshape_input_points(...Z){return this.feature_extractor.reshape_input_points(...Z)}}class L extends B{async _call(Z){return await this.feature_extractor(Z)}}class ue extends B{async _call(Z){return await this.feature_extractor(Z)}}class le extends B{async _call(Z){return await this.feature_extractor(Z)}post_process_speaker_diarization(...Z){return this.feature_extractor.post_process_speaker_diarization(...Z)}}class ke extends B{async _call(Z){return await this.feature_extractor(Z)}}class Ne extends B{}class ut extends B{constructor(Z){super(Z);const{tasks_answer_post_processing_type:ve,task_prompts_without_inputs:Re,task_prompts_with_input:He}=Z.config;this.tasks_answer_post_processing_type=new Map(Object.entries(ve??{})),this.task_prompts_without_inputs=new Map(Object.entries(Re??{})),this.task_prompts_with_input=new Map(Object.entries(He??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(Z){typeof Z=="string"&&(Z=[Z]);const ve=[];for(const Re of Z)if(this.task_prompts_without_inputs.has(Re))ve.push(this.task_prompts_without_inputs.get(Re));else{for(const[He,Xe]of this.task_prompts_with_input)if(Re.includes(He)){ve.push(Xe.replaceAll("{input}",Re).replaceAll(He,""));break}ve.length!==Z.length&&ve.push(Re)}return ve}post_process_generation(Z,ve,Re){const He=this.tasks_answer_post_processing_type.get(ve)??"pure_text";Z=Z.replaceAll("<s>","").replaceAll("</s>","");let Xe;switch(He){case"pure_text":Xe=Z;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const rt=He==="ocr"?"quad_boxes":"bboxes",ft=Z.matchAll(this.regexes[rt]),ht=[],Mt=[];for(const[wt,St,...Rt]of ft)ht.push(St?St.trim():ht.at(-1)??""),Mt.push(Rt.map((at,Ot)=>(Number(at)+.5)/this.size_per_bin*Re[Ot%2]));Xe={labels:ht,[rt]:Mt};break;default:throw new Error(`Task "${ve}" (of type "${He}") not yet implemented.`)}return{[ve]:Xe}}}class Je{static async from_pretrained(Z,{progress_callback:ve=null,config:Re=null,cache_dir:He=null,local_files_only:Xe=!1,revision:rt="main"}={}){let ft=Re??await(0,l.getModelJSON)(Z,"preprocessor_config.json",!0,{progress_callback:ve,config:Re,cache_dir:He,local_files_only:Xe,revision:rt}),ht=ft.feature_extractor_type??ft.image_processor_type,Mt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ht];if(!Mt)if(ft.size!==void 0)console.warn(`Feature extractor type "${ht}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Mt=S;else throw new Error(`Unknown Feature Extractor type: ${ht}`);let wt=this.PROCESSOR_CLASS_MAPPING[ft.processor_class]??B,St=new Mt(ft);return new wt(St)}}qe(Je,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:S,WhisperFeatureExtractor:Ye,ViTFeatureExtractor:Ce,MobileViTFeatureExtractor:Q,MobileViTImageProcessor:ae,MobileNetV1FeatureExtractor:R,MobileNetV2FeatureExtractor:Me,MobileNetV3FeatureExtractor:Qe,MobileNetV4FeatureExtractor:ge,OwlViTFeatureExtractor:Se,Owlv2ImageProcessor:X,CLIPFeatureExtractor:O,CLIPImageProcessor:N,Florence2Processor:ut,ChineseCLIPFeatureExtractor:j,SiglipImageProcessor:D,ConvNextFeatureExtractor:Y,ConvNextImageProcessor:de,SegformerFeatureExtractor:P,BitImageProcessor:I,DPTImageProcessor:x,DPTFeatureExtractor:y,GLPNFeatureExtractor:U,BeitFeatureExtractor:De,DeiTFeatureExtractor:Ke,DetrFeatureExtractor:ot,RTDetrImageProcessor:me,YolosFeatureExtractor:dt,DonutFeatureExtractor:Be,NougatImageProcessor:We,EfficientNetImageProcessor:ye,ViTImageProcessor:ee,VitMatteImageProcessor:je,SamImageProcessor:Ge,Swin2SRImageProcessor:Te,Wav2Vec2FeatureExtractor:tt,SeamlessM4TFeatureExtractor:A,SpeechT5FeatureExtractor:we,ASTFeatureExtractor:Ae,ClapFeatureExtractor:$e,PyAnnoteFeatureExtractor:se,WeSpeakerFeatureExtractor:te}),qe(Je,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:L,Wav2Vec2ProcessorWithLM:ue,PyAnnoteProcessor:le,SamProcessor:J,SpeechT5Processor:ke,OwlViTProcessor:Ne,Florence2Processor:ut})},"./src/tokenizers.js":(e,t,n)=>{n.r(t),n.d(t,{AlbertTokenizer:()=>Ut,AutoTokenizer:()=>Rn,BartTokenizer:()=>Nr,BertTokenizer:()=>Ot,BlenderbotSmallTokenizer:()=>jo,BlenderbotTokenizer:()=>ho,BloomTokenizer:()=>Fr,CLIPTokenizer:()=>Xt,CamembertTokenizer:()=>Pt,CodeGenTokenizer:()=>po,CodeLlamaTokenizer:()=>ks,CohereTokenizer:()=>Br,ConvBertTokenizer:()=>Qr,DebertaTokenizer:()=>Jt,DebertaV2Tokenizer:()=>qt,DistilBertTokenizer:()=>mt,ElectraTokenizer:()=>sn,EsmTokenizer:()=>Bi,FalconTokenizer:()=>Lo,GPT2Tokenizer:()=>bi,GPTNeoXTokenizer:()=>Ro,GemmaTokenizer:()=>co,Grok1Tokenizer:()=>di,HerbertTokenizer:()=>Er,LlamaTokenizer:()=>xi,M2M100Tokenizer:()=>Yi,MBart50Tokenizer:()=>Wr,MBartTokenizer:()=>mn,MPNetTokenizer:()=>Do,MarianTokenizer:()=>Bo,MobileBertTokenizer:()=>Kt,NllbTokenizer:()=>Ti,NougatTokenizer:()=>mo,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ss,RoFormerTokenizer:()=>Cr,RobertaTokenizer:()=>ci,SiglipTokenizer:()=>Zi,SpeechT5Tokenizer:()=>Uo,SqueezeBertTokenizer:()=>Qt,T5Tokenizer:()=>Li,TokenizerModel:()=>Ce,VitsTokenizer:()=>Vo,Wav2Vec2CTCTokenizer:()=>No,WhisperTokenizer:()=>fo,XLMRobertaTokenizer:()=>Oo,XLMTokenizer:()=>Bt,is_chinese_char:()=>U});var o=n("./src/utils/generic.js"),a=n("./src/utils/core.js"),l=n("./src/utils/hub.js"),f=n("./src/utils/maths.js"),_=n("./src/utils/tensor.js"),h=n("./src/utils/data-structures.js"),g=n("./node_modules/@huggingface/jinja/dist/index.js"),M=n("./src/models/whisper/common_whisper.js"),w=n("./src/utils/constants.js");async function C(Ue,W){const fe=await Promise.all([(0,l.getModelJSON)(Ue,"tokenizer.json",!0,W),(0,l.getModelJSON)(Ue,"tokenizer_config.json",!0,W)]);return W.legacy!==null&&(fe[1].legacy=W.legacy),fe}function k(Ue,W){const fe=[];let Pe=0;for(const ze of Ue.matchAll(W)){const Oe=ze[0];Pe<ze.index&&fe.push(Ue.slice(Pe,ze.index)),Oe.length>0&&fe.push(Oe),Pe=ze.index+Oe.length}return Pe<Ue.length&&fe.push(Ue.slice(Pe)),fe}function z(Ue,W=!0){if(Ue.Regex!==void 0){let fe=Ue.Regex.replace(/\\([#&~])/g,"$1");for(const[Pe,ze]of Y)fe=fe.replaceAll(Pe,ze);return new RegExp(fe,"gu")}else if(Ue.String!==void 0){const fe=(0,a.escapeRegExp)(Ue.String);return new RegExp(W?fe:`(${fe})`,"gu")}else return console.warn("Unknown pattern type:",Ue),null}function S(Ue){return new Map(Object.entries(Ue))}function P(Ue){const W=Ue.dims;switch(W.length){case 1:return Ue.tolist();case 2:if(W[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return Ue.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${W.length}.`)}}function y(Ue){return Ue.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function x(Ue){return Ue.replace(/[\u0300-\u036f]/g,"")}function I(Ue){return x(Ue.toLowerCase())}function U(Ue){return Ue>=19968&&Ue<=40959||Ue>=13312&&Ue<=19903||Ue>=131072&&Ue<=173791||Ue>=173824&&Ue<=177983||Ue>=177984&&Ue<=178207||Ue>=178208&&Ue<=183983||Ue>=63744&&Ue<=64255||Ue>=194560&&Ue<=195103}function O(Ue,W,fe){const Pe=[];let ze=0;for(;ze<Ue.length;){if(Pe.push(Ue[ze]),(fe.get(Ue[ze])??W)!==W){++ze;continue}for(;ze<Ue.length&&(fe.get(Ue[ze])??W)===W;)++ze}return Pe}function N(Ue){return Ue.match(/\S+/g)||[]}const j="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",D=new RegExp(`^[${j}]+$`,"gu"),Y=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"]]);class de{constructor(W){this.content=W.content,this.id=W.id,this.single_word=W.single_word??!1,this.lstrip=W.lstrip??!1,this.rstrip=W.rstrip??!1,this.special=W.special??!1,this.normalized=W.normalized??null}}class Ce extends o.Callable{constructor(W){super(),this.config=W,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(W,...fe){switch(W.type){case"WordPiece":return new ee(W);case"Unigram":return new ye(W,...fe);case"BPE":return new Qe(W);default:if(W.vocab)return new ge(W,...fe);throw new Error(`Unknown TokenizerModel type: ${W.type}`)}}_call(W){let fe=this.encode(W);return this.fuse_unk&&(fe=O(fe,this.unk_token_id,this.tokens_to_ids)),fe}encode(W){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(W){return W.map(fe=>this.tokens_to_ids.get(fe)??this.unk_token_id)}convert_ids_to_tokens(W){return W.map(fe=>this.vocab[fe]??this.unk_token)}}class ee extends Ce{constructor(W){super(W),this.tokens_to_ids=S(W.vocab),this.unk_token_id=this.tokens_to_ids.get(W.unk_token),this.unk_token=W.unk_token,this.max_input_chars_per_word=W.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Pe]of this.tokens_to_ids)this.vocab[Pe]=fe}encode(W){const fe=[];for(const Pe of W){const ze=[...Pe];if(ze.length>this.max_input_chars_per_word){fe.push(this.unk_token);continue}let Oe=!1,nt=0;const xt=[];for(;nt<ze.length;){let kt=ze.length,Tt=null;for(;nt<kt;){let At=ze.slice(nt,kt).join("");if(nt>0&&(At=this.config.continuing_subword_prefix+At),this.tokens_to_ids.has(At)){Tt=At;break}--kt}if(Tt===null){Oe=!0;break}xt.push(Tt),nt=kt}Oe?fe.push(this.unk_token):fe.push(...xt)}return fe}}class ye extends Ce{constructor(W,fe){super(W);const Pe=W.vocab.length;this.vocab=new Array(Pe),this.scores=new Array(Pe);for(let ze=0;ze<Pe;++ze){const Oe=W.vocab[ze];this.vocab[ze]=Oe[0],this.scores[ze]=Oe[1]}this.unk_token_id=W.unk_id,this.unk_token=this.vocab[W.unk_id],this.tokens_to_ids=new Map(this.vocab.map((ze,Oe)=>[ze,Oe])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=fe.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,f.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new h.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(W){const fe=W.sentence,Pe=fe.length;let ze=0;for(;ze<Pe;){let nt=!1;for(let xt of this.trie.commonPrefixSearch(fe.slice(ze))){const kt=this.tokens_to_ids.get(xt),Tt=this.scores[kt],At=xt.length;W.insert(ze,At,Tt,kt),!nt&&At===1&&(nt=!0)}nt||W.insert(ze,1,this.unkScore,this.unk_token_id),ze+=1}}tokenize(W){const fe=new h.TokenLattice(W,this.bosTokenId,this.eosTokenId);return this.populateNodes(fe),fe.tokens()}encode(W){const fe=[];for(const Pe of W){const ze=this.tokenize(Pe);fe.push(...ze)}return fe}}const R=(()=>{const Ue=[...Array.from({length:94},(ze,Oe)=>Oe+33),...Array.from({length:12},(ze,Oe)=>Oe+161),...Array.from({length:82},(ze,Oe)=>Oe+174)],W=Ue.slice();let fe=0;for(let ze=0;ze<256;++ze)Ue.includes(ze)||(Ue.push(ze),W.push(256+fe),fe+=1);const Pe=W.map(ze=>String.fromCharCode(ze));return Object.fromEntries(Ue.map((ze,Oe)=>[ze,Pe[Oe]]))})(),Me=(0,a.reverseDictionary)(R);class Qe extends Ce{constructor(W){super(W),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=S(W.vocab),this.unk_token_id=this.tokens_to_ids.get(W.unk_token),this.unk_token=W.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Pe]of this.tokens_to_ids)this.vocab[Pe]=fe;this.bpe_ranks=new Map(W.merges.map((fe,Pe)=>[fe,Pe])),this.merges=W.merges.map(fe=>fe.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=W.end_of_word_suffix,this.continuing_subword_suffix=W.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(W){if(W.length===0)return[];const fe=this.cache.get(W);if(fe!==void 0)return fe;const Pe=Array.from(W);this.end_of_word_suffix&&(Pe[Pe.length-1]+=this.end_of_word_suffix);let ze=[];if(Pe.length>1){const Oe=new h.PriorityQueue((kt,Tt)=>kt.score<Tt.score);let nt={token:Pe[0],bias:0,prev:null,next:null},xt=nt;for(let kt=1;kt<Pe.length;++kt){const Tt={bias:kt/Pe.length,token:Pe[kt],prev:xt,next:null};xt.next=Tt,this._add_node(Oe,xt),xt=Tt}for(;!Oe.isEmpty();){const kt=Oe.pop();if(kt.deleted||!kt.next||kt.next.deleted)continue;if(kt.deleted=!0,kt.next.deleted=!0,kt.prev){const At={...kt.prev};kt.prev.deleted=!0,kt.prev=At,At.prev?At.prev.next=At:nt=At}const Tt={token:kt.token+kt.next.token,bias:kt.bias,prev:kt.prev,next:kt.next.next};Tt.prev?(Tt.prev.next=Tt,this._add_node(Oe,Tt.prev)):nt=Tt,Tt.next&&(Tt.next.prev=Tt,this._add_node(Oe,Tt))}for(let kt=nt;kt!==null;kt=kt.next)ze.push(kt.token)}else ze=Pe;if(this.continuing_subword_suffix)for(let Oe=0;Oe<ze.length-1;++Oe)ze[Oe]+=this.continuing_subword_suffix;return this.cache.set(W,ze),ze}_add_node(W,fe){const Pe=this.bpe_ranks.get(fe.token+this.BPE_SPLIT_TOKEN+fe.next.token);Pe!==void 0&&(fe.score=Pe+fe.bias,W.push(fe))}encode(W){const fe=[];for(const Pe of W){if(this.ignore_merges&&this.tokens_to_ids.has(Pe)){fe.push(Pe);continue}const ze=this.bpe(Pe);for(const Oe of ze)this.tokens_to_ids.has(Oe)?fe.push(Oe):this.byte_fallback?fe.push(...Array.from(this.text_encoder.encode(Oe)).map(nt=>`<0x${nt.toString(16).toUpperCase().padStart(2,"0")}>`)):fe.push(this.unk_token)}return fe}}class ge extends Ce{constructor(W,fe){super(W),this.tokens_to_ids=S(fe.target_lang?W.vocab[fe.target_lang]:W.vocab),this.bos_token=fe.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=fe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=fe.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=fe.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Pe,ze]of this.tokens_to_ids)this.vocab[ze]=Pe}encode(W){return W}}class Q extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"BertNormalizer":return new dt(W);case"Precompiled":return new Xe(W);case"Sequence":return new ot(W);case"Replace":return new ae(W);case"NFC":return new Se(W);case"NFKC":return new X(W);case"NFKD":return new me(W);case"Strip":return new Ke(W);case"StripAccents":return new De(W);case"Lowercase":return new Be(W);case"Prepend":return new We(W);default:throw new Error(`Unknown Normalizer type: ${W.type}`)}}normalize(W){throw Error("normalize should be implemented in subclass.")}_call(W){return this.normalize(W)}}class ae extends Q{normalize(W){const fe=z(this.config.pattern);return fe===null?W:W.replaceAll(fe,this.config.content)}}class Se extends Q{normalize(W){return W=W.normalize("NFC"),W}}class X extends Q{normalize(W){return W=W.normalize("NFKC"),W}}class me extends Q{normalize(W){return W=W.normalize("NFKD"),W}}class Ke extends Q{normalize(W){return this.config.strip_left&&this.config.strip_right?W=W.trim():(this.config.strip_left&&(W=W.trimStart()),this.config.strip_right&&(W=W.trimEnd())),W}}class De extends Q{normalize(W){return W=x(W),W}}class Be extends Q{normalize(W){return W=W.toLowerCase(),W}}class We extends Q{normalize(W){return W=this.config.prepend+W,W}}class ot extends Q{constructor(W){super(W),this.normalizers=W.normalizers.map(fe=>Q.fromConfig(fe))}normalize(W){return this.normalizers.reduce((fe,Pe)=>Pe.normalize(fe),W)}}class dt extends Q{_tokenize_chinese_chars(W){const fe=[];for(let Pe=0;Pe<W.length;++Pe){const ze=W[Pe],Oe=ze.charCodeAt(0);U(Oe)?(fe.push(" "),fe.push(ze),fe.push(" ")):fe.push(ze)}return fe.join("")}stripAccents(W){return W.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(W){switch(W){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(W)}}_clean_text(W){const fe=[];for(const Pe of W){const ze=Pe.charCodeAt(0);ze===0||ze===65533||this._is_control(Pe)||(/^\s$/.test(Pe)?fe.push(" "):fe.push(Pe))}return fe.join("")}normalize(W){return this.config.clean_text&&(W=this._clean_text(W)),this.config.handle_chinese_chars&&(W=this._tokenize_chinese_chars(W)),this.config.lowercase?(W=W.toLowerCase(),this.config.strip_accents!==!1&&(W=this.stripAccents(W))):this.config.strip_accents&&(W=this.stripAccents(W)),W}}class Ge extends o.Callable{static fromConfig(W){if(W===null)return null;switch(W.type){case"BertPreTokenizer":return new Te(W);case"Sequence":return new rt(W);case"Whitespace":return new ft(W);case"WhitespaceSplit":return new ht(W);case"Metaspace":return new Re(W);case"ByteLevel":return new je(W);case"Split":return new Ye(W);case"Punctuation":return new tt(W);case"Digits":return new A(W);case"Replace":return new Mt(W);default:throw new Error(`Unknown PreTokenizer type: ${W.type}`)}}pre_tokenize_text(W,fe){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(W,fe){return(Array.isArray(W)?W.map(Pe=>this.pre_tokenize_text(Pe,fe)):this.pre_tokenize_text(W,fe)).flat()}_call(W,fe){return this.pre_tokenize(W,fe)}}class Te extends Ge{constructor(W){super(),this.pattern=new RegExp(`[^\\s${j}]+|[${j}]`,"gu")}pre_tokenize_text(W,fe){return W.trim().match(this.pattern)||[]}}class je extends Ge{constructor(W){super(),this.config=W,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=R,this.text_encoder=new TextEncoder}pre_tokenize_text(W,fe){return this.add_prefix_space&&!W.startsWith(" ")&&(W=" "+W),(this.use_regex?W.match(this.pattern)||[]:[W]).map(ze=>Array.from(this.text_encoder.encode(ze),Oe=>this.byte_encoder[Oe]).join(""))}}class Ye extends Ge{constructor(W){super(),this.config=W,this.pattern=z(this.config.pattern,this.config.invert)}pre_tokenize_text(W,fe){return this.pattern===null?[]:this.config.invert?W.match(this.pattern)||[]:k(W,this.pattern)}}class tt extends Ge{constructor(W){super(),this.config=W,this.pattern=new RegExp(`[^${j}]+|[${j}]+`,"gu")}pre_tokenize_text(W,fe){return W.match(this.pattern)||[]}}class A extends Ge{constructor(W){super(),this.config=W;const fe=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(fe,"gu")}pre_tokenize_text(W,fe){return W.match(this.pattern)||[]}}class Ae extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"TemplateProcessing":return new te(W);case"ByteLevel":return new we(W);case"RobertaProcessing":return new se(W);case"BertProcessing":return new $e(W);case"Sequence":return new B(W);default:throw new Error(`Unknown PostProcessor type: ${W.type}`)}}post_process(W,...fe){throw Error("post_process should be implemented in subclass.")}_call(W,...fe){return this.post_process(W,...fe)}}class $e extends Ae{constructor(W){super(W),this.cls=W.cls[0],this.sep=W.sep[0]}post_process(W,fe=null,{add_special_tokens:Pe=!0}={}){Pe&&(W=(0,a.mergeArrays)([this.cls],W,[this.sep]));let ze=new Array(W.length).fill(0);if(fe!==null){const Oe=Pe&&this instanceof se?[this.sep]:[],nt=Pe?[this.sep]:[];W=(0,a.mergeArrays)(W,Oe,fe,nt),ze=(0,a.mergeArrays)(ze,new Array(fe.length+Oe.length+nt.length).fill(1))}return{tokens:W,token_type_ids:ze}}}class se extends $e{}class te extends Ae{constructor(W){super(W),this.single=W.single,this.pair=W.pair}post_process(W,fe=null,{add_special_tokens:Pe=!0}={}){const ze=fe===null?this.single:this.pair;let Oe=[],nt=[];for(const xt of ze)"SpecialToken"in xt?Pe&&(Oe.push(xt.SpecialToken.id),nt.push(xt.SpecialToken.type_id)):"Sequence"in xt&&(xt.Sequence.id==="A"?(Oe=(0,a.mergeArrays)(Oe,W),nt=(0,a.mergeArrays)(nt,new Array(W.length).fill(xt.Sequence.type_id))):xt.Sequence.id==="B"&&(Oe=(0,a.mergeArrays)(Oe,fe),nt=(0,a.mergeArrays)(nt,new Array(fe.length).fill(xt.Sequence.type_id))));return{tokens:Oe,token_type_ids:nt}}}class we extends Ae{post_process(W,fe=null){return fe&&(W=(0,a.mergeArrays)(W,fe)),{tokens:W}}}class B extends Ae{constructor(W){super(W),this.processors=W.processors.map(fe=>Ae.fromConfig(fe))}post_process(W,fe=null,Pe={}){let ze;for(const Oe of this.processors)if(Oe instanceof we)W=Oe.post_process(W).tokens,fe&&(fe=Oe.post_process(fe).tokens);else{const nt=Oe.post_process(W,fe,Pe);W=nt.tokens,ze=nt.token_type_ids}return{tokens:W,token_type_ids:ze}}}class J extends o.Callable{constructor(W){super(),this.config=W,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=W.trim_offsets}static fromConfig(W){if(W===null)return null;switch(W.type){case"WordPiece":return new Ne(W);case"Metaspace":return new He(W);case"ByteLevel":return new ut(W);case"Replace":return new L(W);case"ByteFallback":return new ue(W);case"Fuse":return new le(W);case"Strip":return new ke(W);case"Sequence":return new Ve(W);case"CTC":return new Je(W);case"BPEDecoder":return new Z(W);default:throw new Error(`Unknown Decoder type: ${W.type}`)}}_call(W){return this.decode(W)}decode(W){return this.decode_chain(W).join("")}decode_chain(W){throw Error("`decode_chain` should be implemented in subclass.")}}class L extends J{decode_chain(W){const fe=z(this.config.pattern);return fe===null?W:W.map(Pe=>Pe.replaceAll(fe,this.config.content))}}class ue extends J{constructor(W){super(W),this.text_decoder=new TextDecoder}decode_chain(W){const fe=[];let Pe=[];for(const ze of W){let Oe=null;if(ze.length===6&&ze.startsWith("<0x")&&ze.endsWith(">")){const nt=parseInt(ze.slice(3,5),16);isNaN(nt)||(Oe=nt)}if(Oe!==null)Pe.push(Oe);else{if(Pe.length>0){const nt=this.text_decoder.decode(Uint8Array.from(Pe));fe.push(nt),Pe=[]}fe.push(ze)}}if(Pe.length>0){const ze=this.text_decoder.decode(Uint8Array.from(Pe));fe.push(ze),Pe=[]}return fe}}class le extends J{decode_chain(W){return[W.join("")]}}class ke extends J{constructor(W){super(W),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(W){return W.map(fe=>{let Pe=0;for(let Oe=0;Oe<this.start&&fe[Oe]===this.content;++Oe){Pe=Oe+1;continue}let ze=fe.length;for(let Oe=0;Oe<this.stop;++Oe){const nt=fe.length-Oe-1;if(fe[nt]===this.content){ze=nt;continue}else break}return fe.slice(Pe,ze)})}}class Ne extends J{constructor(W){super(W),this.cleanup=W.cleanup}decode_chain(W){return W.map((fe,Pe)=>(Pe!==0&&(fe.startsWith(this.config.prefix)?fe=fe.replace(this.config.prefix,""):fe=" "+fe),this.cleanup&&(fe=y(fe)),fe))}}class ut extends J{constructor(W){super(W),this.byte_decoder=Me,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(W){const fe=W.join(""),Pe=new Uint8Array([...fe].map(Oe=>this.byte_decoder[Oe]));return this.text_decoder.decode(Pe)}decode_chain(W){const fe=[];let Pe=[];for(const ze of W)this.added_tokens.find(Oe=>Oe.content===ze)!==void 0?(Pe.length>0&&(fe.push(this.convert_tokens_to_string(Pe)),Pe=[]),fe.push(ze)):Pe.push(ze);return Pe.length>0&&fe.push(this.convert_tokens_to_string(Pe)),fe}}class Je extends J{constructor(W){super(W),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(W){if(W.length===0)return"";const fe=[W[0]];for(let Oe=1;Oe<W.length;++Oe)W[Oe]!==fe.at(-1)&&fe.push(W[Oe]);let ze=fe.filter(Oe=>Oe!==this.pad_token).join("");return this.cleanup&&(ze=y(ze).replaceAll(this.word_delimiter_token," ").trim()),ze}decode_chain(W){return[this.convert_tokens_to_string(W)]}}class Ve extends J{constructor(W){super(W),this.decoders=W.decoders.map(fe=>J.fromConfig(fe))}decode_chain(W){return this.decoders.reduce((fe,Pe)=>Pe.decode_chain(fe),W)}}class Z extends J{constructor(W){super(W),this.suffix=this.config.suffix}decode_chain(W){return W.map((fe,Pe)=>fe.replaceAll(this.suffix,Pe===W.length-1?"":" "))}}class ve extends J{decode_chain(W){let fe="";for(let Pe=1;Pe<W.length;Pe+=2)fe+=W[Pe];return[fe]}}class Re extends Ge{constructor(W){super(),this.addPrefixSpace=W.add_prefix_space,this.replacement=W.replacement,this.strRep=W.str_rep||this.replacement,this.prepend_scheme=W.prepend_scheme??"always"}pre_tokenize_text(W,{section_index:fe=void 0}={}){let Pe=W.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Pe.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&fe===0)&&(Pe=this.strRep+Pe),[Pe]}}class He extends J{constructor(W){super(W),this.addPrefixSpace=W.add_prefix_space,this.replacement=W.replacement}decode_chain(W){const fe=[];for(let Pe=0;Pe<W.length;++Pe){let ze=W[Pe].replaceAll(this.replacement," ");this.addPrefixSpace&&Pe==0&&ze.startsWith(" ")&&(ze=ze.substring(1)),fe.push(ze)}return fe}}class Xe extends Q{constructor(W){super(W),this.charsmap=W.precompiled_charsmap}normalize(W){return W=W.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),W=W.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm," "),W.includes("~")?W=W.split("~").map(Pe=>Pe.normalize("NFKC")).join("~"):W=W.normalize("NFKC"),W}}class rt extends Ge{constructor(W){super(),this.tokenizers=W.pretokenizers.map(fe=>Ge.fromConfig(fe))}pre_tokenize_text(W,fe){return this.tokenizers.reduce((Pe,ze)=>ze.pre_tokenize(Pe,fe),[W])}}class ft extends Ge{constructor(W){super()}pre_tokenize_text(W,fe){return W.match(/\w+|[^\w\s]+/g)||[]}}class ht extends Ge{constructor(W){super()}pre_tokenize_text(W,fe){return N(W)}}class Mt extends Ge{constructor(W){super(),this.config=W,this.pattern=z(this.config.pattern),this.content=this.config.content}pre_tokenize_text(W,fe){return this.pattern===null?[W]:[W.replaceAll(this.pattern,this.config.content)]}}const wt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function St(Ue,W,fe,Pe){for(const ze of Object.keys(Ue)){const Oe=W-Ue[ze].length,nt=fe(ze),xt=new Array(Oe).fill(nt);Ue[ze]=Pe==="right"?(0,a.mergeArrays)(Ue[ze],xt):(0,a.mergeArrays)(xt,Ue[ze])}}function Rt(Ue,W){for(const fe of Object.keys(Ue))Ue[fe].length=W}class at extends o.Callable{constructor(fe,Pe){super();qe(this,"return_token_type_ids",!1);qe(this,"padding_side","right");this._tokenizer_config=Pe,this.normalizer=Q.fromConfig(fe.normalizer),this.pre_tokenizer=Ge.fromConfig(fe.pre_tokenizer),this.model=Ce.fromConfig(fe.model,Pe),this.post_processor=Ae.fromConfig(fe.post_processor),this.decoder=J.fromConfig(fe.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ze of fe.added_tokens){const Oe=new de(ze);this.added_tokens.push(Oe),this.model.tokens_to_ids.set(Oe.content,Oe.id),this.model.vocab[Oe.id]=Oe.content,Oe.special&&(this.special_tokens.push(Oe.content),this.all_special_ids.push(Oe.id))}if(this.additional_special_tokens=Pe.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((ze,Oe)=>Oe.content.length-ze.content.length).map(ze=>`${ze.lstrip?"\\s*":""}(${(0,a.escapeRegExp)(ze.content)})${ze.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=Pe.model_max_length,this.remove_space=Pe.remove_space,this.clean_up_tokenization_spaces=Pe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Pe.do_lowercase_and_remove_accent??!1,Pe.padding_side&&(this.padding_side=Pe.padding_side),this.legacy=!1,this.chat_template=Pe.chat_template??null,Array.isArray(this.chat_template)){const ze=Object.create(null);for(const{name:Oe,template:nt}of this.chat_template){if(typeof Oe!="string"||typeof nt!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ze[Oe]=nt}this.chat_template=ze}this._compiled_template_cache=new Map}getToken(...fe){for(const Pe of fe){const ze=this._tokenizer_config[Pe];if(ze)if(typeof ze=="object"){if(ze.__type==="AddedToken")return ze.content;throw Error(`Unknown token: ${ze}`)}else return ze}return null}static async from_pretrained(fe,{progress_callback:Pe=null,config:ze=null,cache_dir:Oe=null,local_files_only:nt=!1,revision:xt="main",legacy:kt=null}={}){const Tt=await C(fe,{progress_callback:Pe,config:ze,cache_dir:Oe,local_files_only:nt,revision:xt,legacy:kt});return new this(...Tt)}_call(fe,{text_pair:Pe=null,add_special_tokens:ze=!0,padding:Oe=!1,truncation:nt=null,max_length:xt=null,return_tensor:kt=!0,return_token_type_ids:Tt=null}={}){const At=Array.isArray(fe);let Zt;if(At){if(fe.length===0)throw Error("text array must be non-empty");if(Pe!==null){if(Array.isArray(Pe)){if(fe.length!==Pe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Zt=fe.map((rr,Gt)=>this._encode_plus(rr,{text_pair:Pe[Gt],add_special_tokens:ze,return_token_type_ids:Tt}))}else Zt=fe.map(rr=>this._encode_plus(rr,{add_special_tokens:ze,return_token_type_ids:Tt}))}else{if(fe==null)throw Error("text may not be null or undefined");if(Array.isArray(Pe))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Zt=[this._encode_plus(fe,{text_pair:Pe,add_special_tokens:ze,return_token_type_ids:Tt})]}if(xt===null?Oe==="max_length"?xt=this.model_max_length:xt=(0,f.max)(Zt.map(rr=>rr.input_ids.length))[0]:nt||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),xt=Math.min(xt,this.model_max_length??1/0),Oe||nt)for(let rr=0;rr<Zt.length;++rr)Zt[rr].input_ids.length!==xt&&(Zt[rr].input_ids.length>xt?nt&&Rt(Zt[rr],xt):Oe&&St(Zt[rr],xt,Gt=>Gt==="input_ids"?this.pad_token_id:0,this.padding_side));const Pr={};if(kt){if(!(Oe&&nt)&&Zt.some(Gt=>{var mr;for(const kn of Object.keys(Gt))if(Gt[kn].length!==((mr=Zt[0][kn])==null?void 0:mr.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const rr=[Zt.length,Zt[0].input_ids.length];for(const Gt of Object.keys(Zt[0]))Pr[Gt]=new _.Tensor("int64",BigInt64Array.from(Zt.flatMap(mr=>mr[Gt]).map(BigInt)),rr)}else{for(const rr of Object.keys(Zt[0]))Pr[rr]=Zt.map(Gt=>Gt[rr]);if(!At)for(const rr of Object.keys(Pr))Pr[rr]=Pr[rr][0]}return Pr}_encode_text(fe){return fe===null?null:(this.added_tokens_regex?fe.split(this.added_tokens_regex).filter(Oe=>Oe):[fe]).map((Oe,nt)=>{if(this.added_tokens.find(kt=>kt.content===Oe)!==void 0)return Oe;{if(this.remove_space===!0&&(Oe=Oe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Oe=I(Oe)),this.normalizer!==null&&(Oe=this.normalizer(Oe)),Oe.length===0)return[];const kt=this.pre_tokenizer!==null?this.pre_tokenizer(Oe,{section_index:nt}):[Oe];return this.model(kt)}}).flat()}_encode_plus(fe,{text_pair:Pe=null,add_special_tokens:ze=!0,return_token_type_ids:Oe=null}={}){const{tokens:nt,token_type_ids:xt}=this._tokenize_helper(fe,{pair:Pe,add_special_tokens:ze}),kt=this.model.convert_tokens_to_ids(nt),Tt={input_ids:kt,attention_mask:new Array(kt.length).fill(1)};return(Oe??this.return_token_type_ids)&&xt&&(Tt.token_type_ids=xt),Tt}_tokenize_helper(fe,{pair:Pe=null,add_special_tokens:ze=!1}={}){const Oe=this._encode_text(fe),nt=this._encode_text(Pe);return this.post_processor?this.post_processor(Oe,nt,{add_special_tokens:ze}):{tokens:(0,a.mergeArrays)(Oe??[],nt??[])}}tokenize(fe,{pair:Pe=null,add_special_tokens:ze=!1}={}){return this._tokenize_helper(fe,{pair:Pe,add_special_tokens:ze}).tokens}encode(fe,{text_pair:Pe=null,add_special_tokens:ze=!0,return_token_type_ids:Oe=null}={}){return this._encode_plus(fe,{text_pair:Pe,add_special_tokens:ze,return_token_type_ids:Oe}).input_ids}batch_decode(fe,Pe={}){return fe instanceof _.Tensor&&(fe=fe.tolist()),fe.map(ze=>this.decode(ze,Pe))}decode(fe,Pe={}){if(fe instanceof _.Tensor&&(fe=P(fe)),!Array.isArray(fe)||fe.length===0||!(0,a.isIntegralNumber)(fe[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(fe,Pe)}decode_single(fe,{skip_special_tokens:Pe=!1,clean_up_tokenization_spaces:ze=null}){let Oe=this.model.convert_ids_to_tokens(fe);Pe&&(Oe=Oe.filter(xt=>!this.special_tokens.includes(xt)));let nt=this.decoder?this.decoder(Oe):Oe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(nt=nt.replaceAll(this.decoder.end_of_word_suffix," "),Pe&&(nt=nt.trim())),(ze??this.clean_up_tokenization_spaces)&&(nt=y(nt)),nt}apply_chat_template(fe,{tools:Pe=null,documents:ze=null,chat_template:Oe=null,add_generation_prompt:nt=!1,tokenize:xt=!0,padding:kt=!1,truncation:Tt=!1,max_length:At=null,return_tensor:Zt=!0,return_dict:Pr=!1,tokenizer_kwargs:rr={},...Gt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const st=this.chat_template;if(Oe!==null&&Object.hasOwn(st,Oe))Oe=st[Oe];else if(Oe===null&&"default"in st)Oe=st.default;else if(Oe===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(st).sort()}.`)}else if(this.chat_template)Oe=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");if(typeof Oe!="string")throw Error(`chat_template must be a string, but got ${typeof Oe}`);let mr=this._compiled_template_cache.get(Oe);mr===void 0&&(mr=new g.Template(Oe),this._compiled_template_cache.set(Oe,mr));const kn=Object.create(null);for(const st of wt){const qn=this.getToken(st);qn&&(kn[st]=qn)}const pn=mr.render({messages:fe,add_generation_prompt:nt,tools:Pe,documents:ze,...kn,...Gt});if(xt){const st=this._call(pn,{add_special_tokens:!1,padding:kt,truncation:Tt,max_length:At,return_tensor:Zt,...rr});return Pr?st:st.input_ids}return pn}}class Ot extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Ut extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Kt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Qt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Jt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class qt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Er extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Qr extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Cr extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class mt extends at{}class Pt extends at{}class Bt extends at{constructor(fe,Pe){super(fe,Pe);qe(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class sn extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Li extends at{}class bi extends at{}class Nr extends at{}class mn extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Pe=>this.languageRegex.test(Pe)),this.lang_to_token=Pe=>Pe}_build_translation_inputs(W,fe,Pe){return Mi(this,W,fe,Pe)}}class Wr extends mn{}class ci extends at{}class Fr extends at{constructor(W,fe){var Oe,nt;const Pe=".,!?…。,、।۔،",ze=(nt=(Oe=W.pre_tokenizer)==null?void 0:Oe.pretokenizers[0])==null?void 0:nt.pattern;ze&&ze.Regex===` ?[^(\\s|[${Pe}])]+`&&(ze.Regex=` ?[^\\s${Pe}]+`),super(W,fe)}}const Ri="▁";class xi extends at{constructor(fe,Pe){super(fe,Pe);qe(this,"padding_side","left");this.legacy=Pe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Re({replacement:Ri,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(fe){if(fe===null)return null;if(this.legacy||fe.length===0)return super._encode_text(fe);let Pe=super._encode_text(Ri+fe.replaceAll(Ri," "));return Pe.length>1&&Pe[0]===Ri&&this.special_tokens.includes(Pe[1])&&(Pe=Pe.slice(1)),Pe}}class ks extends at{}class Oo extends at{}class Do extends at{}class Lo extends at{}class Ro extends at{}class Bi extends at{}class Ss extends at{}class co extends at{}class di extends at{}function Mi(Ue,W,fe,Pe){if(!("language_codes"in Ue)||!Array.isArray(Ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ue)||!(Ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ue)||typeof Ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ze=Pe.src_lang,Oe=Pe.tgt_lang;if(!Ue.language_codes.includes(Oe))throw new Error(`Target language code "${Oe}" is not valid. Must be one of: {${Ue.language_codes.join(", ")}}`);if(ze!==void 0){if(!Ue.language_codes.includes(ze))throw new Error(`Source language code "${ze}" is not valid. Must be one of: {${Ue.language_codes.join(", ")}}`);for(const nt of Ue.post_processor.config.single)if("SpecialToken"in nt&&Ue.languageRegex.test(nt.SpecialToken.id)){nt.SpecialToken.id=Ue.lang_to_token(ze);break}}return Pe.forced_bos_token_id=Ue.model.convert_tokens_to_ids([Ue.lang_to_token(Oe)])[0],Ue._call(W,fe)}class Ti extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Pe=>this.languageRegex.test(Pe)),this.lang_to_token=Pe=>Pe}_build_translation_inputs(W,fe,Pe){return Mi(this,W,fe,Pe)}}class Yi extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Pe=>this.languageRegex.test(Pe)).map(Pe=>Pe.slice(2,-2)),this.lang_to_token=Pe=>`__${Pe}__`}_build_translation_inputs(W,fe,Pe){return Mi(this,W,fe,Pe)}}class fo extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(W,{return_timestamps:fe=!1,return_language:Pe=!1,time_precision:ze=null,force_full_sequences:Oe=!0}={}){if(ze===null)throw Error("Must specify time_precision");let nt=null;const xt=fe==="word";function kt(){return{language:nt,timestamp:[null,null],text:""}}const Tt=[];let At=kt(),Zt=0;const Pr=this.timestamp_begin;let rr=[],Gt=[],mr=!1,kn=null;const pn=new Set(this.all_special_ids);for(const xr of W){const an=xr.tokens,$n=xt?xr.token_timestamps:null;let Yt=null,Bn=Pr;if("stride"in xr){const[kr,Ct,wr]=xr.stride;if(Zt-=Ct,kn=kr-wr,Ct&&(Bn=Ct/ze+Pr),wr)for(let zr=an.length-1;zr>=0;--zr){const Gr=Number(an[zr]);if(Gr>=Pr){if(Yt!==null&&(Gr-Pr)*ze<kn)break;Yt=Gr}}}let gn=[],Tr=[];for(let kr=0;kr<an.length;++kr){const Ct=Number(an[kr]);if(pn.has(Ct)){const wr=this.decode([Ct]),zr=M.WHISPER_LANGUAGE_MAPPING.get(wr.slice(2,-2));if(zr!==void 0){if(nt!==null&&zr!==nt&&!fe){rr.push(gn);const Gr=this.findLongestCommonSequence(rr)[0],Nn=this.decode(Gr);At.text=Nn,Tt.push(At),rr=[],gn=[],At=kt()}nt=At.language=zr}}else if(Ct>=Pr){const wr=(Ct-Pr)*ze+Zt,zr=(0,f.round)(wr,2);if(Yt!==null&&Ct>=Yt)mr=!0;else if(mr||rr.length>0&&Ct<Bn)mr=!1;else if(At.timestamp[0]===null)At.timestamp[0]=zr;else if(zr!==At.timestamp[0]){At.timestamp[1]=zr,rr.push(gn),xt&&Gt.push(Tr);const[Gr,Nn]=this.findLongestCommonSequence(rr,Gt),Dt=this.decode(Gr);At.text=Dt,xt&&(At.words=this.collateWordTimestamps(Gr,Nn,nt)),Tt.push(At),rr=[],gn=[],Gt=[],Tr=[],At=kt()}}else if(gn.push(Ct),xt){let wr=(0,f.round)($n[kr]+Zt,2),zr;if(kr+1<$n.length){zr=(0,f.round)($n[kr+1]+Zt,2);const Gr=this.decode([Ct]);D.test(Gr)&&(zr=(0,f.round)(Math.min(wr+ze,zr),2))}else zr=null;Tr.push([wr,zr])}}if("stride"in xr){const[kr,Ct,wr]=xr.stride;Zt+=kr-wr}gn.length>0?(rr.push(gn),xt&&Gt.push(Tr)):rr.every(kr=>kr.length===0)&&(At=kt(),rr=[],gn=[],Gt=[],Tr=[])}if(rr.length>0){if(Oe&&fe)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[xr,an]=this.findLongestCommonSequence(rr,Gt),$n=this.decode(xr);At.text=$n,xt&&(At.words=this.collateWordTimestamps(xr,an,nt)),Tt.push(At)}let st=Object.create(null);const qn=Tt.map(xr=>xr.text).join("");if(fe||Pe){for(let xr=0;xr<Tt.length;++xr){const an=Tt[xr];fe||delete an.timestamp,Pe||delete an.language}if(xt){const xr=[];for(const an of Tt)for(const $n of an.words)xr.push($n);st={chunks:xr}}else st={chunks:Tt}}return[qn,st]}findLongestCommonSequence(W,fe=null){let Pe=W[0],ze=Pe.length,Oe=[];const nt=Array.isArray(fe)&&fe.length>0;let xt=nt?[]:null,kt=nt?fe[0]:null;for(let Tt=1;Tt<W.length;++Tt){const At=W[Tt];let Zt=0,Pr=[ze,ze,0,0];const rr=At.length;for(let xr=1;xr<ze+rr;++xr){const an=Math.max(0,ze-xr),$n=Math.min(ze,ze+rr-xr),Yt=Pe.slice(an,$n),Bn=Math.max(0,xr-ze),gn=Math.min(rr,xr),Tr=At.slice(Bn,gn);if(Yt.length!==Tr.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let kr;nt?kr=Yt.filter((zr,Gr)=>zr===Tr[Gr]&&kt[an+Gr]<=fe[Tt][Bn+Gr]).length:kr=Yt.filter((zr,Gr)=>zr===Tr[Gr]).length;const Ct=xr/1e4,wr=kr/xr+Ct;kr>1&&wr>Zt&&(Zt=wr,Pr=[an,$n,Bn,gn])}const[Gt,mr,kn,pn]=Pr,st=Math.floor((mr+Gt)/2),qn=Math.floor((pn+kn)/2);Oe.push(...Pe.slice(0,st)),Pe=At.slice(qn),ze=Pe.length,nt&&(xt.push(...kt.slice(0,st)),kt=fe[Tt].slice(qn))}return Oe.push(...Pe),nt?(xt.push(...kt),[Oe,xt]):[Oe,[]]}collateWordTimestamps(W,fe,Pe){const[ze,Oe,nt]=this.combineTokensIntoWords(W,Pe),xt=[];for(let kt=0;kt<ze.length;++kt){const Tt=nt[kt];xt.push({text:ze[kt],timestamp:[fe[Tt.at(0)][0],fe[Tt.at(-1)][1]]})}return xt}combineTokensIntoWords(W,fe,Pe=`"'“¡¿([{-`,ze=`"'.。,,!!??::”)]}、`){fe=fe??"english";let Oe,nt,xt;return["chinese","japanese","thai","lao","myanmar"].includes(fe)?[Oe,nt,xt]=this.splitTokensOnUnicode(W):[Oe,nt,xt]=this.splitTokensOnSpaces(W),this.mergePunctuations(Oe,nt,xt,Pe,ze)}decode(W,fe){let Pe;return fe!=null&&fe.decode_with_timestamps?(W instanceof _.Tensor&&(W=P(W)),Pe=this.decodeWithTimestamps(W,fe)):Pe=super.decode(W,fe),Pe}decodeWithTimestamps(W,fe){const Pe=(fe==null?void 0:fe.time_precision)??.02,ze=Array.from(this.all_special_ids).at(-1)+1;let Oe=[[]];for(let nt of W)if(nt=Number(nt),nt>=ze){const xt=((nt-ze)*Pe).toFixed(2);Oe.push(`<|${xt}|>`),Oe.push([])}else Oe[Oe.length-1].push(nt);return Oe=Oe.map(nt=>typeof nt=="string"?nt:super.decode(nt,fe)),Oe.join("")}splitTokensOnUnicode(W){const fe=this.decode(W,{decode_with_timestamps:!0}),Pe="�",ze=[],Oe=[],nt=[];let xt=[],kt=[],Tt=0;for(let At=0;At<W.length;++At){const Zt=W[At];xt.push(Zt),kt.push(At);const Pr=this.decode(xt,{decode_with_timestamps:!0});(!Pr.includes(Pe)||fe[Tt+Pr.indexOf(Pe)]===Pe)&&(ze.push(Pr),Oe.push(xt),nt.push(kt),xt=[],kt=[],Tt+=Pr.length)}return[ze,Oe,nt]}splitTokensOnSpaces(W){const[fe,Pe,ze]=this.splitTokensOnUnicode(W),Oe=[],nt=[],xt=[],kt=new RegExp(`^[${j}]$`,"gu");for(let Tt=0;Tt<fe.length;++Tt){const At=fe[Tt],Zt=Pe[Tt],Pr=ze[Tt],rr=Zt[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),Gt=At.startsWith(" "),mr=At.trim(),kn=kt.test(mr);if(rr||Gt||kn||Oe.length===0)Oe.push(At),nt.push(Zt),xt.push(Pr);else{const pn=Oe.length-1;Oe[pn]+=At,nt[pn].push(...Zt),xt[pn].push(...Pr)}}return[Oe,nt,xt]}mergePunctuations(W,fe,Pe,ze,Oe){const nt=structuredClone(W),xt=structuredClone(fe),kt=structuredClone(Pe);let Tt=nt.length-2,At=nt.length-1;for(;Tt>=0;)nt[Tt].startsWith(" ")&&ze.includes(nt[Tt].trim())?(nt[At]=nt[Tt]+nt[At],xt[At]=(0,a.mergeArrays)(xt[Tt],xt[At]),kt[At]=(0,a.mergeArrays)(kt[Tt],kt[At]),nt[Tt]="",xt[Tt]=[],kt[Tt]=[]):At=Tt,--Tt;for(Tt=0,At=1;At<nt.length;)!nt[Tt].endsWith(" ")&&Oe.includes(nt[At])?(nt[Tt]+=nt[At],xt[Tt]=(0,a.mergeArrays)(xt[Tt],xt[At]),kt[Tt]=(0,a.mergeArrays)(kt[Tt],kt[At]),nt[At]="",xt[At]=[],kt[At]=[]):Tt=At,++At;return[nt.filter(Zt=>Zt),xt.filter(Zt=>Zt.length>0),kt.filter(Zt=>Zt.length>0)]}get_decoder_prompt_ids({language:W=null,task:fe=null,no_timestamps:Pe=!0}={}){const ze=[];if(W){const Oe=(0,M.whisper_language_to_code)(W),nt=this.model.tokens_to_ids.get(`<|${Oe}|>`);if(nt===void 0)throw new Error(`Unable to find language "${Oe}" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);ze.push(nt)}else ze.push(null);if(fe){if(fe=fe.toLowerCase(),fe!=="transcribe"&&fe!=="translate")throw new Error(`Task "${fe}" is not supported. Must be one of: ["transcribe", "translate"]`);const Oe=this.model.tokens_to_ids.get(`<|${fe}|>`);if(Oe===void 0)throw new Error(`Unable to find task "${fe}" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);ze.push(Oe)}else ze.push(null);if(Pe){const Oe=this.model.tokens_to_ids.get("<|notimestamps|>");if(Oe===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);ze.push(Oe)}return ze.map((Oe,nt)=>[nt+1,Oe]).filter(Oe=>Oe[1]!==null)}}class po extends at{}class Xt extends at{}class Zi extends at{}class Bo extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Pe=>this.languageRegex.test(Pe)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(W){if(W===null)return null;const[fe,...Pe]=W.trim().split(this.languageRegex);if(Pe.length===0)return super._encode_text(fe);if(Pe.length===2){const[ze,Oe]=Pe;return this.supported_language_codes.includes(ze)||console.warn(`Unsupported language code "${ze}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,a.mergeArrays)([ze],super._encode_text(Oe))}}}class No extends at{}class ho extends at{}class jo extends at{}class Uo extends at{}class mo extends at{}class Vo extends at{constructor(W,fe){super(W,fe),this.decoder=new ve({})}}class Br extends at{}class Rn{static async from_pretrained(W,{progress_callback:fe=null,config:Pe=null,cache_dir:ze=null,local_files_only:Oe=!1,revision:nt="main",legacy:xt=null}={}){var Pr;const[kt,Tt]=await C(W,{progress_callback:fe,config:Pe,cache_dir:ze,local_files_only:Oe,revision:nt,legacy:xt}),At=((Pr=Tt.tokenizer_class)==null?void 0:Pr.replace(/Fast$/,""))??"PreTrainedTokenizer";let Zt=this.TOKENIZER_CLASS_MAPPING[At];return Zt||(console.warn(`Unknown tokenizer class "${At}", attempting to construct from base class.`),Zt=at),new Zt(kt,Tt)}}qe(Rn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Li,DistilBertTokenizer:mt,CamembertTokenizer:Pt,DebertaTokenizer:Jt,DebertaV2Tokenizer:qt,BertTokenizer:Ot,HerbertTokenizer:Er,ConvBertTokenizer:Qr,RoFormerTokenizer:Cr,XLMTokenizer:Bt,ElectraTokenizer:sn,MobileBertTokenizer:Kt,SqueezeBertTokenizer:Qt,AlbertTokenizer:Ut,GPT2Tokenizer:bi,BartTokenizer:Nr,MBartTokenizer:mn,MBart50Tokenizer:Wr,RobertaTokenizer:ci,WhisperTokenizer:fo,CodeGenTokenizer:po,CLIPTokenizer:Xt,SiglipTokenizer:Zi,MarianTokenizer:Bo,BloomTokenizer:Fr,NllbTokenizer:Ti,M2M100Tokenizer:Yi,LlamaTokenizer:xi,CodeLlamaTokenizer:ks,XLMRobertaTokenizer:Oo,MPNetTokenizer:Do,FalconTokenizer:Lo,GPTNeoXTokenizer:Ro,EsmTokenizer:Bi,Wav2Vec2CTCTokenizer:No,BlenderbotTokenizer:ho,BlenderbotSmallTokenizer:jo,SpeechT5Tokenizer:Uo,NougatTokenizer:mo,VitsTokenizer:Vo,Qwen2Tokenizer:Ss,GemmaTokenizer:co,Grok1Tokenizer:di,CohereTokenizer:Br,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,t,n)=>{n.r(t),n.d(t,{hamming:()=>M,hanning:()=>g,mel_filter_bank:()=>y,read_audio:()=>_,spectrogram:()=>N,window_function:()=>j});var o=n("./src/utils/hub.js"),a=n("./src/utils/maths.js"),l=n("./src/utils/core.js"),f=n("./src/utils/tensor.js");async function _(D,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const de=await(await(0,o.getFile)(D)).arrayBuffer(),Ce=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const ee=await Ce.decodeAudioData(de);let ye;if(ee.numberOfChannels===2){const R=Math.sqrt(2),Me=ee.getChannelData(0),Qe=ee.getChannelData(1);ye=new Float32Array(Me.length);for(let ge=0;ge<ee.length;++ge)ye[ge]=R*(Me[ge]+Qe[ge])/2}else ye=ee.getChannelData(0);return ye}function h(D,Y){if(D<1)return new Float64Array;if(D===1)return new Float64Array([1]);const de=1-Y,Ce=2*Math.PI/(D-1),ee=new Float64Array(D);for(let ye=0;ye<D;++ye)ee[ye]=Y-de*Math.cos(ye*Ce);return ee}function g(D){return h(D,.5)}function M(D){return h(D,.54)}const w={htk:D=>2595*Math.log10(1+D/700),kaldi:D=>1127*Math.log(1+D/700),slaney:(D,Y=1e3,de=15,Ce=27/Math.log(6.4))=>D>=Y?de+Math.log(D/Y)*Ce:3*D/200};function C(D,Y="htk"){const de=w[Y];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof D=="number"?de(D):D.map(Ce=>de(Ce))}const k={htk:D=>700*(10**(D/2595)-1),kaldi:D=>700*(Math.exp(D/1127)-1),slaney:(D,Y=1e3,de=15,Ce=Math.log(6.4)/27)=>D>=de?Y*Math.exp(Ce*(D-de)):200*D/3};function z(D,Y="htk"){const de=k[Y];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof D=="number"?de(D):D.map(Ce=>de(Ce))}function S(D,Y){const de=Float64Array.from({length:Y.length-1},(R,Me)=>Y[Me+1]-Y[Me]),Ce=Array.from({length:D.length},()=>new Array(Y.length));for(let R=0;R<D.length;++R){const Me=Ce[R];for(let Qe=0;Qe<Y.length;++Qe)Me[Qe]=Y[Qe]-D[R]}const ee=Y.length-2,ye=Array.from({length:ee},()=>new Array(D.length));for(let R=0;R<D.length;++R){const Me=Ce[R];for(let Qe=0;Qe<ee;++Qe){const ge=-Me[Qe]/de[Qe],Q=Me[Qe+2]/de[Qe+1];ye[Qe][R]=Math.max(0,Math.min(ge,Q))}}return ye}function P(D,Y,de){const Ce=(Y-D)/(de-1);return Float64Array.from({length:de},(ee,ye)=>D+Ce*ye)}function y(D,Y,de,Ce,ee,ye=null,R="htk",Me=!1){if(ye!==null&&ye!=="slaney")throw new Error('norm must be one of null or "slaney"');const Qe=C(de,R),ge=C(Ce,R),Q=P(Qe,ge,Y+2);let ae=z(Q,R),Se;if(Me){const me=ee/(D*2);Se=C(Float64Array.from({length:D},(Ke,De)=>De*me),R),ae=Q}else Se=P(0,Math.floor(ee/2),D);const X=S(Se,ae);if(ye!==null&&ye==="slaney")for(let me=0;me<Y;++me){const Ke=X[me],De=2/(ae[me+2]-ae[me]);for(let Be=0;Be<D;++Be)Ke[Be]*=De}return X}function x(D,Y,de){const Ce=new D.constructor(D.length+Y+de),ee=D.length-1;for(let ye=0;ye<D.length;++ye)Ce[Y+ye]=D[ye];for(let ye=1;ye<=Y;++ye)Ce[Y-ye]=D[(0,l.calculateReflectOffset)(ye,ee)];for(let ye=1;ye<=de;++ye)Ce[ee+Y+ye]=D[(0,l.calculateReflectOffset)(ee-ye,ee)];return Ce}function I(D,Y,de,Ce,ee){if(de<=0)throw new Error("reference must be greater than zero");if(Ce<=0)throw new Error("min_value must be greater than zero");de=Math.max(Ce,de);const ye=Math.log10(de);for(let R=0;R<D.length;++R)D[R]=Y*Math.log10(Math.max(Ce,D[R])-ye);if(ee!==null){if(ee<=0)throw new Error("db_range must be greater than zero");const R=(0,a.max)(D)[0]-ee;for(let Me=0;Me<D.length;++Me)D[Me]=Math.max(D[Me],R)}return D}function U(D,Y=1,de=1e-5,Ce=null){return I(D,20,Y,de,Ce)}function O(D,Y=1,de=1e-10,Ce=null){return I(D,10,Y,de,Ce)}async function N(D,Y,de,Ce,{fft_length:ee=null,power:ye=1,center:R=!0,pad_mode:Me="reflect",onesided:Qe=!0,preemphasis:ge=null,mel_filters:Q=null,mel_floor:ae=1e-10,log_mel:Se=null,reference:X=1,min_value:me=1e-10,db_range:Ke=null,remove_dc_offset:De=null,min_num_frames:Be=null,max_num_frames:We=null,do_pad:ot=!0,transpose:dt=!1}={}){const Ge=Y.length;if(ee===null&&(ee=de),de>ee)throw Error(`frame_length (${de}) may not be larger than fft_length (${ee})`);if(Ge!==de)throw new Error(`Length of the window (${Ge}) must equal frame_length (${de})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(ye===null&&Q!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(R){if(Me!=="reflect")throw new Error(`pad_mode="${Me}" not implemented yet.`);const J=Math.floor((ee-1)/2)+1;D=x(D,J,J)}let Te=Math.floor(1+Math.floor((D.length-de)/Ce));Be!==null&&Te<Be&&(Te=Be);const je=Qe?Math.floor(ee/2)+1:ee;let Ye=Te,tt=Te;We!==null&&(We>Te?ot&&(tt=We):tt=Ye=We);const A=new a.FFT(ee),Ae=new Float64Array(ee),$e=new Float64Array(A.outputBufferSize),se=new Float32Array(je*tt);for(let J=0;J<Ye;++J){const L=J*Ce,ue=Math.min(D.length-L,de);ue!==de&&Ae.fill(0,0,de);for(let le=0;le<ue;++le)Ae[le]=D[L+le];if(De){let le=0;for(let Ne=0;Ne<ue;++Ne)le+=Ae[Ne];const ke=le/ue;for(let Ne=0;Ne<ue;++Ne)Ae[Ne]-=ke}if(ge!==null){for(let le=ue-1;le>=1;--le)Ae[le]-=ge*Ae[le-1];Ae[0]*=1-ge}for(let le=0;le<Y.length;++le)Ae[le]*=Y[le];A.realTransform($e,Ae);for(let le=0;le<je;++le){const ke=le<<1;se[le*tt+J]=$e[ke]**2+$e[ke+1]**2}}if(ye!==null&&ye!==2){const J=2/ye;for(let L=0;L<se.length;++L)se[L]**=J}const te=Q.length;let we=await(0,f.matmul)(new f.Tensor("float32",Q.flat(),[te,je]),new f.Tensor("float32",se,[je,tt]));dt&&(we=we.transpose(1,0));const B=we.data;for(let J=0;J<B.length;++J)B[J]=Math.max(ae,B[J]);if(ye!==null&&Se!==null){const J=Math.min(B.length,Ye*te);switch(Se){case"log":for(let L=0;L<J;++L)B[L]=Math.log(B[L]);break;case"log10":for(let L=0;L<J;++L)B[L]=Math.log10(B[L]);break;case"dB":if(ye===1)U(B,X,me,Ke);else if(ye===2)O(B,X,me,Ke);else throw new Error(`Cannot use log_mel option '${Se}' with power ${ye}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${Se}'`)}}return we}function j(D,Y,{periodic:de=!0,frame_length:Ce=null,center:ee=!0}={}){const ye=de?D+1:D;let R;switch(Y){case"boxcar":R=new Float64Array(ye).fill(1);break;case"hann":case"hann_window":R=g(ye);break;case"hamming":R=M(ye);break;case"povey":R=g(ye).map(Me=>Math.pow(Me,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(de&&(R=R.subarray(0,D)),Ce===null)return R;if(D>Ce)throw new Error(`Length of the window (${D}) may not be larger than frame_length (${Ce})`);return R}},"./src/utils/constants.js":(e,t,n)=>{n.r(t),n.d(t,{GITHUB_ISSUE_URL:()=>o});const o="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(e,t,n)=>{n.r(t),n.d(t,{calculateDimensions:()=>h,calculateReflectOffset:()=>C,dispatchCallback:()=>o,escapeRegExp:()=>l,isIntegralNumber:()=>_,isTypedArray:()=>f,mergeArrays:()=>M,pick:()=>k,pop:()=>g,product:()=>w,reverseDictionary:()=>a});function o(z,S){z&&z(S)}function a(z){return Object.fromEntries(Object.entries(z).map(([S,P])=>[P,S]))}function l(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(z){var S,P,y;return((y=(P=(S=z==null?void 0:z.prototype)==null?void 0:S.__proto__)==null?void 0:P.constructor)==null?void 0:y.name)==="TypedArray"}function _(z){return Number.isInteger(z)||typeof z=="bigint"}function h(z){const S=[];let P=z;for(;Array.isArray(P);)S.push(P.length),P=P[0];return S}function g(z,S,P=void 0){const y=z[S];if(y!==void 0)return delete z[S],y;if(P===void 0)throw Error(`Key ${S} does not exist in object.`);return P}function M(...z){return Array.prototype.concat.apply([],z)}function w(...z){return z.reduce((S,P)=>S.flatMap(y=>P.map(x=>[y,x])))}function C(z,S){return Math.abs((z+S)%(2*S)-S)}function k(z,S){return Object.assign({},...S.map(P=>{if(z[P]!==void 0)return{[P]:z[P]}}))}},"./src/utils/data-structures.js":(e,t,n)=>{n.r(t),n.d(t,{CharTrie:()=>a,PriorityQueue:()=>o,TokenLattice:()=>f});class o{constructor(g=(w,C)=>w>C,M=1/0){this._heap=[],this._comparator=g,this._maxSize=M}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...g){return this.extend(g)}extend(g){for(const M of g)if(this.size<this._maxSize)this._heap.push(M),this._siftUp();else{const w=this._smallest();this._comparator(M,this._heap[w])&&(this._heap[w]=M,this._siftUpFrom(w))}return this.size}pop(){const g=this.peek(),M=this.size-1;return M>0&&this._swap(0,M),this._heap.pop(),this._siftDown(),g}replace(g){const M=this.peek();return this._heap[0]=g,this._siftDown(),M}_parent(g){return(g+1>>>1)-1}_left(g){return(g<<1)+1}_right(g){return g+1<<1}_greater(g,M){return this._comparator(this._heap[g],this._heap[M])}_swap(g,M){const w=this._heap[g];this._heap[g]=this._heap[M],this._heap[M]=w}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(g){for(;g>0&&this._greater(g,this._parent(g));)this._swap(g,this._parent(g)),g=this._parent(g)}_siftDown(){let g=0;for(;this._left(g)<this.size&&this._greater(this._left(g),g)||this._right(g)<this.size&&this._greater(this._right(g),g);){const M=this._right(g)<this.size&&this._greater(this._right(g),this._left(g))?this._right(g):this._left(g);this._swap(g,M),g=M}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}}class a{constructor(){this.root=l.default()}extend(g){for(let M of g)this.push(M)}push(g){let M=this.root;for(let w of g){let C=M.children.get(w);C===void 0&&(C=l.default(),M.children.set(w,C)),M=C}M.isLeaf=!0}*commonPrefixSearch(g){let M=this.root,w="";for(let C=0;C<g.length&&M!==void 0;++C){const k=g[C];w+=k,M=M.children.get(k),M!==void 0&&M.isLeaf&&(yield w)}}}class l{constructor(g,M){this.isLeaf=g,this.children=M}static default(){return new l(!1,new Map)}}class f{constructor(g,M,w){this.sentence=g,this.len=g.length,this.bosTokenId=M,this.eosTokenId=w,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},()=>[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const C=new _(this.bosTokenId,0,0,0,0),k=new _(this.eosTokenId,1,this.len,0,0);this.nodes.push(C.clone()),this.nodes.push(k.clone()),this.beginNodes[this.len].push(k),this.endNodes[0].push(C)}insert(g,M,w,C){const k=this.nodes.length,z=new _(C,k,g,M,w);this.beginNodes[g].push(z),this.endNodes[g+M].push(z),this.nodes.push(z)}viterbi(){const g=this.len;let M=0;for(;M<=g;){if(this.beginNodes[M].length==0)return[];for(let S of this.beginNodes[M]){S.prev=null;let P=0,y=null;for(let x of this.endNodes[M]){const I=x.backtraceScore+S.score;(y===null||I>P)&&(y=x.clone(),P=I)}if(y!==null)S.prev=y,S.backtraceScore=P;else return[]}++M}const w=[],k=this.beginNodes[g][0].prev;if(k===null)return[];let z=k.clone();for(;z.prev!==null;)w.push(z.clone()),z=z.clone().prev.clone();return w.reverse(),w}piece(g){return this.sentence.slice(g.pos,g.pos+g.length)}tokens(){return this.viterbi().map(M=>this.piece(M))}tokenIds(){return this.viterbi().map(M=>M.tokenId)}}class _{constructor(g,M,w,C,k){this.tokenId=g,this.nodeId=M,this.pos=w,this.length=C,this.score=k,this.prev=null,this.backtraceScore=0}clone(){const g=new _(this.tokenId,this.nodeId,this.pos,this.length,this.score);return g.prev=this.prev,g.backtraceScore=this.backtraceScore,g}}},"./src/utils/devices.js":(e,t,n)=>{n.r(t),n.d(t,{DEVICE_TYPES:()=>o});const o=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,t,n)=>{n.r(t),n.d(t,{DATA_TYPES:()=>f,DEFAULT_DEVICE_DTYPE_MAPPING:()=>_,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>h,isWebGpuFp16Supported:()=>l});var o=n("./src/env.js"),a=n("./src/utils/devices.js");const l=function(){let g;return async function(){if(g===void 0)if(!o.apis.IS_WEBGPU_AVAILABLE)g=!1;else try{g=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{g=!1}return g}}(),f=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_=Object.freeze({[a.DEVICE_TYPES.wasm]:f.q8}),h=Object.freeze({[f.fp32]:"",[f.fp16]:"_fp16",[f.int8]:"_int8",[f.uint8]:"_uint8",[f.q8]:"_quantized",[f.q4]:"_q4",[f.q4f16]:"_q4f16",[f.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,n)=>{n.r(t),n.d(t,{Callable:()=>o});const o=class{constructor(){let a=function(...l){return a._call(...l)};return Object.setPrototypeOf(a,new.target.prototype)}_call(...a){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,t,n)=>{n.r(t),n.d(t,{getFile:()=>M,getModelFile:()=>S,getModelJSON:()=>P});var o=n("?7a2c"),a=n("?a42a"),l=n("./src/env.js"),f=n("./src/utils/core.js");const _={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class h{constructor(U){if(this.filePath=U,this.headers=new Headers,this.exists=o.existsSync(U),this.exists){this.status=200,this.statusText="OK";let O=o.statSync(U);this.headers.set("content-length",O.size.toString()),this.updateContentType();let N=this;this.body=new ReadableStream({start(j){N.arrayBuffer().then(D=>{j.enqueue(new Uint8Array(D)),j.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const U=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",_[U]??"application/octet-stream")}clone(){let U=new h(this.filePath);return U.exists=this.exists,U.status=this.status,U.statusText=this.statusText,U.headers=new Headers(this.headers),U}async arrayBuffer(){return(await o.promises.readFile(this.filePath)).buffer}async blob(){const U=await o.promises.readFile(this.filePath);return new Blob([U],{type:this.headers.get("content-type")})}async text(){return await o.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function g(I,U=null,O=null){let N;try{N=new URL(I)}catch{return!1}return!(U&&!U.includes(N.protocol)||O&&!O.includes(N.hostname))}async function M(I){var U;if(l.env.useFS&&!g(I,["http:","https:","blob:"]))return new h(I);if(typeof process<"u"&&((U=process==null?void 0:process.release)==null?void 0:U.name)==="node"){const O=!!(Mo!=null&&Mo.TESTING_REMOTELY),N=l.env.version,j=new Headers;if(j.set("User-Agent",`transformers.js/${N}; is_ci/${O};`),g(I,["http:","https:"],["huggingface.co","hf.co"])){const Y=(Mo==null?void 0:Mo.HF_TOKEN)??(Mo==null?void 0:Mo.HF_ACCESS_TOKEN);Y&&j.set("Authorization",`Bearer ${Y}`)}return fetch(I,{headers:j})}else return fetch(I)}const w={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function C(I,U,O){if(!O)return null;const N=w[I]??`Error (${I}) occurred while trying to load file`;throw Error(`${N}: "${U}".`)}class k{constructor(U){this.path=U}async match(U){let O=a.join(this.path,U),N=new h(O);if(N.exists)return N}async put(U,O){const N=Buffer.from(await O.arrayBuffer());let j=a.join(this.path,U);try{await o.promises.mkdir(a.dirname(j),{recursive:!0}),await o.promises.writeFile(j,N)}catch(D){console.warn("An error occurred while writing the file to cache:",D)}}}async function z(I,...U){for(let O of U)try{let N=await I.match(O);if(N)return N}catch{continue}}async function S(I,U,O=!0,N={}){if(!l.env.allowLocalModels){if(N.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!l.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,f.dispatchCallback)(N.progress_callback,{status:"initiate",name:I,file:U});let j;if(!j&&l.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{j=await caches.open("transformers-cache")}catch(Se){console.warn("An error occurred while opening the browser cache:",Se)}}if(!j&&l.env.useFSCache&&(j=new k(N.cache_dir??l.env.cacheDir)),!j&&l.env.useCustomCache){if(!l.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!l.env.customCache.match||!l.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");j=l.env.customCache}const D=N.revision??"main";let Y=x(I,U),de=x(l.env.localModelPath,Y),Ce=x(l.env.remoteHost,l.env.remotePathTemplate.replaceAll("{model}",I).replaceAll("{revision}",encodeURIComponent(D)),U),ee=D==="main"?Y:x(I,D,U),ye,R=j instanceof k?ee:Ce,Me=!1,Qe;j&&(Qe=await z(j,de,R));const ge=Qe!==void 0;if(Qe===void 0){if(l.env.allowLocalModels)if(g(Y,["http:","https:"])){if(N.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);if(!l.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}else try{Qe=await M(de),ye=de}catch(X){console.warn(`Unable to load from local path "${de}": "${X}"`)}if(Qe===void 0||Qe.status===404){if(N.local_files_only||!l.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${de}".`);return null}if(Qe=await M(Ce),Qe.status!==200)return C(Qe.status,Ce,O);ye=R}Me=j&&typeof Response<"u"&&Qe instanceof Response&&Qe.status===200}(0,f.dispatchCallback)(N.progress_callback,{status:"download",name:I,file:U});const Q={status:"progress",name:I,file:U};let ae;return N.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ae=new Uint8Array(await Qe.arrayBuffer()),(0,f.dispatchCallback)(N.progress_callback,{...Q,progress:100,loaded:ae.length,total:ae.length})):ae=await y(Qe,Se=>{(0,f.dispatchCallback)(N.progress_callback,{...Q,...Se})}):ae=new Uint8Array(await Qe.arrayBuffer()),Me&&ye&&await j.match(ye)===void 0&&await j.put(ye,new Response(ae,{headers:Qe.headers})).catch(Se=>{console.warn(`Unable to add response to browser cache: ${Se}.`)}),(0,f.dispatchCallback)(N.progress_callback,{status:"done",name:I,file:U}),ae}async function P(I,U,O=!0,N={}){let j=await S(I,U,O,N);if(j===null)return{};let Y=new TextDecoder("utf-8").decode(j);return JSON.parse(Y)}async function y(I,U){const O=I.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let N=parseInt(O??"0"),j=new Uint8Array(N),D=0;const Y=I.body.getReader();async function de(){const{done:Ce,value:ee}=await Y.read();if(Ce)return;let ye=D+ee.length;if(ye>N){N=ye;let Me=new Uint8Array(N);Me.set(j),j=Me}j.set(ee,D),D=ye;const R=D/N*100;return U({progress:R,loaded:D,total:N}),de()}return await de(),j}function x(...I){return I=I.map((U,O)=>(O&&(U=U.replace(new RegExp("^/"),"")),O!==I.length-1&&(U=U.replace(new RegExp("/$"),"")),U)),I.join("/")}},"./src/utils/image.js":(e,t,n)=>{n.r(t),n.d(t,{RawImage:()=>z});var o=n("./src/utils/hub.js"),a=n("./src/env.js"),l=n("./src/utils/tensor.js"),f=n("?2b25");const _=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope";let g,M,w;if(_)g=(S,P)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(S,P)},w=self.createImageBitmap,M=self.ImageData;else if(f)w=async S=>{const y=(await S.metadata()).channels,{data:x,info:I}=await S.rotate().raw().toBuffer({resolveWithObject:!0}),U=new z(new Uint8ClampedArray(x),I.width,I.height,I.channels);return y!==void 0&&y!==I.channels&&U.convert(y),U};else throw new Error("Unable to load image processing library.");const C={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},k=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class z{constructor(P,y,x,I){this.data=P,this.width=y,this.height=x,this.channels=I}get size(){return[this.width,this.height]}static async read(P){if(P instanceof z)return P;if(typeof P=="string"||P instanceof URL)return await this.fromURL(P);throw new Error(`Unsupported input type: ${typeof P}`)}static fromCanvas(P){if(!_)throw new Error("fromCanvas() is only supported in browser environments.");const x=P.getContext("2d").getImageData(0,0,P.width,P.height).data;return new z(x,P.width,P.height,4)}static async fromURL(P){const y=await(0,o.getFile)(P);if(y.status!==200)throw new Error(`Unable to read image from "${P}" (${y.status} ${y.statusText})`);const x=await y.blob();return this.fromBlob(x)}static async fromBlob(P){if(_){const y=await w(P),x=g(y.width,y.height).getContext("2d");return x.drawImage(y,0,0),new this(x.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=f(await P.arrayBuffer());return await w(y)}}static fromTensor(P,y="CHW"){if(P.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${P.dims.length} dimensions.`);if(y==="CHW")P=P.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(P.data instanceof Uint8ClampedArray||P.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${P.type}`);switch(P.dims[2]){case 1:case 2:case 3:case 4:return new z(P.data,P.dims[1],P.dims[0],P.dims[2]);default:throw new Error(`Unsupported number of channels: ${P.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const P=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,x=0;y<this.data.length;y+=this.channels){const I=this.data[y],U=this.data[y+1],O=this.data[y+2];P[x++]=Math.round(.2989*I+.587*U+.114*O)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(P,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const P=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let y=0,x=0;y<this.data.length;++y)P[x++]=this.data[y],P[x++]=this.data[y],P[x++]=this.data[y];break;case 4:for(let y=0,x=0;y<this.data.length;y+=4)P[x++]=this.data[y],P[x++]=this.data[y+1],P[x++]=this.data[y+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(P,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const P=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let y=0,x=0;y<this.data.length;++y)P[x++]=this.data[y],P[x++]=this.data[y],P[x++]=this.data[y],P[x++]=255;break;case 3:for(let y=0,x=0;y<this.data.length;y+=3)P[x++]=this.data[y],P[x++]=this.data[y+1],P[x++]=this.data[y+2],P[x++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(P,this.width,this.height,4)}async resize(P,y,{resample:x=2}={}){let I=C[x]??x;if(_){const U=this.channels,O=this.toCanvas(),N=g(P,y).getContext("2d");return N.drawImage(O,0,0,P,y),new z(N.getImageData(0,0,P,y).data,P,y,4).convert(U)}else{let U=this.toSharp();switch(I){case"box":case"hamming":(I==="box"||I==="hamming")&&(console.warn(`Resampling method ${I} is not yet supported. Using bilinear instead.`),I="bilinear");case"nearest":case"bilinear":case"bicubic":U=U.affine([P/this.width,0,0,y/this.height],{interpolator:I});break;case"lanczos":U=U.resize({width:P,height:y,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${I} is not supported.`)}return await w(U)}}async pad([P,y,x,I]){if(P=Math.max(P,0),y=Math.max(y,0),x=Math.max(x,0),I=Math.max(I,0),P===0&&y===0&&x===0&&I===0)return this;if(_){const U=this.channels,O=this.toCanvas(),N=this.width+P+y,j=this.height+x+I,D=g(N,j).getContext("2d");return D.drawImage(O,0,0,this.width,this.height,P,x,N,j),new z(D.getImageData(0,0,N,j).data,N,j,4).convert(U)}else{const U=this.toSharp().extend({left:P,right:y,top:x,bottom:I});return await w(U)}}async crop([P,y,x,I]){if(P=Math.max(P,0),y=Math.max(y,0),x=Math.min(x,this.width-1),I=Math.min(I,this.height-1),P===0&&y===0&&x===this.width-1&&I===this.height-1)return this;const U=x-P+1,O=I-y+1;if(_){const N=this.channels,j=this.toCanvas(),D=g(U,O).getContext("2d");return D.drawImage(j,P,y,U,O,0,0,U,O),new z(D.getImageData(0,0,U,O).data,U,O,4).convert(N)}else{const N=this.toSharp().extract({left:P,top:y,width:U,height:O});return await w(N)}}async center_crop(P,y){if(this.width===P&&this.height===y)return this;const x=(this.width-P)/2,I=(this.height-y)/2;if(_){const U=this.channels,O=this.toCanvas(),N=g(P,y).getContext("2d");let j=0,D=0,Y=0,de=0;return x>=0?j=x:Y=-x,I>=0?D=I:de=-I,N.drawImage(O,j,D,P,y,Y,de,P,y),new z(N.getImageData(0,0,P,y).data,P,y,4).convert(U)}else{let U=this.toSharp();if(x>=0&&I>=0)U=U.extract({left:Math.floor(x),top:Math.floor(I),width:P,height:y});else if(x<=0&&I<=0){const O=Math.floor(-I),N=Math.floor(-x);U=U.extend({top:O,left:N,right:P-this.width-N,bottom:y-this.height-O})}else{let O=[0,0],N=0;I<0?(O[0]=Math.floor(-I),O[1]=y-this.height-O[0]):N=Math.floor(I);let j=[0,0],D=0;x<0?(j[0]=Math.floor(-x),j[1]=P-this.width-j[0]):D=Math.floor(x),U=U.extend({top:O[0],bottom:O[1],left:j[0],right:j[1]}).extract({left:D,top:N,width:P,height:y})}return await w(U)}}async toBlob(P="image/png",y=1){if(!_)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:P,quality:y})}toTensor(P="CHW"){let y=new l.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(P!=="HWC")if(P==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${P}`);return y}toCanvas(){if(!_)throw new Error("toCanvas() is only supported in browser environments.");const P=this.clone().rgba(),y=g(P.width,P.height),x=new M(P.data,P.width,P.height);return y.getContext("2d").putImageData(x,0,0),y}_update(P,y,x,I=null){return this.data=P,this.width=y,this.height=x,I!==null&&(this.channels=I),this}clone(){return new z(this.data.slice(),this.width,this.height,this.channels)}convert(P){if(this.channels===P)return this;switch(P){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(P){if(_){if(h)throw new Error("Unable to save an image from a Web Worker.");const y=P.split(".").pop().toLowerCase(),x=k.get(y)??"image/png",I=await this.toBlob(x),U=URL.createObjectURL(I),O=document.createElement("a");O.href=U,O.download=P,O.click(),O.remove()}else{if(a.env.useFS)return await this.toSharp().toFile(P);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(_)throw new Error("toSharp() is only supported in server-side environments.");return f(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,t,n)=>{n.r(t),n.d(t,{FFT:()=>S,bankers_round:()=>x,cos_sim:()=>h,dot:()=>_,dynamic_time_warping:()=>I,interpolate_data:()=>o,log_softmax:()=>f,magnitude:()=>g,max:()=>w,medianFilter:()=>P,min:()=>M,permute_data:()=>a,round:()=>y,softmax:()=>l});function o(U,[O,N,j],[D,Y],de="bilinear",Ce=!1){const ee=Y/j,ye=D/N,R=new U.constructor(D*Y*O),Me=N*j,Qe=D*Y;for(let ge=0;ge<D;++ge)for(let Q=0;Q<Y;++Q){const ae=ge*Y+Q,Se=(Q+.5)/ee-.5,X=(ge+.5)/ye-.5;let me=Math.floor(Se),Ke=Math.floor(X);const De=Math.min(me+1,j-1),Be=Math.min(Ke+1,N-1);me=Math.max(me,0),Ke=Math.max(Ke,0);const We=Se-me,ot=X-Ke,dt=(1-We)*(1-ot),Ge=We*(1-ot),Te=(1-We)*ot,je=We*ot,Ye=Ke*j,tt=Be*j,A=Ye+me,Ae=Ye+De,$e=tt+me,se=tt+De;for(let te=0;te<O;++te){const we=te*Me;R[te*Qe+ae]=dt*U[we+A]+Ge*U[we+Ae]+Te*U[we+$e]+je*U[we+se]}}return R}function a(U,O,N){const j=new Array(N.length),D=new Array(N.length);for(let Ce=N.length-1,ee=1;Ce>=0;--Ce)D[Ce]=ee,j[Ce]=O[N[Ce]],ee*=j[Ce];const Y=N.map((Ce,ee)=>D[N.indexOf(ee)]),de=new U.constructor(U.length);for(let Ce=0;Ce<U.length;++Ce){let ee=0;for(let ye=O.length-1,R=Ce;ye>=0;--ye)ee+=R%O[ye]*Y[ye],R=Math.floor(R/O[ye]);de[ee]=U[Ce]}return[de,j]}function l(U){const O=w(U)[0],N=U.map(Y=>Math.exp(Y-O)),j=N.reduce((Y,de)=>Y+de,0);return N.map(Y=>Y/j)}function f(U){return l(U).map(j=>Math.log(j))}function _(U,O){let N=0;for(let j=0;j<U.length;++j)N+=U[j]*O[j];return N}function h(U,O){const N=_(U,O),j=g(U),D=g(O);return N/(j*D)}function g(U){return Math.sqrt(U.reduce((O,N)=>O+N*N,0))}function M(U){if(U.length===0)throw Error("Array must not be empty");let O=U[0],N=0;for(let j=1;j<U.length;++j)U[j]<O&&(O=U[j],N=j);return[O,N]}function w(U){if(U.length===0)throw Error("Array must not be empty");let O=U[0],N=0;for(let j=1;j<U.length;++j)U[j]>O&&(O=U[j],N=j);return[Number(O),N]}function C(U){return U>0&&(U&U-1)===0}class k{constructor(O){if(this.size=O|0,this.size<=1||!C(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=O<<1,this.table=new Float64Array(this.size*2);for(let j=0;j<this.table.length;j+=2){const D=Math.PI*j/this.size;this.table[j]=Math.cos(D),this.table[j+1]=-Math.sin(D)}let N=0;for(let j=1;this.size>j;j<<=1)++N;this._width=N%2===0?N-1:N,this._bitrev=new Int32Array(1<<this._width);for(let j=0;j<this._bitrev.length;++j){this._bitrev[j]=0;for(let D=0;D<this._width;D+=2){const Y=this._width-D-2;this._bitrev[j]|=(j>>>D&3)<<Y}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(O,N){const j=N||new Array(O.length>>>1);for(let D=0;D<O.length;D+=2)j[D>>>1]=O[D];return j}toComplexArray(O,N){const j=N||this.createComplexArray();for(let D=0;D<j.length;D+=2)j[D]=O[D>>>1],j[D+1]=0;return j}transform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._transform4(O,N,1)}realTransform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._realTransform4(O,N,1)}inverseTransform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._transform4(O,N,-1);for(let j=0;j<O.length;++j)O[j]/=this.size}_transform4(O,N,j){const D=this._csize;let de=1<<this._width,Ce=D/de<<1,ee,ye;const R=this._bitrev;if(Ce===4)for(ee=0,ye=0;ee<D;ee+=Ce,++ye){const Qe=R[ye];this._singleTransform2(N,O,ee,Qe,de)}else for(ee=0,ye=0;ee<D;ee+=Ce,++ye){const Qe=R[ye];this._singleTransform4(N,O,ee,Qe,de,j)}const Me=this.table;for(de>>=2;de>=2;de>>=2){Ce=D/de<<1;const Qe=Ce>>>2;for(ee=0;ee<D;ee+=Ce){const ge=ee+Qe-1;for(let Q=ee,ae=0;Q<ge;Q+=2,ae+=de){const Se=Q,X=Se+Qe,me=X+Qe,Ke=me+Qe,De=O[Se],Be=O[Se+1],We=O[X],ot=O[X+1],dt=O[me],Ge=O[me+1],Te=O[Ke],je=O[Ke+1],Ye=Me[ae],tt=j*Me[ae+1],A=We*Ye-ot*tt,Ae=We*tt+ot*Ye,$e=Me[2*ae],se=j*Me[2*ae+1],te=dt*$e-Ge*se,we=dt*se+Ge*$e,B=Me[3*ae],J=j*Me[3*ae+1],L=Te*B-je*J,ue=Te*J+je*B,le=De+te,ke=Be+we,Ne=De-te,ut=Be-we,Je=A+L,Ve=Ae+ue,Z=j*(A-L),ve=j*(Ae-ue);O[Se]=le+Je,O[Se+1]=ke+Ve,O[X]=Ne+ve,O[X+1]=ut-Z,O[me]=le-Je,O[me+1]=ke-Ve,O[Ke]=Ne-ve,O[Ke+1]=ut+Z}}}}_singleTransform2(O,N,j,D,Y){const de=O[D],Ce=O[D+1],ee=O[D+Y],ye=O[D+Y+1];N[j]=de+ee,N[j+1]=Ce+ye,N[j+2]=de-ee,N[j+3]=Ce-ye}_singleTransform4(O,N,j,D,Y,de){const Ce=Y*2,ee=Y*3,ye=O[D],R=O[D+1],Me=O[D+Y],Qe=O[D+Y+1],ge=O[D+Ce],Q=O[D+Ce+1],ae=O[D+ee],Se=O[D+ee+1],X=ye+ge,me=R+Q,Ke=ye-ge,De=R-Q,Be=Me+ae,We=Qe+Se,ot=de*(Me-ae),dt=de*(Qe-Se);N[j]=X+Be,N[j+1]=me+We,N[j+2]=Ke+dt,N[j+3]=De-ot,N[j+4]=X-Be,N[j+5]=me-We,N[j+6]=Ke-dt,N[j+7]=De+ot}_realTransform4(O,N,j){const D=this._csize;let de=1<<this._width,Ce=D/de<<1,ee,ye;const R=this._bitrev;if(Ce===4)for(ee=0,ye=0;ee<D;ee+=Ce,++ye){const ge=R[ye];this._singleRealTransform2(N,O,ee,ge>>>1,de>>>1)}else for(ee=0,ye=0;ee<D;ee+=Ce,++ye){const ge=R[ye];this._singleRealTransform4(N,O,ee,ge>>>1,de>>>1,j)}const Me=this.table;for(de>>=2;de>=2;de>>=2){Ce=D/de<<1;const ge=Ce>>>1,Q=ge>>>1,ae=Q>>>1;for(ee=0;ee<D;ee+=Ce)for(let Se=0,X=0;Se<=ae;Se+=2,X+=de){const me=ee+Se,Ke=me+Q,De=Ke+Q,Be=De+Q,We=O[me],ot=O[me+1],dt=O[Ke],Ge=O[Ke+1],Te=O[De],je=O[De+1],Ye=O[Be],tt=O[Be+1],A=We,Ae=ot,$e=Me[X],se=j*Me[X+1],te=dt*$e-Ge*se,we=dt*se+Ge*$e,B=Me[2*X],J=j*Me[2*X+1],L=Te*B-je*J,ue=Te*J+je*B,le=Me[3*X],ke=j*Me[3*X+1],Ne=Ye*le-tt*ke,ut=Ye*ke+tt*le,Je=A+L,Ve=Ae+ue,Z=A-L,ve=Ae-ue,Re=te+Ne,He=we+ut,Xe=j*(te-Ne),rt=j*(we-ut);if(O[me]=Je+Re,O[me+1]=Ve+He,O[Ke]=Z+rt,O[Ke+1]=ve-Xe,Se===0){O[De]=Je-Re,O[De+1]=Ve-He;continue}if(Se===ae)continue;const ft=ee+Q-Se,ht=ee+ge-Se;O[ft]=Z-j*rt,O[ft+1]=-ve-j*Xe,O[ht]=Je-j*Re,O[ht+1]=-Ve+j*He}}const Qe=D>>>1;for(let ge=2;ge<Qe;ge+=2)O[D-ge]=O[ge],O[D-ge+1]=-O[ge+1]}_singleRealTransform2(O,N,j,D,Y){const de=O[D],Ce=O[D+Y];N[j]=de+Ce,N[j+1]=0,N[j+2]=de-Ce,N[j+3]=0}_singleRealTransform4(O,N,j,D,Y,de){const Ce=Y*2,ee=Y*3,ye=O[D],R=O[D+Y],Me=O[D+Ce],Qe=O[D+ee],ge=ye+Me,Q=ye-Me,ae=R+Qe,Se=de*(R-Qe);N[j]=ge+ae,N[j+1]=0,N[j+2]=Q,N[j+3]=-Se,N[j+4]=ge-ae,N[j+5]=0,N[j+6]=Q,N[j+7]=Se}}class z{constructor(O){const N=2*(O-1),j=2*(2*O-1),D=2**Math.ceil(Math.log2(j));this.bufferSize=D,this._a=N;const Y=new Float64Array(j),de=new Float64Array(D);this._chirpBuffer=new Float64Array(D),this._buffer1=new Float64Array(D),this._buffer2=new Float64Array(D),this._outBuffer1=new Float64Array(D),this._outBuffer2=new Float64Array(D);const Ce=-2*Math.PI/O,ee=Math.cos(Ce),ye=Math.sin(Ce);for(let R=0;R<j>>1;++R){const Me=(R+1-O)**2/2,Qe=Math.sqrt(ee**2+ye**2)**Me,ge=Me*Math.atan2(ye,ee),Q=2*R;Y[Q]=Qe*Math.cos(ge),Y[Q+1]=Qe*Math.sin(ge),de[Q]=Y[Q],de[Q+1]=-Y[Q+1]}this._slicedChirpBuffer=Y.subarray(N,j),this._f=new k(D>>1),this._f.transform(this._chirpBuffer,de)}_transform(O,N,j){const D=this._buffer1,Y=this._buffer2,de=this._outBuffer1,Ce=this._outBuffer2,ee=this._chirpBuffer,ye=this._slicedChirpBuffer,R=this._a;if(j)for(let Me=0;Me<ye.length;Me+=2){const Qe=Me+1,ge=Me>>1,Q=N[ge];D[Me]=Q*ye[Me],D[Qe]=Q*ye[Qe]}else for(let Me=0;Me<ye.length;Me+=2){const Qe=Me+1;D[Me]=N[Me]*ye[Me]-N[Qe]*ye[Qe],D[Qe]=N[Me]*ye[Qe]+N[Qe]*ye[Me]}this._f.transform(de,D);for(let Me=0;Me<ee.length;Me+=2){const Qe=Me+1;Y[Me]=de[Me]*ee[Me]-de[Qe]*ee[Qe],Y[Qe]=de[Me]*ee[Qe]+de[Qe]*ee[Me]}this._f.inverseTransform(Ce,Y);for(let Me=0;Me<Ce.length;Me+=2){const Qe=Ce[Me+R],ge=Ce[Me+R+1],Q=ye[Me],ae=ye[Me+1];O[Me]=Qe*Q-ge*ae,O[Me+1]=Qe*ae+ge*Q}}transform(O,N){this._transform(O,N,!1)}realTransform(O,N){this._transform(O,N,!0)}}class S{constructor(O){this.fft_length=O,this.isPowerOfTwo=C(O),this.isPowerOfTwo?(this.fft=new k(O),this.outputBufferSize=2*O):(this.fft=new z(O),this.outputBufferSize=this.fft.bufferSize)}realTransform(O,N){this.fft.realTransform(O,N)}transform(O,N){this.fft.transform(O,N)}}function P(U,O){if(O%2===0||O<=0)throw new Error("Window size must be a positive odd number");const N=new U.constructor(U.length),j=new U.constructor(O),D=Math.floor(O/2);for(let Y=0;Y<U.length;++Y){let de=0;for(let Ce=-D;Ce<=D;++Ce){let ee=Y+Ce;ee<0?ee=Math.abs(ee):ee>=U.length&&(ee=2*(U.length-1)-ee),j[de++]=U[ee]}j.sort(),N[Y]=j[D]}return N}function y(U,O){const N=Math.pow(10,O);return Math.round(U*N)/N}function x(U){const O=Math.round(U);return Math.abs(U)%1===.5?O%2===0?O:O-1:O}function I(U){const O=U.length,N=U[0].length,j=[O+1,N+1],D=Array.from({length:j[0]},()=>Array(j[1]).fill(1/0));D[0][0]=0;const Y=Array.from({length:j[0]},()=>Array(j[1]).fill(-1));for(let R=1;R<j[1];++R)for(let Me=1;Me<j[0];++Me){const Qe=D[Me-1][R-1],ge=D[Me-1][R],Q=D[Me][R-1];let ae,Se;Qe<ge&&Qe<Q?(ae=Qe,Se=0):ge<Qe&&ge<Q?(ae=ge,Se=1):(ae=Q,Se=2),D[Me][R]=U[Me-1][R-1]+ae,Y[Me][R]=Se}for(let R=0;R<j[1];++R)Y[0][R]=2;for(let R=0;R<j[0];++R)Y[R][0]=1;let de=O,Ce=N,ee=[],ye=[];for(;de>0||Ce>0;)switch(ee.push(de-1),ye.push(Ce-1),Y[de][Ce]){case 0:--de,--Ce;break;case 1:--de;break;case 2:--Ce;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${de}, ${Ce}]. Please file a bug report.`)}return ee.reverse(),ye.reverse(),[ee,ye]}},"./src/utils/tensor.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>_,cat:()=>U,full:()=>de,full_like:()=>Ce,interpolate:()=>M,interpolate_4d:()=>w,layer_norm:()=>P,matmul:()=>C,mean:()=>j,mean_pooling:()=>S,ones:()=>ee,ones_like:()=>ye,permute:()=>g,quantize_embeddings:()=>Qe,rfft:()=>k,stack:()=>O,std_mean:()=>N,topk:()=>z,zeros:()=>R,zeros_like:()=>Me});var o=n("./src/utils/maths.js"),a=n("./src/backends/onnx.js"),l=n("./src/ops/registry.js");const f=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class _{constructor(...Q){qe(this,"ort_tensor");return(0,a.isONNXTensor)(Q[0])?this.ort_tensor=Q[0]:this.ort_tensor=new a.Tensor(Q[0],Q[1],Q[2]),new Proxy(this,{get:(ae,Se)=>{if(typeof Se=="string"){let X=Number(Se);if(Number.isInteger(X))return ae._getitem(X)}return ae[Se]},set:(ae,Se,X)=>ae[Se]=X})}get dims(){return this.ort_tensor.dims}set dims(Q){this.ort_tensor.dims=Q}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[Q,...ae]=this.dims;if(ae.length>0){const Se=ae.reduce((X,me)=>X*me);for(let X=0;X<Q;++X)yield this._subarray(X,Se,ae)}else yield*this.data}_getitem(Q){const[ae,...Se]=this.dims;if(Q=I(Q,ae),Se.length>0){const X=Se.reduce((me,Ke)=>me*Ke);return this._subarray(Q,X,Se)}else return new _(this.type,[this.data[Q]],Se)}indexOf(Q){const ae=this.data;for(let Se=0;Se<ae.length;++Se)if(ae[Se]==Q)return Se;return-1}_subarray(Q,ae,Se){const X=Q*ae,me=(Q+1)*ae,Ke="subarray"in this.data?this.data.subarray(X,me):this.data.slice(X,me);return new _(this.type,Ke,Se)}item(){const Q=this.data;if(Q.length!==1)throw new Error(`a Tensor with ${Q.length} elements cannot be converted to Scalar`);return Q[0]}tolist(){return h(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const Q=this.data;for(let ae=0;ae<Q.length;++ae)Q[ae]=1/(1+Math.exp(-Q[ae]));return this}mul(Q){return this.clone().mul_(Q)}mul_(Q){const ae=this.data;for(let Se=0;Se<ae.length;++Se)ae[Se]*=Q;return this}div(Q){return this.clone().div_(Q)}div_(Q){const ae=this.data;for(let Se=0;Se<ae.length;++Se)ae[Se]/=Q;return this}add(Q){return this.clone().add_(Q)}add_(Q){const ae=this.data;for(let Se=0;Se<ae.length;++Se)ae[Se]+=Q;return this}clone(){return new _(this.type,this.data.slice(),this.dims.slice())}slice(...Q){const ae=[],Se=[];for(let We=0;We<this.dims.length;++We){let ot=Q[We];if(ot==null)Se.push([0,this.dims[We]]),ae.push(this.dims[We]);else if(typeof ot=="number")ot=I(ot,this.dims[We],We),Se.push([ot,ot+1]);else if(Array.isArray(ot)&&ot.length===2){let[dt,Ge]=ot;if(dt=dt===null?0:I(dt,this.dims[We],We,!1),Ge=Ge===null?this.dims[We]:I(Ge,this.dims[We],We,!1),dt>Ge)throw new Error(`Invalid slice: ${ot}`);const Te=[Math.max(dt,0),Math.min(Ge,this.dims[We])];Se.push(Te),ae.push(Te[1]-Te[0])}else throw new Error(`Invalid slice: ${ot}`)}const X=Se.map(([We,ot])=>ot-We),me=X.reduce((We,ot)=>We*ot),Ke=this.data,De=new Ke.constructor(me),Be=this.stride();for(let We=0;We<me;++We){let ot=0;for(let dt=X.length-1,Ge=We;dt>=0;--dt){const Te=X[dt];ot+=(Ge%Te+Se[dt][0])*Be[dt],Ge=Math.floor(Ge/Te)}De[We]=Ke[ot]}return new _(this.type,De,ae)}permute(...Q){return g(this,Q)}transpose(...Q){return this.permute(...Q)}sum(Q=null,ae=!1){return this.norm(1,Q,ae)}norm(Q="fro",ae=null,Se=!1){if(Q==="fro")Q=2;else if(typeof Q=="string")throw Error(`Unsupported norm: ${Q}`);const X=this.data;if(ae===null){let De=X.reduce((Be,We)=>Be+We**Q,0)**(1/Q);return new _(this.type,[De],[])}ae=I(ae,this.dims.length);const me=this.dims.slice();me[ae]=1;const Ke=new X.constructor(X.length/this.dims[ae]);for(let De=0;De<X.length;++De){let Be=0;for(let We=this.dims.length-1,ot=De,dt=1;We>=0;--We){const Ge=this.dims[We];if(We!==ae){const Te=ot%Ge;Be+=Te*dt,dt*=me[We]}ot=Math.floor(ot/Ge)}Ke[Be]+=X[De]**Q}if(Q!==1)for(let De=0;De<Ke.length;++De)Ke[De]=Ke[De]**(1/Q);return Se||me.splice(ae,1),new _(this.type,Ke,me)}normalize_(Q=2,ae=1){ae=I(ae,this.dims.length);const Se=this.norm(Q,ae,!0),X=this.data,me=Se.data;for(let Ke=0;Ke<X.length;++Ke){let De=0;for(let Be=this.dims.length-1,We=Ke,ot=1;Be>=0;--Be){const dt=this.dims[Be];if(Be!==ae){const Ge=We%dt;De+=Ge*ot,ot*=this.dims[Be]}We=Math.floor(We/dt)}X[Ke]/=me[De]}return this}normalize(Q=2,ae=1){return this.clone().normalize_(Q,ae)}stride(){return D(this.dims)}squeeze(Q=null){return new _(this.type,this.data,y(this.dims,Q))}squeeze_(Q=null){return this.dims=y(this.dims,Q),this}unsqueeze(Q=null){return new _(this.type,this.data,x(this.dims,Q))}unsqueeze_(Q=null){return this.dims=x(this.dims,Q),this}flatten_(Q=0,ae=-1){ae=(ae+this.dims.length)%this.dims.length;let Se=this.dims.slice(0,Q),X=this.dims.slice(Q,ae+1),me=this.dims.slice(ae+1);return this.dims=[...Se,X.reduce((Ke,De)=>Ke*De,1),...me],this}flatten(Q=0,ae=-1){return this.clone().flatten_(Q,ae)}view(...Q){let ae=-1;for(let X=0;X<Q.length;++X)if(Q[X]===-1){if(ae!==-1)throw new Error("Only one dimension can be inferred");ae=X}const Se=this.data;if(ae!==-1){const X=Q.reduce((me,Ke,De)=>De!==ae?me*Ke:me,1);Q[ae]=Se.length/X}return new _(this.type,Se,Q)}neg_(){const Q=this.data;for(let ae=0;ae<Q.length;++ae)Q[ae]=-Q[ae];return this}neg(){return this.clone().neg_()}clamp_(Q,ae){const Se=this.data;for(let X=0;X<Se.length;++X)Se[X]=Math.min(Math.max(Se[X],Q),ae);return this}clamp(Q,ae){return this.clone().clamp_(Q,ae)}round_(){const Q=this.data;for(let ae=0;ae<Q.length;++ae)Q[ae]=Math.round(Q[ae]);return this}round(){return this.clone().round_()}mean(Q=null,ae=!1){return j(this,Q,ae)}to(Q){if(this.type===Q)return this;if(!f.hasOwnProperty(Q))throw new Error(`Unsupported type: ${Q}`);return new _(Q,f[Q].from(this.data),this.dims)}}function h(ge,Q){const ae=ge.length,Se=Q.reduce((me,Ke)=>me*Ke);if(ae!==Se)throw Error(`cannot reshape array of size ${ae} into shape (${Q})`);let X=ge;for(let me=Q.length-1;me>=0;me--)X=X.reduce((Ke,De)=>{let Be=Ke[Ke.length-1];return Be.length<Q[me]?Be.push(De):Ke.push([De]),Ke},[[]]);return X[0]}function g(ge,Q){const[ae,Se]=(0,o.permute_data)(ge.data,ge.dims,Q);return new _(ge.type,ae,Se)}function M(ge,[Q,ae],Se="bilinear",X=!1){const me=ge.dims.at(-3)??1,Ke=ge.dims.at(-2),De=ge.dims.at(-1);let Be=(0,o.interpolate_data)(ge.data,[me,Ke,De],[Q,ae],Se,X);return new _(ge.type,Be,[me,Q,ae])}async function w(ge,{size:Q=null,mode:ae="bilinear"}={}){if(ge.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!Q)throw new Error("`interpolate_4d` requires a `size` argument.");let Se;if(Q.length===2)Se=[...ge.dims.slice(0,2),...Q];else if(Q.length===3)Se=[ge.dims[0],...Q];else if(Q.length===4)Se=Q;else throw new Error("`size` must be of length 2, 3, or 4.");let X;if(ae==="bilinear")X=await l.TensorOpRegistry.bilinear_interpolate_4d;else if(ae==="bicubic")X=await l.TensorOpRegistry.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${ae}`);const me=new _("int64",new BigInt64Array(Se.map(BigInt)),[Se.length]);return await X({x:ge,s:me})}async function C(ge,Q){return await(await l.TensorOpRegistry.matmul)({a:ge,b:Q})}async function k(ge,Q){return await(await l.TensorOpRegistry.rfft)({x:ge,a:Q})}async function z(ge,Q){const ae=await l.TensorOpRegistry.top_k;return Q===null?Q=ge.dims.at(-1):Q=Math.min(Q,ge.dims.at(-1)),await ae({x:ge,k:new _("int64",[BigInt(Q)],[1])})}function S(ge,Q){const ae=ge.data,Se=Q.data,X=[ge.dims[0],ge.dims[2]],me=new ae.constructor(X[0]*X[1]),[Ke,De,Be]=ge.dims;let We=0;for(let ot=0;ot<Ke;++ot){const dt=ot*Be*De;for(let Ge=0;Ge<Be;++Ge){let Te=0,je=0;const Ye=ot*De,tt=dt+Ge;for(let Ae=0;Ae<De;++Ae){const $e=Number(Se[Ye+Ae]);je+=$e,Te+=ae[tt+Ae*Be]*$e}const A=Te/je;me[We++]=A}}return new _(ge.type,me,X)}function P(ge,Q,{eps:ae=1e-5}={}){if(ge.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");const[Se,X]=ge.dims;if(Q.length!==1&&Q[0]!==X)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");const[me,Ke]=N(ge,1,0,!0),De=me.data,Be=Ke.data,We=ge.data,ot=new We.constructor(We.length);for(let dt=0;dt<Se;++dt){const Ge=dt*X;for(let Te=0;Te<X;++Te){const je=Ge+Te;ot[je]=(We[je]-Be[dt])/(De[dt]+ae)}}return new _(ge.type,ot,ge.dims)}function y(ge,Q){return ge=ge.slice(),Q===null?ge=ge.filter(ae=>ae!==1):typeof Q=="number"?ge[Q]===1&&ge.splice(Q,1):Array.isArray(Q)&&(ge=ge.filter((ae,Se)=>ae!==1||!Q.includes(Se))),ge}function x(ge,Q){return Q=I(Q,ge.length+1),ge=ge.slice(),ge.splice(Q,0,1),ge}function I(ge,Q,ae=null,Se=!0){if(Se&&(ge<-Q||ge>=Q))throw new Error(`IndexError: index ${ge} is out of bounds for dimension${ae===null?"":" "+ae} with size ${Q}`);return ge<0&&(ge=(ge%Q+Q)%Q),ge}function U(ge,Q=0){Q=I(Q,ge[0].dims.length);const ae=ge[0].dims.slice();ae[Q]=ge.reduce((Ke,De)=>Ke+De.dims[Q],0);const Se=ae.reduce((Ke,De)=>Ke*De,1),X=new ge[0].data.constructor(Se),me=ge[0].type;if(Q===0){let Ke=0;for(const De of ge){const Be=De.data;X.set(Be,Ke),Ke+=Be.length}}else{let Ke=0;for(let De=0;De<ge.length;++De){const{data:Be,dims:We}=ge[De];for(let ot=0;ot<Be.length;++ot){let dt=0;for(let Ge=We.length-1,Te=ot,je=1;Ge>=0;--Ge){const Ye=We[Ge];let tt=Te%Ye;Ge===Q&&(tt+=Ke),dt+=tt*je,je*=ae[Ge],Te=Math.floor(Te/Ye)}X[dt]=Be[ot]}Ke+=We[Q]}}return new _(me,X,ae)}function O(ge,Q=0){return U(ge.map(ae=>ae.unsqueeze(Q)),Q)}function N(ge,Q=null,ae=1,Se=!1){const X=ge.data,me=ge.dims;if(Q===null){const Ge=X.reduce((tt,A)=>tt+A,0)/X.length,Te=Math.sqrt(X.reduce((tt,A)=>tt+(A-Ge)**2,0)/(X.length-ae)),je=new _(ge.type,[Ge],[]);return[new _(ge.type,[Te],[]),je]}Q=I(Q,me.length);const Ke=j(ge,Q,Se),De=Ke.data,Be=me.slice();Be[Q]=1;const We=new X.constructor(X.length/me[Q]);for(let dt=0;dt<X.length;++dt){let Ge=0;for(let Te=me.length-1,je=dt,Ye=1;Te>=0;--Te){const tt=me[Te];if(Te!==Q){const A=je%tt;Ge+=A*Ye,Ye*=Be[Te]}je=Math.floor(je/tt)}We[Ge]+=(X[dt]-De[Ge])**2}for(let dt=0;dt<We.length;++dt)We[dt]=Math.sqrt(We[dt]/(me[Q]-ae));return Se||Be.splice(Q,1),[new _(ge.type,We,Be),Ke]}function j(ge,Q=null,ae=!1){const Se=ge.data;if(Q===null){const De=Se.reduce((Be,We)=>Be+We,0);return new _(ge.type,[De/Se.length],[])}const X=ge.dims;Q=I(Q,X.length);const me=X.slice();me[Q]=1;const Ke=new Se.constructor(Se.length/X[Q]);for(let De=0;De<Se.length;++De){let Be=0;for(let We=X.length-1,ot=De,dt=1;We>=0;--We){const Ge=X[We];if(We!==Q){const Te=ot%Ge;Be+=Te*dt,dt*=me[We]}ot=Math.floor(ot/Ge)}Ke[Be]+=Se[De]}if(X[Q]!==1)for(let De=0;De<Ke.length;++De)Ke[De]=Ke[De]/X[Q];return ae||me.splice(Q,1),new _(ge.type,Ke,me)}function D(ge){const Q=new Array(ge.length);for(let ae=ge.length-1,Se=1;ae>=0;--ae)Q[ae]=Se,Se*=ge[ae];return Q}function Y(ge,Q,ae,Se){const X=ge.reduce((me,Ke)=>me*Ke,1);return new _(ae,new Se(X).fill(Q),ge)}function de(ge,Q){let ae,Se;if(typeof Q=="number")ae="float32",Se=Float32Array;else if(typeof Q=="bigint")ae="int64",Se=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof Q}`);return Y(ge,Q,ae,Se)}function Ce(ge,Q){return de(ge.dims,Q)}function ee(ge){return Y(ge,1n,"int64",BigInt64Array)}function ye(ge){return ee(ge.dims)}function R(ge){return Y(ge,0n,"int64",BigInt64Array)}function Me(ge){return R(ge.dims)}function Qe(ge,Q){if(ge.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ge.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(Q))throw new Error("The precision must be either 'binary' or 'ubinary'");const ae=Q==="binary",Se=ae?"int8":"uint8",X=ae?Int8Array:Uint8Array,me=ge.data,Ke=new X(me.length/8);for(let De=0;De<me.length;++De){const Be=me[De]>0?1:0,We=Math.floor(De/8),ot=De%8;Ke[We]|=Be<<7-ot,ae&&ot===0&&(Ke[We]-=128)}return new _(Se,Ke,[ge.dims[0],ge.dims[1]/8])}}},w1={};function Yr(e){var t=w1[e];if(t!==void 0)return t.exports;var n=w1[e]={exports:{}};return sE[e](n,n.exports,Yr),n.exports}(()=>{var e=Object.getPrototypeOf?n=>Object.getPrototypeOf(n):n=>n.__proto__,t;Yr.t=function(n,o){if(o&1&&(n=this(n)),o&8||typeof n=="object"&&n&&(o&4&&n.__esModule||o&16&&typeof n.then=="function"))return n;var a=Object.create(null);Yr.r(a);var l={};t=t||[null,e({}),e([]),e(e)];for(var f=o&2&&n;typeof f=="object"&&!~t.indexOf(f);f=e(f))Object.getOwnPropertyNames(f).forEach(_=>l[_]=()=>n[_]);return l.default=()=>n,Yr.d(a,l),a}})();Yr.d=(e,t)=>{for(var n in t)Yr.o(t,n)&&!Yr.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})};Yr.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);Yr.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};(()=>{var e;if(typeof import.meta.url=="string"&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Yr.p=e})();Yr.b=void 0;var $={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Yr.r($),Yr.d($,{ASTFeatureExtractor:()=>a.ASTFeatureExtractor,ASTForAudioClassification:()=>n.ASTForAudioClassification,ASTModel:()=>n.ASTModel,ASTPreTrainedModel:()=>n.ASTPreTrainedModel,AlbertForMaskedLM:()=>n.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>n.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>n.AlbertForSequenceClassification,AlbertModel:()=>n.AlbertModel,AlbertPreTrainedModel:()=>n.AlbertPreTrainedModel,AlbertTokenizer:()=>o.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>l.AutoConfig,AutoModel:()=>n.AutoModel,AutoModelForAudioClassification:()=>n.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>n.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>n.AutoModelForCTC,AutoModelForCausalLM:()=>n.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>n.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>n.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>n.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>n.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>n.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>n.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>n.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>n.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>n.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>n.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>n.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>n.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>n.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>n.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>n.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>n.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>n.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>n.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>n.AutoModelForVision2Seq,AutoModelForXVector:()=>n.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>n.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>a.AutoProcessor,AutoTokenizer:()=>o.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>n.BartForConditionalGeneration,BartForSequenceClassification:()=>n.BartForSequenceClassification,BartModel:()=>n.BartModel,BartPretrainedModel:()=>n.BartPretrainedModel,BartTokenizer:()=>o.BartTokenizer,BaseModelOutput:()=>n.BaseModelOutput,BaseStreamer:()=>M.BaseStreamer,BeitFeatureExtractor:()=>a.BeitFeatureExtractor,BeitForImageClassification:()=>n.BeitForImageClassification,BeitModel:()=>n.BeitModel,BeitPreTrainedModel:()=>n.BeitPreTrainedModel,BertForMaskedLM:()=>n.BertForMaskedLM,BertForQuestionAnswering:()=>n.BertForQuestionAnswering,BertForSequenceClassification:()=>n.BertForSequenceClassification,BertForTokenClassification:()=>n.BertForTokenClassification,BertModel:()=>n.BertModel,BertPreTrainedModel:()=>n.BertPreTrainedModel,BertTokenizer:()=>o.BertTokenizer,BitImageProcessor:()=>a.BitImageProcessor,BlenderbotForConditionalGeneration:()=>n.BlenderbotForConditionalGeneration,BlenderbotModel:()=>n.BlenderbotModel,BlenderbotPreTrainedModel:()=>n.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>n.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>n.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>n.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>o.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>o.BlenderbotTokenizer,BloomForCausalLM:()=>n.BloomForCausalLM,BloomModel:()=>n.BloomModel,BloomPreTrainedModel:()=>n.BloomPreTrainedModel,BloomTokenizer:()=>o.BloomTokenizer,CLIPFeatureExtractor:()=>a.CLIPFeatureExtractor,CLIPImageProcessor:()=>a.CLIPImageProcessor,CLIPModel:()=>n.CLIPModel,CLIPPreTrainedModel:()=>n.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>n.CLIPSegForImageSegmentation,CLIPSegModel:()=>n.CLIPSegModel,CLIPSegPreTrainedModel:()=>n.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>n.CLIPTextModelWithProjection,CLIPTokenizer:()=>o.CLIPTokenizer,CLIPVisionModelWithProjection:()=>n.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>n.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>n.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>n.CamembertForSequenceClassification,CamembertForTokenClassification:()=>n.CamembertForTokenClassification,CamembertModel:()=>n.CamembertModel,CamembertPreTrainedModel:()=>n.CamembertPreTrainedModel,CamembertTokenizer:()=>o.CamembertTokenizer,CausalLMOutput:()=>n.CausalLMOutput,CausalLMOutputWithPast:()=>n.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>a.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>n.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>n.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>n.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>a.ClapFeatureExtractor,ClapModel:()=>n.ClapModel,ClapPreTrainedModel:()=>n.ClapPreTrainedModel,ClapTextModelWithProjection:()=>n.ClapTextModelWithProjection,CodeGenForCausalLM:()=>n.CodeGenForCausalLM,CodeGenModel:()=>n.CodeGenModel,CodeGenPreTrainedModel:()=>n.CodeGenPreTrainedModel,CodeGenTokenizer:()=>o.CodeGenTokenizer,CodeLlamaTokenizer:()=>o.CodeLlamaTokenizer,CohereForCausalLM:()=>n.CohereForCausalLM,CohereModel:()=>n.CohereModel,CoherePreTrainedModel:()=>n.CoherePreTrainedModel,CohereTokenizer:()=>o.CohereTokenizer,ConvBertForMaskedLM:()=>n.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>n.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>n.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>n.ConvBertForTokenClassification,ConvBertModel:()=>n.ConvBertModel,ConvBertPreTrainedModel:()=>n.ConvBertPreTrainedModel,ConvBertTokenizer:()=>o.ConvBertTokenizer,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>n.ConvNextForImageClassification,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,ConvNextModel:()=>n.ConvNextModel,ConvNextPreTrainedModel:()=>n.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>n.ConvNextV2ForImageClassification,ConvNextV2Model:()=>n.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>n.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>a.DPTFeatureExtractor,DPTForDepthEstimation:()=>n.DPTForDepthEstimation,DPTImageProcessor:()=>a.DPTImageProcessor,DPTModel:()=>n.DPTModel,DPTPreTrainedModel:()=>n.DPTPreTrainedModel,DebertaForMaskedLM:()=>n.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>n.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>n.DebertaForSequenceClassification,DebertaForTokenClassification:()=>n.DebertaForTokenClassification,DebertaModel:()=>n.DebertaModel,DebertaPreTrainedModel:()=>n.DebertaPreTrainedModel,DebertaTokenizer:()=>o.DebertaTokenizer,DebertaV2ForMaskedLM:()=>n.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>n.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>n.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>n.DebertaV2ForTokenClassification,DebertaV2Model:()=>n.DebertaV2Model,DebertaV2PreTrainedModel:()=>n.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>o.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>a.DeiTFeatureExtractor,DeiTForImageClassification:()=>n.DeiTForImageClassification,DeiTModel:()=>n.DeiTModel,DeiTPreTrainedModel:()=>n.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>n.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>n.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DetrFeatureExtractor:()=>a.DetrFeatureExtractor,DetrForObjectDetection:()=>n.DetrForObjectDetection,DetrForSegmentation:()=>n.DetrForSegmentation,DetrModel:()=>n.DetrModel,DetrObjectDetectionOutput:()=>n.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>n.DetrPreTrainedModel,DetrSegmentationOutput:()=>n.DetrSegmentationOutput,Dinov2ForImageClassification:()=>n.Dinov2ForImageClassification,Dinov2Model:()=>n.Dinov2Model,Dinov2PreTrainedModel:()=>n.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>n.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>n.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>n.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>n.DistilBertForTokenClassification,DistilBertModel:()=>n.DistilBertModel,DistilBertPreTrainedModel:()=>n.DistilBertPreTrainedModel,DistilBertTokenizer:()=>o.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>a.DonutFeatureExtractor,DonutSwinModel:()=>n.DonutSwinModel,DonutSwinPreTrainedModel:()=>n.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>n.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>a.EfficientNetImageProcessor,EfficientNetModel:()=>n.EfficientNetModel,EfficientNetPreTrainedModel:()=>n.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>n.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>n.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>n.ElectraForSequenceClassification,ElectraForTokenClassification:()=>n.ElectraForTokenClassification,ElectraModel:()=>n.ElectraModel,ElectraPreTrainedModel:()=>n.ElectraPreTrainedModel,ElectraTokenizer:()=>o.ElectraTokenizer,EosTokenCriteria:()=>w.EosTokenCriteria,EsmForMaskedLM:()=>n.EsmForMaskedLM,EsmForSequenceClassification:()=>n.EsmForSequenceClassification,EsmForTokenClassification:()=>n.EsmForTokenClassification,EsmModel:()=>n.EsmModel,EsmPreTrainedModel:()=>n.EsmPreTrainedModel,EsmTokenizer:()=>o.EsmTokenizer,FFT:()=>g.FFT,FalconForCausalLM:()=>n.FalconForCausalLM,FalconModel:()=>n.FalconModel,FalconPreTrainedModel:()=>n.FalconPreTrainedModel,FalconTokenizer:()=>o.FalconTokenizer,FastViTForImageClassification:()=>n.FastViTForImageClassification,FastViTModel:()=>n.FastViTModel,FastViTPreTrainedModel:()=>n.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>a.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>n.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>n.Florence2PreTrainedModel,Florence2Processor:()=>a.Florence2Processor,GLPNFeatureExtractor:()=>a.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>n.GLPNForDepthEstimation,GLPNModel:()=>n.GLPNModel,GLPNPreTrainedModel:()=>n.GLPNPreTrainedModel,GPT2LMHeadModel:()=>n.GPT2LMHeadModel,GPT2Model:()=>n.GPT2Model,GPT2PreTrainedModel:()=>n.GPT2PreTrainedModel,GPT2Tokenizer:()=>o.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>n.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>n.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>n.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>n.GPTJForCausalLM,GPTJModel:()=>n.GPTJModel,GPTJPreTrainedModel:()=>n.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>n.GPTNeoForCausalLM,GPTNeoModel:()=>n.GPTNeoModel,GPTNeoPreTrainedModel:()=>n.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>n.GPTNeoXForCausalLM,GPTNeoXModel:()=>n.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>n.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>o.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>n.Gemma2ForCausalLM,Gemma2Model:()=>n.Gemma2Model,Gemma2PreTrainedModel:()=>n.Gemma2PreTrainedModel,GemmaForCausalLM:()=>n.GemmaForCausalLM,GemmaModel:()=>n.GemmaModel,GemmaPreTrainedModel:()=>n.GemmaPreTrainedModel,GemmaTokenizer:()=>o.GemmaTokenizer,Grok1Tokenizer:()=>o.Grok1Tokenizer,HerbertTokenizer:()=>o.HerbertTokenizer,HubertForCTC:()=>n.HubertForCTC,HubertForSequenceClassification:()=>n.HubertForSequenceClassification,HubertModel:()=>n.HubertModel,HubertPreTrainedModel:()=>n.HubertPreTrainedModel,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>a.ImageFeatureExtractor,ImageMattingOutput:()=>n.ImageMattingOutput,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>w.InterruptableStoppingCriteria,LlamaForCausalLM:()=>n.LlamaForCausalLM,LlamaModel:()=>n.LlamaModel,LlamaPreTrainedModel:()=>n.LlamaPreTrainedModel,LlamaTokenizer:()=>o.LlamaTokenizer,LlavaForConditionalGeneration:()=>n.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>n.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>n.LongT5ForConditionalGeneration,LongT5Model:()=>n.LongT5Model,LongT5PreTrainedModel:()=>n.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>n.M2M100ForConditionalGeneration,M2M100Model:()=>n.M2M100Model,M2M100PreTrainedModel:()=>n.M2M100PreTrainedModel,M2M100Tokenizer:()=>o.M2M100Tokenizer,MBart50Tokenizer:()=>o.MBart50Tokenizer,MBartForCausalLM:()=>n.MBartForCausalLM,MBartForConditionalGeneration:()=>n.MBartForConditionalGeneration,MBartForSequenceClassification:()=>n.MBartForSequenceClassification,MBartModel:()=>n.MBartModel,MBartPreTrainedModel:()=>n.MBartPreTrainedModel,MBartTokenizer:()=>o.MBartTokenizer,MPNetForMaskedLM:()=>n.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>n.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>n.MPNetForSequenceClassification,MPNetForTokenClassification:()=>n.MPNetForTokenClassification,MPNetModel:()=>n.MPNetModel,MPNetPreTrainedModel:()=>n.MPNetPreTrainedModel,MPNetTokenizer:()=>o.MPNetTokenizer,MT5ForConditionalGeneration:()=>n.MT5ForConditionalGeneration,MT5Model:()=>n.MT5Model,MT5PreTrainedModel:()=>n.MT5PreTrainedModel,MarianMTModel:()=>n.MarianMTModel,MarianModel:()=>n.MarianModel,MarianPreTrainedModel:()=>n.MarianPreTrainedModel,MarianTokenizer:()=>o.MarianTokenizer,MaskedLMOutput:()=>n.MaskedLMOutput,MaxLengthCriteria:()=>w.MaxLengthCriteria,MistralForCausalLM:()=>n.MistralForCausalLM,MistralModel:()=>n.MistralModel,MistralPreTrainedModel:()=>n.MistralPreTrainedModel,MobileBertForMaskedLM:()=>n.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>n.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>n.MobileBertForSequenceClassification,MobileBertModel:()=>n.MobileBertModel,MobileBertPreTrainedModel:()=>n.MobileBertPreTrainedModel,MobileBertTokenizer:()=>o.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>a.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>n.MobileNetV1ForImageClassification,MobileNetV1Model:()=>n.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>n.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>a.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>n.MobileNetV2ForImageClassification,MobileNetV2Model:()=>n.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>n.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>a.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>n.MobileNetV3ForImageClassification,MobileNetV3Model:()=>n.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>n.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>a.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>n.MobileNetV4ForImageClassification,MobileNetV4Model:()=>n.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>n.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>a.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>n.MobileViTForImageClassification,MobileViTImageProcessor:()=>a.MobileViTImageProcessor,MobileViTModel:()=>n.MobileViTModel,MobileViTPreTrainedModel:()=>n.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>n.MobileViTV2ForImageClassification,MobileViTV2Model:()=>n.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>n.MobileViTV2PreTrainedModel,ModelOutput:()=>n.ModelOutput,Moondream1ForConditionalGeneration:()=>n.Moondream1ForConditionalGeneration,MptForCausalLM:()=>n.MptForCausalLM,MptModel:()=>n.MptModel,MptPreTrainedModel:()=>n.MptPreTrainedModel,MusicgenForCausalLM:()=>n.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>n.MusicgenForConditionalGeneration,MusicgenModel:()=>n.MusicgenModel,MusicgenPreTrainedModel:()=>n.MusicgenPreTrainedModel,NllbTokenizer:()=>o.NllbTokenizer,NomicBertModel:()=>n.NomicBertModel,NomicBertPreTrainedModel:()=>n.NomicBertPreTrainedModel,NougatImageProcessor:()=>a.NougatImageProcessor,NougatTokenizer:()=>o.NougatTokenizer,OPTForCausalLM:()=>n.OPTForCausalLM,OPTModel:()=>n.OPTModel,OPTPreTrainedModel:()=>n.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OpenELMForCausalLM:()=>n.OpenELMForCausalLM,OpenELMModel:()=>n.OpenELMModel,OpenELMPreTrainedModel:()=>n.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>a.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>n.OwlViTForObjectDetection,OwlViTModel:()=>n.OwlViTModel,OwlViTPreTrainedModel:()=>n.OwlViTPreTrainedModel,OwlViTProcessor:()=>a.OwlViTProcessor,Owlv2ForObjectDetection:()=>n.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>a.Owlv2ImageProcessor,Owlv2Model:()=>n.Owlv2Model,Owlv2PreTrainedModel:()=>n.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>n.Phi3ForCausalLM,Phi3Model:()=>n.Phi3Model,Phi3PreTrainedModel:()=>n.Phi3PreTrainedModel,PhiForCausalLM:()=>n.PhiForCausalLM,PhiModel:()=>n.PhiModel,PhiPreTrainedModel:()=>n.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>n.PreTrainedModel,PreTrainedTokenizer:()=>o.PreTrainedTokenizer,PretrainedConfig:()=>l.PretrainedConfig,PretrainedMixin:()=>n.PretrainedMixin,Processor:()=>a.Processor,PyAnnoteFeatureExtractor:()=>a.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>n.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>n.PyAnnoteModel,PyAnnotePreTrainedModel:()=>n.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>a.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>n.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>n.Qwen2ForCausalLM,Qwen2Model:()=>n.Qwen2Model,Qwen2PreTrainedModel:()=>n.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>o.Qwen2Tokenizer,RTDetrForObjectDetection:()=>n.RTDetrForObjectDetection,RTDetrImageProcessor:()=>a.RTDetrImageProcessor,RTDetrModel:()=>n.RTDetrModel,RTDetrObjectDetectionOutput:()=>n.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>n.RTDetrPreTrainedModel,RawImage:()=>_.RawImage,ResNetForImageClassification:()=>n.ResNetForImageClassification,ResNetModel:()=>n.ResNetModel,ResNetPreTrainedModel:()=>n.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>n.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>n.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>n.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>n.RoFormerForTokenClassification,RoFormerModel:()=>n.RoFormerModel,RoFormerPreTrainedModel:()=>n.RoFormerPreTrainedModel,RoFormerTokenizer:()=>o.RoFormerTokenizer,RobertaForMaskedLM:()=>n.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>n.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>n.RobertaForSequenceClassification,RobertaForTokenClassification:()=>n.RobertaForTokenClassification,RobertaModel:()=>n.RobertaModel,RobertaPreTrainedModel:()=>n.RobertaPreTrainedModel,RobertaTokenizer:()=>o.RobertaTokenizer,SamImageProcessor:()=>a.SamImageProcessor,SamImageSegmentationOutput:()=>n.SamImageSegmentationOutput,SamModel:()=>n.SamModel,SamPreTrainedModel:()=>n.SamPreTrainedModel,SamProcessor:()=>a.SamProcessor,SeamlessM4TFeatureExtractor:()=>a.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>a.SegformerFeatureExtractor,SegformerForImageClassification:()=>n.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>n.SegformerForSemanticSegmentation,SegformerModel:()=>n.SegformerModel,SegformerPreTrainedModel:()=>n.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>n.Seq2SeqLMOutput,SequenceClassifierOutput:()=>n.SequenceClassifierOutput,SiglipImageProcessor:()=>a.SiglipImageProcessor,SiglipModel:()=>n.SiglipModel,SiglipPreTrainedModel:()=>n.SiglipPreTrainedModel,SiglipTextModel:()=>n.SiglipTextModel,SiglipTokenizer:()=>o.SiglipTokenizer,SiglipVisionModel:()=>n.SiglipVisionModel,SpeechT5FeatureExtractor:()=>a.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>n.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>n.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>n.SpeechT5HifiGan,SpeechT5Model:()=>n.SpeechT5Model,SpeechT5PreTrainedModel:()=>n.SpeechT5PreTrainedModel,SpeechT5Processor:()=>a.SpeechT5Processor,SpeechT5Tokenizer:()=>o.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>n.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>n.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>n.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>n.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>n.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>o.SqueezeBertTokenizer,StableLmForCausalLM:()=>n.StableLmForCausalLM,StableLmModel:()=>n.StableLmModel,StableLmPreTrainedModel:()=>n.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>n.Starcoder2ForCausalLM,Starcoder2Model:()=>n.Starcoder2Model,Starcoder2PreTrainedModel:()=>n.Starcoder2PreTrainedModel,StoppingCriteria:()=>w.StoppingCriteria,StoppingCriteriaList:()=>w.StoppingCriteriaList,SummarizationPipeline:()=>t.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>n.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>a.Swin2SRImageProcessor,Swin2SRModel:()=>n.Swin2SRModel,Swin2SRPreTrainedModel:()=>n.Swin2SRPreTrainedModel,SwinForImageClassification:()=>n.SwinForImageClassification,SwinModel:()=>n.SwinModel,SwinPreTrainedModel:()=>n.SwinPreTrainedModel,T5ForConditionalGeneration:()=>n.T5ForConditionalGeneration,T5Model:()=>n.T5Model,T5PreTrainedModel:()=>n.T5PreTrainedModel,T5Tokenizer:()=>o.T5Tokenizer,TableTransformerForObjectDetection:()=>n.TableTransformerForObjectDetection,TableTransformerModel:()=>n.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>n.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>n.TableTransformerPreTrainedModel,Tensor:()=>h.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>M.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>n.TokenClassifierOutput,TokenizerModel:()=>o.TokenizerModel,TrOCRForCausalLM:()=>n.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>n.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>n.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>n.UniSpeechForSequenceClassification,UniSpeechModel:()=>n.UniSpeechModel,UniSpeechPreTrainedModel:()=>n.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>n.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>n.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>n.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>n.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>n.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>a.ViTFeatureExtractor,ViTForImageClassification:()=>n.ViTForImageClassification,ViTImageProcessor:()=>a.ViTImageProcessor,ViTModel:()=>n.ViTModel,ViTPreTrainedModel:()=>n.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>n.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>n.VitMatteForImageMatting,VitMatteImageProcessor:()=>a.VitMatteImageProcessor,VitMattePreTrainedModel:()=>n.VitMattePreTrainedModel,VitsModel:()=>n.VitsModel,VitsModelOutput:()=>n.VitsModelOutput,VitsPreTrainedModel:()=>n.VitsPreTrainedModel,VitsTokenizer:()=>o.VitsTokenizer,Wav2Vec2BertForCTC:()=>n.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>n.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>n.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>n.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>o.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>a.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>n.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>n.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>n.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>n.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>n.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>a.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>n.WavLMForAudioFrameClassification,WavLMForCTC:()=>n.WavLMForCTC,WavLMForSequenceClassification:()=>n.WavLMForSequenceClassification,WavLMForXVector:()=>n.WavLMForXVector,WavLMModel:()=>n.WavLMModel,WavLMPreTrainedModel:()=>n.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>a.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>n.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>n.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>a.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>n.WhisperForConditionalGeneration,WhisperModel:()=>n.WhisperModel,WhisperPreTrainedModel:()=>n.WhisperPreTrainedModel,WhisperProcessor:()=>a.WhisperProcessor,WhisperTextStreamer:()=>M.WhisperTextStreamer,WhisperTokenizer:()=>o.WhisperTokenizer,XLMForQuestionAnswering:()=>n.XLMForQuestionAnswering,XLMForSequenceClassification:()=>n.XLMForSequenceClassification,XLMForTokenClassification:()=>n.XLMForTokenClassification,XLMModel:()=>n.XLMModel,XLMPreTrainedModel:()=>n.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>n.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>n.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>n.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>n.XLMRobertaForTokenClassification,XLMRobertaModel:()=>n.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>n.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>o.XLMRobertaTokenizer,XLMTokenizer:()=>o.XLMTokenizer,XLMWithLMHeadModel:()=>n.XLMWithLMHeadModel,XVectorOutput:()=>n.XVectorOutput,YolosFeatureExtractor:()=>a.YolosFeatureExtractor,YolosForObjectDetection:()=>n.YolosForObjectDetection,YolosModel:()=>n.YolosModel,YolosObjectDetectionOutput:()=>n.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>n.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>h.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>e.env,full:()=>h.full,full_like:()=>h.full_like,getKeyValueShapes:()=>l.getKeyValueShapes,hamming:()=>f.hamming,hanning:()=>f.hanning,interpolate:()=>h.interpolate,interpolate_4d:()=>h.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>o.is_chinese_char,layer_norm:()=>h.layer_norm,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>h.matmul,max:()=>g.max,mean:()=>h.mean,mean_pooling:()=>h.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>f.mel_filter_bank,min:()=>g.min,ones:()=>h.ones,ones_like:()=>h.ones_like,permute:()=>h.permute,permute_data:()=>g.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>h.quantize_embeddings,read_audio:()=>f.read_audio,rfft:()=>h.rfft,round:()=>g.round,softmax:()=>g.softmax,spectrogram:()=>f.spectrogram,stack:()=>h.stack,std_mean:()=>h.std_mean,topk:()=>h.topk,window_function:()=>f.window_function,zeros:()=>h.zeros,zeros_like:()=>h.zeros_like});var e=Yr("./src/env.js"),t=Yr("./src/pipelines.js"),n=Yr("./src/models.js"),o=Yr("./src/tokenizers.js"),a=Yr("./src/processors.js"),l=Yr("./src/configs.js"),f=Yr("./src/utils/audio.js"),_=Yr("./src/utils/image.js"),h=Yr("./src/utils/tensor.js"),g=Yr("./src/utils/maths.js"),M=Yr("./src/generation/streamers.js"),w=Yr("./src/generation/stopping_criteria.js")})();$.ASTFeatureExtractor;$.ASTForAudioClassification;$.ASTModel;$.ASTPreTrainedModel;$.AlbertForMaskedLM;$.AlbertForQuestionAnswering;$.AlbertForSequenceClassification;$.AlbertModel;$.AlbertPreTrainedModel;$.AlbertTokenizer;$.AudioClassificationPipeline;$.AutoConfig;var aE=$.AutoModel;$.AutoModelForAudioClassification;$.AutoModelForAudioFrameClassification;$.AutoModelForCTC;$.AutoModelForCausalLM;$.AutoModelForDepthEstimation;$.AutoModelForDocumentQuestionAnswering;$.AutoModelForImageClassification;$.AutoModelForImageFeatureExtraction;$.AutoModelForImageMatting;$.AutoModelForImageSegmentation;$.AutoModelForImageToImage;$.AutoModelForMaskGeneration;$.AutoModelForMaskedLM;$.AutoModelForObjectDetection;$.AutoModelForQuestionAnswering;$.AutoModelForSemanticSegmentation;$.AutoModelForSeq2SeqLM;$.AutoModelForSequenceClassification;$.AutoModelForSpeechSeq2Seq;$.AutoModelForTextToSpectrogram;$.AutoModelForTextToWaveform;$.AutoModelForTokenClassification;$.AutoModelForVision2Seq;$.AutoModelForXVector;$.AutoModelForZeroShotObjectDetection;var lE=$.AutoProcessor;$.AutoTokenizer;$.AutomaticSpeechRecognitionPipeline;$.BartForConditionalGeneration;$.BartForSequenceClassification;$.BartModel;$.BartPretrainedModel;$.BartTokenizer;$.BaseModelOutput;$.BaseStreamer;$.BeitFeatureExtractor;$.BeitForImageClassification;$.BeitModel;$.BeitPreTrainedModel;$.BertForMaskedLM;$.BertForQuestionAnswering;$.BertForSequenceClassification;$.BertForTokenClassification;$.BertModel;$.BertPreTrainedModel;$.BertTokenizer;$.BitImageProcessor;$.BlenderbotForConditionalGeneration;$.BlenderbotModel;$.BlenderbotPreTrainedModel;$.BlenderbotSmallForConditionalGeneration;$.BlenderbotSmallModel;$.BlenderbotSmallPreTrainedModel;$.BlenderbotSmallTokenizer;$.BlenderbotTokenizer;$.BloomForCausalLM;$.BloomModel;$.BloomPreTrainedModel;$.BloomTokenizer;$.CLIPFeatureExtractor;$.CLIPImageProcessor;$.CLIPModel;$.CLIPPreTrainedModel;$.CLIPSegForImageSegmentation;$.CLIPSegModel;$.CLIPSegPreTrainedModel;$.CLIPTextModelWithProjection;$.CLIPTokenizer;$.CLIPVisionModelWithProjection;$.CamembertForMaskedLM;$.CamembertForQuestionAnswering;$.CamembertForSequenceClassification;$.CamembertForTokenClassification;$.CamembertModel;$.CamembertPreTrainedModel;$.CamembertTokenizer;$.CausalLMOutput;$.CausalLMOutputWithPast;$.ChineseCLIPFeatureExtractor;$.ChineseCLIPModel;$.ChineseCLIPPreTrainedModel;$.ClapAudioModelWithProjection;$.ClapFeatureExtractor;$.ClapModel;$.ClapPreTrainedModel;$.ClapTextModelWithProjection;$.CodeGenForCausalLM;$.CodeGenModel;$.CodeGenPreTrainedModel;$.CodeGenTokenizer;$.CodeLlamaTokenizer;$.CohereForCausalLM;$.CohereModel;$.CoherePreTrainedModel;$.CohereTokenizer;$.ConvBertForMaskedLM;$.ConvBertForQuestionAnswering;$.ConvBertForSequenceClassification;$.ConvBertForTokenClassification;$.ConvBertModel;$.ConvBertPreTrainedModel;$.ConvBertTokenizer;$.ConvNextFeatureExtractor;$.ConvNextForImageClassification;$.ConvNextImageProcessor;$.ConvNextModel;$.ConvNextPreTrainedModel;$.ConvNextV2ForImageClassification;$.ConvNextV2Model;$.ConvNextV2PreTrainedModel;$.DPTFeatureExtractor;$.DPTForDepthEstimation;$.DPTImageProcessor;$.DPTModel;$.DPTPreTrainedModel;$.DebertaForMaskedLM;$.DebertaForQuestionAnswering;$.DebertaForSequenceClassification;$.DebertaForTokenClassification;$.DebertaModel;$.DebertaPreTrainedModel;$.DebertaTokenizer;$.DebertaV2ForMaskedLM;$.DebertaV2ForQuestionAnswering;$.DebertaV2ForSequenceClassification;$.DebertaV2ForTokenClassification;$.DebertaV2Model;$.DebertaV2PreTrainedModel;$.DebertaV2Tokenizer;$.DeiTFeatureExtractor;$.DeiTForImageClassification;$.DeiTModel;$.DeiTPreTrainedModel;$.DepthAnythingForDepthEstimation;$.DepthAnythingPreTrainedModel;$.DepthEstimationPipeline;$.DetrFeatureExtractor;$.DetrForObjectDetection;$.DetrForSegmentation;$.DetrModel;$.DetrObjectDetectionOutput;$.DetrPreTrainedModel;$.DetrSegmentationOutput;$.Dinov2ForImageClassification;$.Dinov2Model;$.Dinov2PreTrainedModel;$.DistilBertForMaskedLM;$.DistilBertForQuestionAnswering;$.DistilBertForSequenceClassification;$.DistilBertForTokenClassification;$.DistilBertModel;$.DistilBertPreTrainedModel;$.DistilBertTokenizer;$.DocumentQuestionAnsweringPipeline;$.DonutFeatureExtractor;$.DonutSwinModel;$.DonutSwinPreTrainedModel;$.EfficientNetForImageClassification;$.EfficientNetImageProcessor;$.EfficientNetModel;$.EfficientNetPreTrainedModel;$.ElectraForMaskedLM;$.ElectraForQuestionAnswering;$.ElectraForSequenceClassification;$.ElectraForTokenClassification;$.ElectraModel;$.ElectraPreTrainedModel;$.ElectraTokenizer;$.EosTokenCriteria;$.EsmForMaskedLM;$.EsmForSequenceClassification;$.EsmForTokenClassification;$.EsmModel;$.EsmPreTrainedModel;$.EsmTokenizer;$.FFT;$.FalconForCausalLM;$.FalconModel;$.FalconPreTrainedModel;$.FalconTokenizer;$.FastViTForImageClassification;$.FastViTModel;$.FastViTPreTrainedModel;$.FeatureExtractionPipeline;$.FeatureExtractor;$.FillMaskPipeline;$.Florence2ForConditionalGeneration;$.Florence2PreTrainedModel;$.Florence2Processor;$.GLPNFeatureExtractor;$.GLPNForDepthEstimation;$.GLPNModel;$.GLPNPreTrainedModel;$.GPT2LMHeadModel;$.GPT2Model;$.GPT2PreTrainedModel;$.GPT2Tokenizer;$.GPTBigCodeForCausalLM;$.GPTBigCodeModel;$.GPTBigCodePreTrainedModel;$.GPTJForCausalLM;$.GPTJModel;$.GPTJPreTrainedModel;$.GPTNeoForCausalLM;$.GPTNeoModel;$.GPTNeoPreTrainedModel;$.GPTNeoXForCausalLM;$.GPTNeoXModel;$.GPTNeoXPreTrainedModel;$.GPTNeoXTokenizer;$.Gemma2ForCausalLM;$.Gemma2Model;$.Gemma2PreTrainedModel;$.GemmaForCausalLM;$.GemmaModel;$.GemmaPreTrainedModel;$.GemmaTokenizer;$.Grok1Tokenizer;$.HerbertTokenizer;$.HubertForCTC;$.HubertForSequenceClassification;$.HubertModel;$.HubertPreTrainedModel;$.ImageClassificationPipeline;$.ImageFeatureExtractionPipeline;$.ImageFeatureExtractor;$.ImageMattingOutput;$.ImageSegmentationPipeline;$.ImageToImagePipeline;$.ImageToTextPipeline;$.InterruptableStoppingCriteria;$.LlamaForCausalLM;$.LlamaModel;$.LlamaPreTrainedModel;$.LlamaTokenizer;$.LlavaForConditionalGeneration;$.LlavaPreTrainedModel;$.LongT5ForConditionalGeneration;$.LongT5Model;$.LongT5PreTrainedModel;$.M2M100ForConditionalGeneration;$.M2M100Model;$.M2M100PreTrainedModel;$.M2M100Tokenizer;$.MBart50Tokenizer;$.MBartForCausalLM;$.MBartForConditionalGeneration;$.MBartForSequenceClassification;$.MBartModel;$.MBartPreTrainedModel;$.MBartTokenizer;$.MPNetForMaskedLM;$.MPNetForQuestionAnswering;$.MPNetForSequenceClassification;$.MPNetForTokenClassification;$.MPNetModel;$.MPNetPreTrainedModel;$.MPNetTokenizer;$.MT5ForConditionalGeneration;$.MT5Model;$.MT5PreTrainedModel;$.MarianMTModel;$.MarianModel;$.MarianPreTrainedModel;$.MarianTokenizer;$.MaskedLMOutput;$.MaxLengthCriteria;$.MistralForCausalLM;$.MistralModel;$.MistralPreTrainedModel;$.MobileBertForMaskedLM;$.MobileBertForQuestionAnswering;$.MobileBertForSequenceClassification;$.MobileBertModel;$.MobileBertPreTrainedModel;$.MobileBertTokenizer;$.MobileNetV1FeatureExtractor;$.MobileNetV1ForImageClassification;$.MobileNetV1Model;$.MobileNetV1PreTrainedModel;$.MobileNetV2FeatureExtractor;$.MobileNetV2ForImageClassification;$.MobileNetV2Model;$.MobileNetV2PreTrainedModel;$.MobileNetV3FeatureExtractor;$.MobileNetV3ForImageClassification;$.MobileNetV3Model;$.MobileNetV3PreTrainedModel;$.MobileNetV4FeatureExtractor;$.MobileNetV4ForImageClassification;$.MobileNetV4Model;$.MobileNetV4PreTrainedModel;$.MobileViTFeatureExtractor;$.MobileViTForImageClassification;$.MobileViTImageProcessor;$.MobileViTModel;$.MobileViTPreTrainedModel;$.MobileViTV2ForImageClassification;$.MobileViTV2Model;$.MobileViTV2PreTrainedModel;$.ModelOutput;$.Moondream1ForConditionalGeneration;$.MptForCausalLM;$.MptModel;$.MptPreTrainedModel;$.MusicgenForCausalLM;$.MusicgenForConditionalGeneration;$.MusicgenModel;$.MusicgenPreTrainedModel;$.NllbTokenizer;$.NomicBertModel;$.NomicBertPreTrainedModel;$.NougatImageProcessor;$.NougatTokenizer;$.OPTForCausalLM;$.OPTModel;$.OPTPreTrainedModel;$.ObjectDetectionPipeline;$.OpenELMForCausalLM;$.OpenELMModel;$.OpenELMPreTrainedModel;$.OwlViTFeatureExtractor;$.OwlViTForObjectDetection;$.OwlViTModel;$.OwlViTPreTrainedModel;$.OwlViTProcessor;$.Owlv2ForObjectDetection;$.Owlv2ImageProcessor;$.Owlv2Model;$.Owlv2PreTrainedModel;$.Phi3ForCausalLM;$.Phi3Model;$.Phi3PreTrainedModel;$.PhiForCausalLM;$.PhiModel;$.PhiPreTrainedModel;$.Pipeline;$.PreTrainedModel;$.PreTrainedTokenizer;$.PretrainedConfig;$.PretrainedMixin;$.Processor;$.PyAnnoteFeatureExtractor;$.PyAnnoteForAudioFrameClassification;$.PyAnnoteModel;$.PyAnnotePreTrainedModel;$.PyAnnoteProcessor;$.QuestionAnsweringModelOutput;$.QuestionAnsweringPipeline;$.Qwen2ForCausalLM;$.Qwen2Model;$.Qwen2PreTrainedModel;$.Qwen2Tokenizer;$.RTDetrForObjectDetection;$.RTDetrImageProcessor;$.RTDetrModel;$.RTDetrObjectDetectionOutput;$.RTDetrPreTrainedModel;var v1=$.RawImage;$.ResNetForImageClassification;$.ResNetModel;$.ResNetPreTrainedModel;$.RoFormerForMaskedLM;$.RoFormerForQuestionAnswering;$.RoFormerForSequenceClassification;$.RoFormerForTokenClassification;$.RoFormerModel;$.RoFormerPreTrainedModel;$.RoFormerTokenizer;$.RobertaForMaskedLM;$.RobertaForQuestionAnswering;$.RobertaForSequenceClassification;$.RobertaForTokenClassification;$.RobertaModel;$.RobertaPreTrainedModel;$.RobertaTokenizer;$.SamImageProcessor;$.SamImageSegmentationOutput;$.SamModel;$.SamPreTrainedModel;$.SamProcessor;$.SeamlessM4TFeatureExtractor;$.SegformerFeatureExtractor;$.SegformerForImageClassification;$.SegformerForSemanticSegmentation;$.SegformerModel;$.SegformerPreTrainedModel;$.Seq2SeqLMOutput;$.SequenceClassifierOutput;$.SiglipImageProcessor;$.SiglipModel;$.SiglipPreTrainedModel;$.SiglipTextModel;$.SiglipTokenizer;$.SiglipVisionModel;$.SpeechT5FeatureExtractor;$.SpeechT5ForSpeechToText;$.SpeechT5ForTextToSpeech;$.SpeechT5HifiGan;$.SpeechT5Model;$.SpeechT5PreTrainedModel;$.SpeechT5Processor;$.SpeechT5Tokenizer;$.SqueezeBertForMaskedLM;$.SqueezeBertForQuestionAnswering;$.SqueezeBertForSequenceClassification;$.SqueezeBertModel;$.SqueezeBertPreTrainedModel;$.SqueezeBertTokenizer;$.StableLmForCausalLM;$.StableLmModel;$.StableLmPreTrainedModel;$.Starcoder2ForCausalLM;$.Starcoder2Model;$.Starcoder2PreTrainedModel;$.StoppingCriteria;$.StoppingCriteriaList;$.SummarizationPipeline;$.Swin2SRForImageSuperResolution;$.Swin2SRImageProcessor;$.Swin2SRModel;$.Swin2SRPreTrainedModel;$.SwinForImageClassification;$.SwinModel;$.SwinPreTrainedModel;$.T5ForConditionalGeneration;$.T5Model;$.T5PreTrainedModel;$.T5Tokenizer;$.TableTransformerForObjectDetection;$.TableTransformerModel;$.TableTransformerObjectDetectionOutput;$.TableTransformerPreTrainedModel;$.Tensor;$.Text2TextGenerationPipeline;$.TextClassificationPipeline;$.TextGenerationPipeline;$.TextStreamer;$.TextToAudioPipeline;$.TokenClassificationPipeline;$.TokenClassifierOutput;$.TokenizerModel;$.TrOCRForCausalLM;$.TrOCRPreTrainedModel;$.TranslationPipeline;$.UniSpeechForCTC;$.UniSpeechForSequenceClassification;$.UniSpeechModel;$.UniSpeechPreTrainedModel;$.UniSpeechSatForAudioFrameClassification;$.UniSpeechSatForCTC;$.UniSpeechSatForSequenceClassification;$.UniSpeechSatModel;$.UniSpeechSatPreTrainedModel;$.ViTFeatureExtractor;$.ViTForImageClassification;$.ViTImageProcessor;$.ViTModel;$.ViTPreTrainedModel;$.VisionEncoderDecoderModel;$.VitMatteForImageMatting;$.VitMatteImageProcessor;$.VitMattePreTrainedModel;$.VitsModel;$.VitsModelOutput;$.VitsPreTrainedModel;$.VitsTokenizer;$.Wav2Vec2BertForCTC;$.Wav2Vec2BertForSequenceClassification;$.Wav2Vec2BertModel;$.Wav2Vec2BertPreTrainedModel;$.Wav2Vec2CTCTokenizer;$.Wav2Vec2FeatureExtractor;$.Wav2Vec2ForAudioFrameClassification;$.Wav2Vec2ForCTC;$.Wav2Vec2ForSequenceClassification;$.Wav2Vec2Model;$.Wav2Vec2PreTrainedModel;$.Wav2Vec2ProcessorWithLM;$.WavLMForAudioFrameClassification;$.WavLMForCTC;$.WavLMForSequenceClassification;$.WavLMForXVector;$.WavLMModel;$.WavLMPreTrainedModel;$.WeSpeakerFeatureExtractor;$.WeSpeakerResNetModel;$.WeSpeakerResNetPreTrainedModel;$.WhisperFeatureExtractor;$.WhisperForConditionalGeneration;$.WhisperModel;$.WhisperPreTrainedModel;$.WhisperProcessor;$.WhisperTextStreamer;$.WhisperTokenizer;$.XLMForQuestionAnswering;$.XLMForSequenceClassification;$.XLMForTokenClassification;$.XLMModel;$.XLMPreTrainedModel;$.XLMRobertaForMaskedLM;$.XLMRobertaForQuestionAnswering;$.XLMRobertaForSequenceClassification;$.XLMRobertaForTokenClassification;$.XLMRobertaModel;$.XLMRobertaPreTrainedModel;$.XLMRobertaTokenizer;$.XLMTokenizer;$.XLMWithLMHeadModel;$.XVectorOutput;$.YolosFeatureExtractor;$.YolosForObjectDetection;$.YolosModel;$.YolosObjectDetectionOutput;$.YolosPreTrainedModel;$.ZeroShotAudioClassificationPipeline;$.ZeroShotClassificationPipeline;$.ZeroShotImageClassificationPipeline;$.ZeroShotObjectDetectionPipeline;$.bankers_round;$.cat;$.cos_sim;$.dot;$.dynamic_time_warping;var uE=$.env;$.full;$.full_like;$.getKeyValueShapes;$.hamming;$.hanning;$.interpolate;$.interpolate_4d;$.interpolate_data;$.is_chinese_char;$.layer_norm;$.log_softmax;$.magnitude;$.matmul;$.max;$.mean;$.mean_pooling;$.medianFilter;$.mel_filter_bank;$.min;$.ones;$.ones_like;$.permute;$.permute_data;$.pipeline;$.quantize_embeddings;$.read_audio;$.rfft;$.round;$.softmax;$.spectrogram;$.stack;$.std_mean;$.topk;$.window_function;$.zeros;$.zeros_like;function uh(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Y2={exports:{}};/*! + +JSZip v3.10.1 - A JavaScript class for generating and reading zip files +<http://stuartk.com/jszip> + +(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com> +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/main/LICENSE +*/(function(e,t){(function(n){e.exports=n()})(function(){return function n(o,a,l){function f(g,M){if(!a[g]){if(!o[g]){var w=typeof uh=="function"&&uh;if(!M&&w)return w(g,!0);if(_)return _(g,!0);var C=new Error("Cannot find module '"+g+"'");throw C.code="MODULE_NOT_FOUND",C}var k=a[g]={exports:{}};o[g][0].call(k.exports,function(z){var S=o[g][1][z];return f(S||z)},k,k.exports,n,o,a,l)}return a[g].exports}for(var _=typeof uh=="function"&&uh,h=0;h<l.length;h++)f(l[h]);return f}({1:[function(n,o,a){var l=n("./utils"),f=n("./support"),_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";a.encode=function(h){for(var g,M,w,C,k,z,S,P=[],y=0,x=h.length,I=x,U=l.getTypeOf(h)!=="string";y<h.length;)I=x-y,w=U?(g=h[y++],M=y<x?h[y++]:0,y<x?h[y++]:0):(g=h.charCodeAt(y++),M=y<x?h.charCodeAt(y++):0,y<x?h.charCodeAt(y++):0),C=g>>2,k=(3&g)<<4|M>>4,z=1<I?(15&M)<<2|w>>6:64,S=2<I?63&w:64,P.push(_.charAt(C)+_.charAt(k)+_.charAt(z)+_.charAt(S));return P.join("")},a.decode=function(h){var g,M,w,C,k,z,S=0,P=0,y="data:";if(h.substr(0,y.length)===y)throw new Error("Invalid base64 input, it looks like a data url.");var x,I=3*(h=h.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(h.charAt(h.length-1)===_.charAt(64)&&I--,h.charAt(h.length-2)===_.charAt(64)&&I--,I%1!=0)throw new Error("Invalid base64 input, bad content length.");for(x=f.uint8array?new Uint8Array(0|I):new Array(0|I);S<h.length;)g=_.indexOf(h.charAt(S++))<<2|(C=_.indexOf(h.charAt(S++)))>>4,M=(15&C)<<4|(k=_.indexOf(h.charAt(S++)))>>2,w=(3&k)<<6|(z=_.indexOf(h.charAt(S++))),x[P++]=g,k!==64&&(x[P++]=M),z!==64&&(x[P++]=w);return x}},{"./support":30,"./utils":32}],2:[function(n,o,a){var l=n("./external"),f=n("./stream/DataWorker"),_=n("./stream/Crc32Probe"),h=n("./stream/DataLengthProbe");function g(M,w,C,k,z){this.compressedSize=M,this.uncompressedSize=w,this.crc32=C,this.compression=k,this.compressedContent=z}g.prototype={getContentWorker:function(){var M=new f(l.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new h("data_length")),w=this;return M.on("end",function(){if(this.streamInfo.data_length!==w.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),M},getCompressedWorker:function(){return new f(l.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},g.createWorkerFrom=function(M,w,C){return M.pipe(new _).pipe(new h("uncompressedSize")).pipe(w.compressWorker(C)).pipe(new h("compressedSize")).withStreamInfo("compression",w)},o.exports=g},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,o,a){var l=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new l("STORE compression")},uncompressWorker:function(){return new l("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,o,a){var l=n("./utils"),f=function(){for(var _,h=[],g=0;g<256;g++){_=g;for(var M=0;M<8;M++)_=1&_?3988292384^_>>>1:_>>>1;h[g]=_}return h}();o.exports=function(_,h){return _!==void 0&&_.length?l.getTypeOf(_)!=="string"?function(g,M,w,C){var k=f,z=C+w;g^=-1;for(var S=C;S<z;S++)g=g>>>8^k[255&(g^M[S])];return-1^g}(0|h,_,_.length,0):function(g,M,w,C){var k=f,z=C+w;g^=-1;for(var S=C;S<z;S++)g=g>>>8^k[255&(g^M.charCodeAt(S))];return-1^g}(0|h,_,_.length,0):0}},{"./utils":32}],5:[function(n,o,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,o,a){var l=null;l=typeof Promise<"u"?Promise:n("lie"),o.exports={Promise:l}},{lie:37}],7:[function(n,o,a){var l=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",f=n("pako"),_=n("./utils"),h=n("./stream/GenericWorker"),g=l?"uint8array":"array";function M(w,C){h.call(this,"FlateWorker/"+w),this._pako=null,this._pakoAction=w,this._pakoOptions=C,this.meta={}}a.magic="\b\0",_.inherits(M,h),M.prototype.processChunk=function(w){this.meta=w.meta,this._pako===null&&this._createPako(),this._pako.push(_.transformTo(g,w.data),!1)},M.prototype.flush=function(){h.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},M.prototype.cleanUp=function(){h.prototype.cleanUp.call(this),this._pako=null},M.prototype._createPako=function(){this._pako=new f[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var w=this;this._pako.onData=function(C){w.push({data:C,meta:w.meta})}},a.compressWorker=function(w){return new M("Deflate",w)},a.uncompressWorker=function(){return new M("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,o,a){function l(k,z){var S,P="";for(S=0;S<z;S++)P+=String.fromCharCode(255&k),k>>>=8;return P}function f(k,z,S,P,y,x){var I,U,O=k.file,N=k.compression,j=x!==g.utf8encode,D=_.transformTo("string",x(O.name)),Y=_.transformTo("string",g.utf8encode(O.name)),de=O.comment,Ce=_.transformTo("string",x(de)),ee=_.transformTo("string",g.utf8encode(de)),ye=Y.length!==O.name.length,R=ee.length!==de.length,Me="",Qe="",ge="",Q=O.dir,ae=O.date,Se={crc32:0,compressedSize:0,uncompressedSize:0};z&&!S||(Se.crc32=k.crc32,Se.compressedSize=k.compressedSize,Se.uncompressedSize=k.uncompressedSize);var X=0;z&&(X|=8),j||!ye&&!R||(X|=2048);var me=0,Ke=0;Q&&(me|=16),y==="UNIX"?(Ke=798,me|=function(Be,We){var ot=Be;return Be||(ot=We?16893:33204),(65535&ot)<<16}(O.unixPermissions,Q)):(Ke=20,me|=function(Be){return 63&(Be||0)}(O.dosPermissions)),I=ae.getUTCHours(),I<<=6,I|=ae.getUTCMinutes(),I<<=5,I|=ae.getUTCSeconds()/2,U=ae.getUTCFullYear()-1980,U<<=4,U|=ae.getUTCMonth()+1,U<<=5,U|=ae.getUTCDate(),ye&&(Qe=l(1,1)+l(M(D),4)+Y,Me+="up"+l(Qe.length,2)+Qe),R&&(ge=l(1,1)+l(M(Ce),4)+ee,Me+="uc"+l(ge.length,2)+ge);var De="";return De+=` +\0`,De+=l(X,2),De+=N.magic,De+=l(I,2),De+=l(U,2),De+=l(Se.crc32,4),De+=l(Se.compressedSize,4),De+=l(Se.uncompressedSize,4),De+=l(D.length,2),De+=l(Me.length,2),{fileRecord:w.LOCAL_FILE_HEADER+De+D+Me,dirRecord:w.CENTRAL_FILE_HEADER+l(Ke,2)+De+l(Ce.length,2)+"\0\0\0\0"+l(me,4)+l(P,4)+D+Me+Ce}}var _=n("../utils"),h=n("../stream/GenericWorker"),g=n("../utf8"),M=n("../crc32"),w=n("../signature");function C(k,z,S,P){h.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=z,this.zipPlatform=S,this.encodeFileName=P,this.streamFiles=k,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}_.inherits(C,h),C.prototype.push=function(k){var z=k.meta.percent||0,S=this.entriesCount,P=this._sources.length;this.accumulate?this.contentBuffer.push(k):(this.bytesWritten+=k.data.length,h.prototype.push.call(this,{data:k.data,meta:{currentFile:this.currentFile,percent:S?(z+100*(S-P-1))/S:100}}))},C.prototype.openedSource=function(k){this.currentSourceOffset=this.bytesWritten,this.currentFile=k.file.name;var z=this.streamFiles&&!k.file.dir;if(z){var S=f(k,z,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:S.fileRecord,meta:{percent:0}})}else this.accumulate=!0},C.prototype.closedSource=function(k){this.accumulate=!1;var z=this.streamFiles&&!k.file.dir,S=f(k,z,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(S.dirRecord),z)this.push({data:function(P){return w.DATA_DESCRIPTOR+l(P.crc32,4)+l(P.compressedSize,4)+l(P.uncompressedSize,4)}(k),meta:{percent:100}});else for(this.push({data:S.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},C.prototype.flush=function(){for(var k=this.bytesWritten,z=0;z<this.dirRecords.length;z++)this.push({data:this.dirRecords[z],meta:{percent:100}});var S=this.bytesWritten-k,P=function(y,x,I,U,O){var N=_.transformTo("string",O(U));return w.CENTRAL_DIRECTORY_END+"\0\0\0\0"+l(y,2)+l(y,2)+l(x,4)+l(I,4)+l(N.length,2)+N}(this.dirRecords.length,S,k,this.zipComment,this.encodeFileName);this.push({data:P,meta:{percent:100}})},C.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},C.prototype.registerPrevious=function(k){this._sources.push(k);var z=this;return k.on("data",function(S){z.processChunk(S)}),k.on("end",function(){z.closedSource(z.previous.streamInfo),z._sources.length?z.prepareNextSource():z.end()}),k.on("error",function(S){z.error(S)}),this},C.prototype.resume=function(){return!!h.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},C.prototype.error=function(k){var z=this._sources;if(!h.prototype.error.call(this,k))return!1;for(var S=0;S<z.length;S++)try{z[S].error(k)}catch{}return!0},C.prototype.lock=function(){h.prototype.lock.call(this);for(var k=this._sources,z=0;z<k.length;z++)k[z].lock()},o.exports=C},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,o,a){var l=n("../compressions"),f=n("./ZipFileWorker");a.generateWorker=function(_,h,g){var M=new f(h.streamFiles,g,h.platform,h.encodeFileName),w=0;try{_.forEach(function(C,k){w++;var z=function(x,I){var U=x||I,O=l[U];if(!O)throw new Error(U+" is not a valid compression method !");return O}(k.options.compression,h.compression),S=k.options.compressionOptions||h.compressionOptions||{},P=k.dir,y=k.date;k._compressWorker(z,S).withStreamInfo("file",{name:C,dir:P,date:y,comment:k.comment||"",unixPermissions:k.unixPermissions,dosPermissions:k.dosPermissions}).pipe(M)}),M.entriesCount=w}catch(C){M.error(C)}return M}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(n,o,a){function l(){if(!(this instanceof l))return new l;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var f=new l;for(var _ in this)typeof this[_]!="function"&&(f[_]=this[_]);return f}}(l.prototype=n("./object")).loadAsync=n("./load"),l.support=n("./support"),l.defaults=n("./defaults"),l.version="3.10.1",l.loadAsync=function(f,_){return new l().loadAsync(f,_)},l.external=n("./external"),o.exports=l},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(n,o,a){var l=n("./utils"),f=n("./external"),_=n("./utf8"),h=n("./zipEntries"),g=n("./stream/Crc32Probe"),M=n("./nodejsUtils");function w(C){return new f.Promise(function(k,z){var S=C.decompressed.getContentWorker().pipe(new g);S.on("error",function(P){z(P)}).on("end",function(){S.streamInfo.crc32!==C.decompressed.crc32?z(new Error("Corrupted zip : CRC32 mismatch")):k()}).resume()})}o.exports=function(C,k){var z=this;return k=l.extend(k||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:_.utf8decode}),M.isNode&&M.isStream(C)?f.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):l.prepareContent("the loaded zip file",C,!0,k.optimizedBinaryString,k.base64).then(function(S){var P=new h(k);return P.load(S),P}).then(function(S){var P=[f.Promise.resolve(S)],y=S.files;if(k.checkCRC32)for(var x=0;x<y.length;x++)P.push(w(y[x]));return f.Promise.all(P)}).then(function(S){for(var P=S.shift(),y=P.files,x=0;x<y.length;x++){var I=y[x],U=I.fileNameStr,O=l.resolve(I.fileNameStr);z.file(O,I.decompressed,{binary:!0,optimizedBinaryString:!0,date:I.date,dir:I.dir,comment:I.fileCommentStr.length?I.fileCommentStr:null,unixPermissions:I.unixPermissions,dosPermissions:I.dosPermissions,createFolders:k.createFolders}),I.dir||(z.file(O).unsafeOriginalName=U)}return P.zipComment.length&&(z.comment=P.zipComment),z})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(n,o,a){var l=n("../utils"),f=n("../stream/GenericWorker");function _(h,g){f.call(this,"Nodejs stream input adapter for "+h),this._upstreamEnded=!1,this._bindStream(g)}l.inherits(_,f),_.prototype._bindStream=function(h){var g=this;(this._stream=h).pause(),h.on("data",function(M){g.push({data:M,meta:{percent:0}})}).on("error",function(M){g.isPaused?this.generatedError=M:g.error(M)}).on("end",function(){g.isPaused?g._upstreamEnded=!0:g.end()})},_.prototype.pause=function(){return!!f.prototype.pause.call(this)&&(this._stream.pause(),!0)},_.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},o.exports=_},{"../stream/GenericWorker":28,"../utils":32}],13:[function(n,o,a){var l=n("readable-stream").Readable;function f(_,h,g){l.call(this,h),this._helper=_;var M=this;_.on("data",function(w,C){M.push(w)||M._helper.pause(),g&&g(C)}).on("error",function(w){M.emit("error",w)}).on("end",function(){M.push(null)})}n("../utils").inherits(f,l),f.prototype._read=function(){this._helper.resume()},o.exports=f},{"../utils":32,"readable-stream":16}],14:[function(n,o,a){o.exports={isNode:typeof Buffer<"u",newBufferFrom:function(l,f){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(l,f);if(typeof l=="number")throw new Error('The "data" argument must not be a number');return new Buffer(l,f)},allocBuffer:function(l){if(Buffer.alloc)return Buffer.alloc(l);var f=new Buffer(l);return f.fill(0),f},isBuffer:function(l){return Buffer.isBuffer(l)},isStream:function(l){return l&&typeof l.on=="function"&&typeof l.pause=="function"&&typeof l.resume=="function"}}},{}],15:[function(n,o,a){function l(O,N,j){var D,Y=_.getTypeOf(N),de=_.extend(j||{},M);de.date=de.date||new Date,de.compression!==null&&(de.compression=de.compression.toUpperCase()),typeof de.unixPermissions=="string"&&(de.unixPermissions=parseInt(de.unixPermissions,8)),de.unixPermissions&&16384&de.unixPermissions&&(de.dir=!0),de.dosPermissions&&16&de.dosPermissions&&(de.dir=!0),de.dir&&(O=y(O)),de.createFolders&&(D=P(O))&&x.call(this,D,!0);var Ce=Y==="string"&&de.binary===!1&&de.base64===!1;j&&j.binary!==void 0||(de.binary=!Ce),(N instanceof w&&N.uncompressedSize===0||de.dir||!N||N.length===0)&&(de.base64=!1,de.binary=!0,N="",de.compression="STORE",Y="string");var ee=null;ee=N instanceof w||N instanceof h?N:z.isNode&&z.isStream(N)?new S(O,N):_.prepareContent(O,N,de.binary,de.optimizedBinaryString,de.base64);var ye=new C(O,ee,de);this.files[O]=ye}var f=n("./utf8"),_=n("./utils"),h=n("./stream/GenericWorker"),g=n("./stream/StreamHelper"),M=n("./defaults"),w=n("./compressedObject"),C=n("./zipObject"),k=n("./generate"),z=n("./nodejsUtils"),S=n("./nodejs/NodejsStreamInputAdapter"),P=function(O){O.slice(-1)==="/"&&(O=O.substring(0,O.length-1));var N=O.lastIndexOf("/");return 0<N?O.substring(0,N):""},y=function(O){return O.slice(-1)!=="/"&&(O+="/"),O},x=function(O,N){return N=N!==void 0?N:M.createFolders,O=y(O),this.files[O]||l.call(this,O,null,{dir:!0,createFolders:N}),this.files[O]};function I(O){return Object.prototype.toString.call(O)==="[object RegExp]"}var U={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(O){var N,j,D;for(N in this.files)D=this.files[N],(j=N.slice(this.root.length,N.length))&&N.slice(0,this.root.length)===this.root&&O(j,D)},filter:function(O){var N=[];return this.forEach(function(j,D){O(j,D)&&N.push(D)}),N},file:function(O,N,j){if(arguments.length!==1)return O=this.root+O,l.call(this,O,N,j),this;if(I(O)){var D=O;return this.filter(function(de,Ce){return!Ce.dir&&D.test(de)})}var Y=this.files[this.root+O];return Y&&!Y.dir?Y:null},folder:function(O){if(!O)return this;if(I(O))return this.filter(function(Y,de){return de.dir&&O.test(Y)});var N=this.root+O,j=x.call(this,N),D=this.clone();return D.root=j.name,D},remove:function(O){O=this.root+O;var N=this.files[O];if(N||(O.slice(-1)!=="/"&&(O+="/"),N=this.files[O]),N&&!N.dir)delete this.files[O];else for(var j=this.filter(function(Y,de){return de.name.slice(0,O.length)===O}),D=0;D<j.length;D++)delete this.files[j[D].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(O){var N,j={};try{if((j=_.extend(O||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:f.utf8encode})).type=j.type.toLowerCase(),j.compression=j.compression.toUpperCase(),j.type==="binarystring"&&(j.type="string"),!j.type)throw new Error("No output type specified.");_.checkSupport(j.type),j.platform!=="darwin"&&j.platform!=="freebsd"&&j.platform!=="linux"&&j.platform!=="sunos"||(j.platform="UNIX"),j.platform==="win32"&&(j.platform="DOS");var D=j.comment||this.comment||"";N=k.generateWorker(this,j,D)}catch(Y){(N=new h("error")).error(Y)}return new g(N,j.type||"string",j.mimeType)},generateAsync:function(O,N){return this.generateInternalStream(O).accumulate(N)},generateNodeStream:function(O,N){return(O=O||{}).type||(O.type="nodebuffer"),this.generateInternalStream(O).toNodejsStream(N)}};o.exports=U},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(n,o,a){o.exports=n("stream")},{stream:void 0}],17:[function(n,o,a){var l=n("./DataReader");function f(_){l.call(this,_);for(var h=0;h<this.data.length;h++)_[h]=255&_[h]}n("../utils").inherits(f,l),f.prototype.byteAt=function(_){return this.data[this.zero+_]},f.prototype.lastIndexOfSignature=function(_){for(var h=_.charCodeAt(0),g=_.charCodeAt(1),M=_.charCodeAt(2),w=_.charCodeAt(3),C=this.length-4;0<=C;--C)if(this.data[C]===h&&this.data[C+1]===g&&this.data[C+2]===M&&this.data[C+3]===w)return C-this.zero;return-1},f.prototype.readAndCheckSignature=function(_){var h=_.charCodeAt(0),g=_.charCodeAt(1),M=_.charCodeAt(2),w=_.charCodeAt(3),C=this.readData(4);return h===C[0]&&g===C[1]&&M===C[2]&&w===C[3]},f.prototype.readData=function(_){if(this.checkOffset(_),_===0)return[];var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./DataReader":18}],18:[function(n,o,a){var l=n("../utils");function f(_){this.data=_,this.length=_.length,this.index=0,this.zero=0}f.prototype={checkOffset:function(_){this.checkIndex(this.index+_)},checkIndex:function(_){if(this.length<this.zero+_||_<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+_+"). Corrupted zip ?")},setIndex:function(_){this.checkIndex(_),this.index=_},skip:function(_){this.setIndex(this.index+_)},byteAt:function(){},readInt:function(_){var h,g=0;for(this.checkOffset(_),h=this.index+_-1;h>=this.index;h--)g=(g<<8)+this.byteAt(h);return this.index+=_,g},readString:function(_){return l.transformTo("string",this.readData(_))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var _=this.readInt(4);return new Date(Date.UTC(1980+(_>>25&127),(_>>21&15)-1,_>>16&31,_>>11&31,_>>5&63,(31&_)<<1))}},o.exports=f},{"../utils":32}],19:[function(n,o,a){var l=n("./Uint8ArrayReader");function f(_){l.call(this,_)}n("../utils").inherits(f,l),f.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,o,a){var l=n("./DataReader");function f(_){l.call(this,_)}n("../utils").inherits(f,l),f.prototype.byteAt=function(_){return this.data.charCodeAt(this.zero+_)},f.prototype.lastIndexOfSignature=function(_){return this.data.lastIndexOf(_)-this.zero},f.prototype.readAndCheckSignature=function(_){return _===this.readData(4)},f.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./DataReader":18}],21:[function(n,o,a){var l=n("./ArrayReader");function f(_){l.call(this,_)}n("../utils").inherits(f,l),f.prototype.readData=function(_){if(this.checkOffset(_),_===0)return new Uint8Array(0);var h=this.data.subarray(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./ArrayReader":17}],22:[function(n,o,a){var l=n("../utils"),f=n("../support"),_=n("./ArrayReader"),h=n("./StringReader"),g=n("./NodeBufferReader"),M=n("./Uint8ArrayReader");o.exports=function(w){var C=l.getTypeOf(w);return l.checkSupport(C),C!=="string"||f.uint8array?C==="nodebuffer"?new g(w):f.uint8array?new M(l.transformTo("uint8array",w)):new _(l.transformTo("array",w)):new h(w)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,o,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,o,a){var l=n("./GenericWorker"),f=n("../utils");function _(h){l.call(this,"ConvertWorker to "+h),this.destType=h}f.inherits(_,l),_.prototype.processChunk=function(h){this.push({data:f.transformTo(this.destType,h.data),meta:h.meta})},o.exports=_},{"../utils":32,"./GenericWorker":28}],25:[function(n,o,a){var l=n("./GenericWorker"),f=n("../crc32");function _(){l.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(_,l),_.prototype.processChunk=function(h){this.streamInfo.crc32=f(h.data,this.streamInfo.crc32||0),this.push(h)},o.exports=_},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,o,a){var l=n("../utils"),f=n("./GenericWorker");function _(h){f.call(this,"DataLengthProbe for "+h),this.propName=h,this.withStreamInfo(h,0)}l.inherits(_,f),_.prototype.processChunk=function(h){if(h){var g=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=g+h.data.length}f.prototype.processChunk.call(this,h)},o.exports=_},{"../utils":32,"./GenericWorker":28}],27:[function(n,o,a){var l=n("../utils"),f=n("./GenericWorker");function _(h){f.call(this,"DataWorker");var g=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,h.then(function(M){g.dataIsReady=!0,g.data=M,g.max=M&&M.length||0,g.type=l.getTypeOf(M),g.isPaused||g._tickAndRepeat()},function(M){g.error(M)})}l.inherits(_,f),_.prototype.cleanUp=function(){f.prototype.cleanUp.call(this),this.data=null},_.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,l.delay(this._tickAndRepeat,[],this)),!0)},_.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(l.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},_.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var h=null,g=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":h=this.data.substring(this.index,g);break;case"uint8array":h=this.data.subarray(this.index,g);break;case"array":case"nodebuffer":h=this.data.slice(this.index,g)}return this.index=g,this.push({data:h,meta:{percent:this.max?this.index/this.max*100:0}})},o.exports=_},{"../utils":32,"./GenericWorker":28}],28:[function(n,o,a){function l(f){this.name=f||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}l.prototype={push:function(f){this.emit("data",f)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(f){this.emit("error",f)}return!0},error:function(f){return!this.isFinished&&(this.isPaused?this.generatedError=f:(this.isFinished=!0,this.emit("error",f),this.previous&&this.previous.error(f),this.cleanUp()),!0)},on:function(f,_){return this._listeners[f].push(_),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(f,_){if(this._listeners[f])for(var h=0;h<this._listeners[f].length;h++)this._listeners[f][h].call(this,_)},pipe:function(f){return f.registerPrevious(this)},registerPrevious:function(f){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=f.streamInfo,this.mergeStreamInfo(),this.previous=f;var _=this;return f.on("data",function(h){_.processChunk(h)}),f.on("end",function(){_.end()}),f.on("error",function(h){_.error(h)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var f=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),f=!0),this.previous&&this.previous.resume(),!f},flush:function(){},processChunk:function(f){this.push(f)},withStreamInfo:function(f,_){return this.extraStreamInfo[f]=_,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var f in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,f)&&(this.streamInfo[f]=this.extraStreamInfo[f])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var f="Worker "+this.name;return this.previous?this.previous+" -> "+f:f}},o.exports=l},{}],29:[function(n,o,a){var l=n("../utils"),f=n("./ConvertWorker"),_=n("./GenericWorker"),h=n("../base64"),g=n("../support"),M=n("../external"),w=null;if(g.nodestream)try{w=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function C(z,S){return new M.Promise(function(P,y){var x=[],I=z._internalType,U=z._outputType,O=z._mimeType;z.on("data",function(N,j){x.push(N),S&&S(j)}).on("error",function(N){x=[],y(N)}).on("end",function(){try{var N=function(j,D,Y){switch(j){case"blob":return l.newBlob(l.transformTo("arraybuffer",D),Y);case"base64":return h.encode(D);default:return l.transformTo(j,D)}}(U,function(j,D){var Y,de=0,Ce=null,ee=0;for(Y=0;Y<D.length;Y++)ee+=D[Y].length;switch(j){case"string":return D.join("");case"array":return Array.prototype.concat.apply([],D);case"uint8array":for(Ce=new Uint8Array(ee),Y=0;Y<D.length;Y++)Ce.set(D[Y],de),de+=D[Y].length;return Ce;case"nodebuffer":return Buffer.concat(D);default:throw new Error("concat : unsupported type '"+j+"'")}}(I,x),O);P(N)}catch(j){y(j)}x=[]}).resume()})}function k(z,S,P){var y=S;switch(S){case"blob":case"arraybuffer":y="uint8array";break;case"base64":y="string"}try{this._internalType=y,this._outputType=S,this._mimeType=P,l.checkSupport(y),this._worker=z.pipe(new f(y)),z.lock()}catch(x){this._worker=new _("error"),this._worker.error(x)}}k.prototype={accumulate:function(z){return C(this,z)},on:function(z,S){var P=this;return z==="data"?this._worker.on(z,function(y){S.call(P,y.data,y.meta)}):this._worker.on(z,function(){l.delay(S,arguments,P)}),this},resume:function(){return l.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(z){if(l.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new w(this,{objectMode:this._outputType!=="nodebuffer"},z)}},o.exports=k},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(n,o,a){if(a.base64=!0,a.array=!0,a.string=!0,a.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",a.nodebuffer=typeof Buffer<"u",a.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")a.blob=!1;else{var l=new ArrayBuffer(0);try{a.blob=new Blob([l],{type:"application/zip"}).size===0}catch{try{var f=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);f.append(l),a.blob=f.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,o,a){for(var l=n("./utils"),f=n("./support"),_=n("./nodejsUtils"),h=n("./stream/GenericWorker"),g=new Array(256),M=0;M<256;M++)g[M]=252<=M?6:248<=M?5:240<=M?4:224<=M?3:192<=M?2:1;g[254]=g[254]=1;function w(){h.call(this,"utf-8 decode"),this.leftOver=null}function C(){h.call(this,"utf-8 encode")}a.utf8encode=function(k){return f.nodebuffer?_.newBufferFrom(k,"utf-8"):function(z){var S,P,y,x,I,U=z.length,O=0;for(x=0;x<U;x++)(64512&(P=z.charCodeAt(x)))==55296&&x+1<U&&(64512&(y=z.charCodeAt(x+1)))==56320&&(P=65536+(P-55296<<10)+(y-56320),x++),O+=P<128?1:P<2048?2:P<65536?3:4;for(S=f.uint8array?new Uint8Array(O):new Array(O),x=I=0;I<O;x++)(64512&(P=z.charCodeAt(x)))==55296&&x+1<U&&(64512&(y=z.charCodeAt(x+1)))==56320&&(P=65536+(P-55296<<10)+(y-56320),x++),P<128?S[I++]=P:(P<2048?S[I++]=192|P>>>6:(P<65536?S[I++]=224|P>>>12:(S[I++]=240|P>>>18,S[I++]=128|P>>>12&63),S[I++]=128|P>>>6&63),S[I++]=128|63&P);return S}(k)},a.utf8decode=function(k){return f.nodebuffer?l.transformTo("nodebuffer",k).toString("utf-8"):function(z){var S,P,y,x,I=z.length,U=new Array(2*I);for(S=P=0;S<I;)if((y=z[S++])<128)U[P++]=y;else if(4<(x=g[y]))U[P++]=65533,S+=x-1;else{for(y&=x===2?31:x===3?15:7;1<x&&S<I;)y=y<<6|63&z[S++],x--;1<x?U[P++]=65533:y<65536?U[P++]=y:(y-=65536,U[P++]=55296|y>>10&1023,U[P++]=56320|1023&y)}return U.length!==P&&(U.subarray?U=U.subarray(0,P):U.length=P),l.applyFromCharCode(U)}(k=l.transformTo(f.uint8array?"uint8array":"array",k))},l.inherits(w,h),w.prototype.processChunk=function(k){var z=l.transformTo(f.uint8array?"uint8array":"array",k.data);if(this.leftOver&&this.leftOver.length){if(f.uint8array){var S=z;(z=new Uint8Array(S.length+this.leftOver.length)).set(this.leftOver,0),z.set(S,this.leftOver.length)}else z=this.leftOver.concat(z);this.leftOver=null}var P=function(x,I){var U;for((I=I||x.length)>x.length&&(I=x.length),U=I-1;0<=U&&(192&x[U])==128;)U--;return U<0||U===0?I:U+g[x[U]]>I?U:I}(z),y=z;P!==z.length&&(f.uint8array?(y=z.subarray(0,P),this.leftOver=z.subarray(P,z.length)):(y=z.slice(0,P),this.leftOver=z.slice(P,z.length))),this.push({data:a.utf8decode(y),meta:k.meta})},w.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=w,l.inherits(C,h),C.prototype.processChunk=function(k){this.push({data:a.utf8encode(k.data),meta:k.meta})},a.Utf8EncodeWorker=C},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,o,a){var l=n("./support"),f=n("./base64"),_=n("./nodejsUtils"),h=n("./external");function g(S){return S}function M(S,P){for(var y=0;y<S.length;++y)P[y]=255&S.charCodeAt(y);return P}n("setimmediate"),a.newBlob=function(S,P){a.checkSupport("blob");try{return new Blob([S],{type:P})}catch{try{var y=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return y.append(S),y.getBlob(P)}catch{throw new Error("Bug : can't construct the Blob.")}}};var w={stringifyByChunk:function(S,P,y){var x=[],I=0,U=S.length;if(U<=y)return String.fromCharCode.apply(null,S);for(;I<U;)P==="array"||P==="nodebuffer"?x.push(String.fromCharCode.apply(null,S.slice(I,Math.min(I+y,U)))):x.push(String.fromCharCode.apply(null,S.subarray(I,Math.min(I+y,U)))),I+=y;return x.join("")},stringifyByChar:function(S){for(var P="",y=0;y<S.length;y++)P+=String.fromCharCode(S[y]);return P},applyCanBeUsed:{uint8array:function(){try{return l.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}}(),nodebuffer:function(){try{return l.nodebuffer&&String.fromCharCode.apply(null,_.allocBuffer(1)).length===1}catch{return!1}}()}};function C(S){var P=65536,y=a.getTypeOf(S),x=!0;if(y==="uint8array"?x=w.applyCanBeUsed.uint8array:y==="nodebuffer"&&(x=w.applyCanBeUsed.nodebuffer),x)for(;1<P;)try{return w.stringifyByChunk(S,y,P)}catch{P=Math.floor(P/2)}return w.stringifyByChar(S)}function k(S,P){for(var y=0;y<S.length;y++)P[y]=S[y];return P}a.applyFromCharCode=C;var z={};z.string={string:g,array:function(S){return M(S,new Array(S.length))},arraybuffer:function(S){return z.string.uint8array(S).buffer},uint8array:function(S){return M(S,new Uint8Array(S.length))},nodebuffer:function(S){return M(S,_.allocBuffer(S.length))}},z.array={string:C,array:g,arraybuffer:function(S){return new Uint8Array(S).buffer},uint8array:function(S){return new Uint8Array(S)},nodebuffer:function(S){return _.newBufferFrom(S)}},z.arraybuffer={string:function(S){return C(new Uint8Array(S))},array:function(S){return k(new Uint8Array(S),new Array(S.byteLength))},arraybuffer:g,uint8array:function(S){return new Uint8Array(S)},nodebuffer:function(S){return _.newBufferFrom(new Uint8Array(S))}},z.uint8array={string:C,array:function(S){return k(S,new Array(S.length))},arraybuffer:function(S){return S.buffer},uint8array:g,nodebuffer:function(S){return _.newBufferFrom(S)}},z.nodebuffer={string:C,array:function(S){return k(S,new Array(S.length))},arraybuffer:function(S){return z.nodebuffer.uint8array(S).buffer},uint8array:function(S){return k(S,new Uint8Array(S.length))},nodebuffer:g},a.transformTo=function(S,P){if(P=P||"",!S)return P;a.checkSupport(S);var y=a.getTypeOf(P);return z[y][S](P)},a.resolve=function(S){for(var P=S.split("/"),y=[],x=0;x<P.length;x++){var I=P[x];I==="."||I===""&&x!==0&&x!==P.length-1||(I===".."?y.pop():y.push(I))}return y.join("/")},a.getTypeOf=function(S){return typeof S=="string"?"string":Object.prototype.toString.call(S)==="[object Array]"?"array":l.nodebuffer&&_.isBuffer(S)?"nodebuffer":l.uint8array&&S instanceof Uint8Array?"uint8array":l.arraybuffer&&S instanceof ArrayBuffer?"arraybuffer":void 0},a.checkSupport=function(S){if(!l[S.toLowerCase()])throw new Error(S+" is not supported by this platform")},a.MAX_VALUE_16BITS=65535,a.MAX_VALUE_32BITS=-1,a.pretty=function(S){var P,y,x="";for(y=0;y<(S||"").length;y++)x+="\\x"+((P=S.charCodeAt(y))<16?"0":"")+P.toString(16).toUpperCase();return x},a.delay=function(S,P,y){setImmediate(function(){S.apply(y||null,P||[])})},a.inherits=function(S,P){function y(){}y.prototype=P.prototype,S.prototype=new y},a.extend=function(){var S,P,y={};for(S=0;S<arguments.length;S++)for(P in arguments[S])Object.prototype.hasOwnProperty.call(arguments[S],P)&&y[P]===void 0&&(y[P]=arguments[S][P]);return y},a.prepareContent=function(S,P,y,x,I){return h.Promise.resolve(P).then(function(U){return l.blob&&(U instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(U))!==-1)&&typeof FileReader<"u"?new h.Promise(function(O,N){var j=new FileReader;j.onload=function(D){O(D.target.result)},j.onerror=function(D){N(D.target.error)},j.readAsArrayBuffer(U)}):U}).then(function(U){var O=a.getTypeOf(U);return O?(O==="arraybuffer"?U=a.transformTo("uint8array",U):O==="string"&&(I?U=f.decode(U):y&&x!==!0&&(U=function(N){return M(N,l.uint8array?new Uint8Array(N.length):new Array(N.length))}(U))),U):h.Promise.reject(new Error("Can't read the data of '"+S+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(n,o,a){var l=n("./reader/readerFor"),f=n("./utils"),_=n("./signature"),h=n("./zipEntry"),g=n("./support");function M(w){this.files=[],this.loadOptions=w}M.prototype={checkSignature:function(w){if(!this.reader.readAndCheckSignature(w)){this.reader.index-=4;var C=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+f.pretty(C)+", expected "+f.pretty(w)+")")}},isSignature:function(w,C){var k=this.reader.index;this.reader.setIndex(w);var z=this.reader.readString(4)===C;return this.reader.setIndex(k),z},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var w=this.reader.readData(this.zipCommentLength),C=g.uint8array?"uint8array":"array",k=f.transformTo(C,w);this.zipComment=this.loadOptions.decodeFileName(k)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var w,C,k,z=this.zip64EndOfCentralSize-44;0<z;)w=this.reader.readInt(2),C=this.reader.readInt(4),k=this.reader.readData(C),this.zip64ExtensibleData[w]={id:w,length:C,value:k}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var w,C;for(w=0;w<this.files.length;w++)C=this.files[w],this.reader.setIndex(C.localHeaderOffset),this.checkSignature(_.LOCAL_FILE_HEADER),C.readLocalPart(this.reader),C.handleUTF8(),C.processAttributes()},readCentralDir:function(){var w;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(_.CENTRAL_FILE_HEADER);)(w=new h({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(w);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var w=this.reader.lastIndexOfSignature(_.CENTRAL_DIRECTORY_END);if(w<0)throw this.isSignature(0,_.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(w);var C=w;if(this.checkSignature(_.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===f.MAX_VALUE_16BITS||this.diskWithCentralDirStart===f.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===f.MAX_VALUE_16BITS||this.centralDirRecords===f.MAX_VALUE_16BITS||this.centralDirSize===f.MAX_VALUE_32BITS||this.centralDirOffset===f.MAX_VALUE_32BITS){if(this.zip64=!0,(w=this.reader.lastIndexOfSignature(_.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(w),this.checkSignature(_.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,_.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(_.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(_.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var k=this.centralDirOffset+this.centralDirSize;this.zip64&&(k+=20,k+=12+this.zip64EndOfCentralSize);var z=C-k;if(0<z)this.isSignature(C,_.CENTRAL_FILE_HEADER)||(this.reader.zero=z);else if(z<0)throw new Error("Corrupted zip: missing "+Math.abs(z)+" bytes.")},prepareReader:function(w){this.reader=l(w)},load:function(w){this.prepareReader(w),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},o.exports=M},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(n,o,a){var l=n("./reader/readerFor"),f=n("./utils"),_=n("./compressedObject"),h=n("./crc32"),g=n("./utf8"),M=n("./compressions"),w=n("./support");function C(k,z){this.options=k,this.loadOptions=z}C.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(k){var z,S;if(k.skip(22),this.fileNameLength=k.readInt(2),S=k.readInt(2),this.fileName=k.readData(this.fileNameLength),k.skip(S),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((z=function(P){for(var y in M)if(Object.prototype.hasOwnProperty.call(M,y)&&M[y].magic===P)return M[y];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+f.pretty(this.compressionMethod)+" unknown (inner file : "+f.transformTo("string",this.fileName)+")");this.decompressed=new _(this.compressedSize,this.uncompressedSize,this.crc32,z,k.readData(this.compressedSize))},readCentralPart:function(k){this.versionMadeBy=k.readInt(2),k.skip(2),this.bitFlag=k.readInt(2),this.compressionMethod=k.readString(2),this.date=k.readDate(),this.crc32=k.readInt(4),this.compressedSize=k.readInt(4),this.uncompressedSize=k.readInt(4);var z=k.readInt(2);if(this.extraFieldsLength=k.readInt(2),this.fileCommentLength=k.readInt(2),this.diskNumberStart=k.readInt(2),this.internalFileAttributes=k.readInt(2),this.externalFileAttributes=k.readInt(4),this.localHeaderOffset=k.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");k.skip(z),this.readExtraFields(k),this.parseZIP64ExtraField(k),this.fileComment=k.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var k=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),k==0&&(this.dosPermissions=63&this.externalFileAttributes),k==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var k=l(this.extraFields[1].value);this.uncompressedSize===f.MAX_VALUE_32BITS&&(this.uncompressedSize=k.readInt(8)),this.compressedSize===f.MAX_VALUE_32BITS&&(this.compressedSize=k.readInt(8)),this.localHeaderOffset===f.MAX_VALUE_32BITS&&(this.localHeaderOffset=k.readInt(8)),this.diskNumberStart===f.MAX_VALUE_32BITS&&(this.diskNumberStart=k.readInt(4))}},readExtraFields:function(k){var z,S,P,y=k.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});k.index+4<y;)z=k.readInt(2),S=k.readInt(2),P=k.readData(S),this.extraFields[z]={id:z,length:S,value:P};k.setIndex(y)},handleUTF8:function(){var k=w.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=g.utf8decode(this.fileName),this.fileCommentStr=g.utf8decode(this.fileComment);else{var z=this.findExtraFieldUnicodePath();if(z!==null)this.fileNameStr=z;else{var S=f.transformTo(k,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(S)}var P=this.findExtraFieldUnicodeComment();if(P!==null)this.fileCommentStr=P;else{var y=f.transformTo(k,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(y)}}},findExtraFieldUnicodePath:function(){var k=this.extraFields[28789];if(k){var z=l(k.value);return z.readInt(1)!==1||h(this.fileName)!==z.readInt(4)?null:g.utf8decode(z.readData(k.length-5))}return null},findExtraFieldUnicodeComment:function(){var k=this.extraFields[25461];if(k){var z=l(k.value);return z.readInt(1)!==1||h(this.fileComment)!==z.readInt(4)?null:g.utf8decode(z.readData(k.length-5))}return null}},o.exports=C},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,o,a){function l(z,S,P){this.name=z,this.dir=P.dir,this.date=P.date,this.comment=P.comment,this.unixPermissions=P.unixPermissions,this.dosPermissions=P.dosPermissions,this._data=S,this._dataBinary=P.binary,this.options={compression:P.compression,compressionOptions:P.compressionOptions}}var f=n("./stream/StreamHelper"),_=n("./stream/DataWorker"),h=n("./utf8"),g=n("./compressedObject"),M=n("./stream/GenericWorker");l.prototype={internalStream:function(z){var S=null,P="string";try{if(!z)throw new Error("No output type specified.");var y=(P=z.toLowerCase())==="string"||P==="text";P!=="binarystring"&&P!=="text"||(P="string"),S=this._decompressWorker();var x=!this._dataBinary;x&&!y&&(S=S.pipe(new h.Utf8EncodeWorker)),!x&&y&&(S=S.pipe(new h.Utf8DecodeWorker))}catch(I){(S=new M("error")).error(I)}return new f(S,P,"")},async:function(z,S){return this.internalStream(z).accumulate(S)},nodeStream:function(z,S){return this.internalStream(z||"nodebuffer").toNodejsStream(S)},_compressWorker:function(z,S){if(this._data instanceof g&&this._data.compression.magic===z.magic)return this._data.getCompressedWorker();var P=this._decompressWorker();return this._dataBinary||(P=P.pipe(new h.Utf8EncodeWorker)),g.createWorkerFrom(P,z,S)},_decompressWorker:function(){return this._data instanceof g?this._data.getContentWorker():this._data instanceof M?this._data:new _(this._data)}};for(var w=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],C=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},k=0;k<w.length;k++)l.prototype[w[k]]=C;o.exports=l},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(n,o,a){(function(l){var f,_,h=l.MutationObserver||l.WebKitMutationObserver;if(h){var g=0,M=new h(z),w=l.document.createTextNode("");M.observe(w,{characterData:!0}),f=function(){w.data=g=++g%2}}else if(l.setImmediate||l.MessageChannel===void 0)f="document"in l&&"onreadystatechange"in l.document.createElement("script")?function(){var S=l.document.createElement("script");S.onreadystatechange=function(){z(),S.onreadystatechange=null,S.parentNode.removeChild(S),S=null},l.document.documentElement.appendChild(S)}:function(){setTimeout(z,0)};else{var C=new l.MessageChannel;C.port1.onmessage=z,f=function(){C.port2.postMessage(0)}}var k=[];function z(){var S,P;_=!0;for(var y=k.length;y;){for(P=k,k=[],S=-1;++S<y;)P[S]();y=k.length}_=!1}o.exports=function(S){k.push(S)!==1||_||f()}}).call(this,typeof So<"u"?So:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(n,o,a){var l=n("immediate");function f(){}var _={},h=["REJECTED"],g=["FULFILLED"],M=["PENDING"];function w(y){if(typeof y!="function")throw new TypeError("resolver must be a function");this.state=M,this.queue=[],this.outcome=void 0,y!==f&&S(this,y)}function C(y,x,I){this.promise=y,typeof x=="function"&&(this.onFulfilled=x,this.callFulfilled=this.otherCallFulfilled),typeof I=="function"&&(this.onRejected=I,this.callRejected=this.otherCallRejected)}function k(y,x,I){l(function(){var U;try{U=x(I)}catch(O){return _.reject(y,O)}U===y?_.reject(y,new TypeError("Cannot resolve promise with itself")):_.resolve(y,U)})}function z(y){var x=y&&y.then;if(y&&(typeof y=="object"||typeof y=="function")&&typeof x=="function")return function(){x.apply(y,arguments)}}function S(y,x){var I=!1;function U(j){I||(I=!0,_.reject(y,j))}function O(j){I||(I=!0,_.resolve(y,j))}var N=P(function(){x(O,U)});N.status==="error"&&U(N.value)}function P(y,x){var I={};try{I.value=y(x),I.status="success"}catch(U){I.status="error",I.value=U}return I}(o.exports=w).prototype.finally=function(y){if(typeof y!="function")return this;var x=this.constructor;return this.then(function(I){return x.resolve(y()).then(function(){return I})},function(I){return x.resolve(y()).then(function(){throw I})})},w.prototype.catch=function(y){return this.then(null,y)},w.prototype.then=function(y,x){if(typeof y!="function"&&this.state===g||typeof x!="function"&&this.state===h)return this;var I=new this.constructor(f);return this.state!==M?k(I,this.state===g?y:x,this.outcome):this.queue.push(new C(I,y,x)),I},C.prototype.callFulfilled=function(y){_.resolve(this.promise,y)},C.prototype.otherCallFulfilled=function(y){k(this.promise,this.onFulfilled,y)},C.prototype.callRejected=function(y){_.reject(this.promise,y)},C.prototype.otherCallRejected=function(y){k(this.promise,this.onRejected,y)},_.resolve=function(y,x){var I=P(z,x);if(I.status==="error")return _.reject(y,I.value);var U=I.value;if(U)S(y,U);else{y.state=g,y.outcome=x;for(var O=-1,N=y.queue.length;++O<N;)y.queue[O].callFulfilled(x)}return y},_.reject=function(y,x){y.state=h,y.outcome=x;for(var I=-1,U=y.queue.length;++I<U;)y.queue[I].callRejected(x);return y},w.resolve=function(y){return y instanceof this?y:_.resolve(new this(f),y)},w.reject=function(y){var x=new this(f);return _.reject(x,y)},w.all=function(y){var x=this;if(Object.prototype.toString.call(y)!=="[object Array]")return this.reject(new TypeError("must be an array"));var I=y.length,U=!1;if(!I)return this.resolve([]);for(var O=new Array(I),N=0,j=-1,D=new this(f);++j<I;)Y(y[j],j);return D;function Y(de,Ce){x.resolve(de).then(function(ee){O[Ce]=ee,++N!==I||U||(U=!0,_.resolve(D,O))},function(ee){U||(U=!0,_.reject(D,ee))})}},w.race=function(y){var x=this;if(Object.prototype.toString.call(y)!=="[object Array]")return this.reject(new TypeError("must be an array"));var I=y.length,U=!1;if(!I)return this.resolve([]);for(var O=-1,N=new this(f);++O<I;)j=y[O],x.resolve(j).then(function(D){U||(U=!0,_.resolve(N,D))},function(D){U||(U=!0,_.reject(N,D))});var j;return N}},{immediate:36}],38:[function(n,o,a){var l={};(0,n("./lib/utils/common").assign)(l,n("./lib/deflate"),n("./lib/inflate"),n("./lib/zlib/constants")),o.exports=l},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(n,o,a){var l=n("./zlib/deflate"),f=n("./utils/common"),_=n("./utils/strings"),h=n("./zlib/messages"),g=n("./zlib/zstream"),M=Object.prototype.toString,w=0,C=-1,k=0,z=8;function S(y){if(!(this instanceof S))return new S(y);this.options=f.assign({level:C,method:z,chunkSize:16384,windowBits:15,memLevel:8,strategy:k,to:""},y||{});var x=this.options;x.raw&&0<x.windowBits?x.windowBits=-x.windowBits:x.gzip&&0<x.windowBits&&x.windowBits<16&&(x.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new g,this.strm.avail_out=0;var I=l.deflateInit2(this.strm,x.level,x.method,x.windowBits,x.memLevel,x.strategy);if(I!==w)throw new Error(h[I]);if(x.header&&l.deflateSetHeader(this.strm,x.header),x.dictionary){var U;if(U=typeof x.dictionary=="string"?_.string2buf(x.dictionary):M.call(x.dictionary)==="[object ArrayBuffer]"?new Uint8Array(x.dictionary):x.dictionary,(I=l.deflateSetDictionary(this.strm,U))!==w)throw new Error(h[I]);this._dict_set=!0}}function P(y,x){var I=new S(x);if(I.push(y,!0),I.err)throw I.msg||h[I.err];return I.result}S.prototype.push=function(y,x){var I,U,O=this.strm,N=this.options.chunkSize;if(this.ended)return!1;U=x===~~x?x:x===!0?4:0,typeof y=="string"?O.input=_.string2buf(y):M.call(y)==="[object ArrayBuffer]"?O.input=new Uint8Array(y):O.input=y,O.next_in=0,O.avail_in=O.input.length;do{if(O.avail_out===0&&(O.output=new f.Buf8(N),O.next_out=0,O.avail_out=N),(I=l.deflate(O,U))!==1&&I!==w)return this.onEnd(I),!(this.ended=!0);O.avail_out!==0&&(O.avail_in!==0||U!==4&&U!==2)||(this.options.to==="string"?this.onData(_.buf2binstring(f.shrinkBuf(O.output,O.next_out))):this.onData(f.shrinkBuf(O.output,O.next_out)))}while((0<O.avail_in||O.avail_out===0)&&I!==1);return U===4?(I=l.deflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===w):U!==2||(this.onEnd(w),!(O.avail_out=0))},S.prototype.onData=function(y){this.chunks.push(y)},S.prototype.onEnd=function(y){y===w&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=f.flattenChunks(this.chunks)),this.chunks=[],this.err=y,this.msg=this.strm.msg},a.Deflate=S,a.deflate=P,a.deflateRaw=function(y,x){return(x=x||{}).raw=!0,P(y,x)},a.gzip=function(y,x){return(x=x||{}).gzip=!0,P(y,x)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(n,o,a){var l=n("./zlib/inflate"),f=n("./utils/common"),_=n("./utils/strings"),h=n("./zlib/constants"),g=n("./zlib/messages"),M=n("./zlib/zstream"),w=n("./zlib/gzheader"),C=Object.prototype.toString;function k(S){if(!(this instanceof k))return new k(S);this.options=f.assign({chunkSize:16384,windowBits:0,to:""},S||{});var P=this.options;P.raw&&0<=P.windowBits&&P.windowBits<16&&(P.windowBits=-P.windowBits,P.windowBits===0&&(P.windowBits=-15)),!(0<=P.windowBits&&P.windowBits<16)||S&&S.windowBits||(P.windowBits+=32),15<P.windowBits&&P.windowBits<48&&!(15&P.windowBits)&&(P.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new M,this.strm.avail_out=0;var y=l.inflateInit2(this.strm,P.windowBits);if(y!==h.Z_OK)throw new Error(g[y]);this.header=new w,l.inflateGetHeader(this.strm,this.header)}function z(S,P){var y=new k(P);if(y.push(S,!0),y.err)throw y.msg||g[y.err];return y.result}k.prototype.push=function(S,P){var y,x,I,U,O,N,j=this.strm,D=this.options.chunkSize,Y=this.options.dictionary,de=!1;if(this.ended)return!1;x=P===~~P?P:P===!0?h.Z_FINISH:h.Z_NO_FLUSH,typeof S=="string"?j.input=_.binstring2buf(S):C.call(S)==="[object ArrayBuffer]"?j.input=new Uint8Array(S):j.input=S,j.next_in=0,j.avail_in=j.input.length;do{if(j.avail_out===0&&(j.output=new f.Buf8(D),j.next_out=0,j.avail_out=D),(y=l.inflate(j,h.Z_NO_FLUSH))===h.Z_NEED_DICT&&Y&&(N=typeof Y=="string"?_.string2buf(Y):C.call(Y)==="[object ArrayBuffer]"?new Uint8Array(Y):Y,y=l.inflateSetDictionary(this.strm,N)),y===h.Z_BUF_ERROR&&de===!0&&(y=h.Z_OK,de=!1),y!==h.Z_STREAM_END&&y!==h.Z_OK)return this.onEnd(y),!(this.ended=!0);j.next_out&&(j.avail_out!==0&&y!==h.Z_STREAM_END&&(j.avail_in!==0||x!==h.Z_FINISH&&x!==h.Z_SYNC_FLUSH)||(this.options.to==="string"?(I=_.utf8border(j.output,j.next_out),U=j.next_out-I,O=_.buf2string(j.output,I),j.next_out=U,j.avail_out=D-U,U&&f.arraySet(j.output,j.output,I,U,0),this.onData(O)):this.onData(f.shrinkBuf(j.output,j.next_out)))),j.avail_in===0&&j.avail_out===0&&(de=!0)}while((0<j.avail_in||j.avail_out===0)&&y!==h.Z_STREAM_END);return y===h.Z_STREAM_END&&(x=h.Z_FINISH),x===h.Z_FINISH?(y=l.inflateEnd(this.strm),this.onEnd(y),this.ended=!0,y===h.Z_OK):x!==h.Z_SYNC_FLUSH||(this.onEnd(h.Z_OK),!(j.avail_out=0))},k.prototype.onData=function(S){this.chunks.push(S)},k.prototype.onEnd=function(S){S===h.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=f.flattenChunks(this.chunks)),this.chunks=[],this.err=S,this.msg=this.strm.msg},a.Inflate=k,a.inflate=z,a.inflateRaw=function(S,P){return(P=P||{}).raw=!0,z(S,P)},a.ungzip=z},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(n,o,a){var l=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";a.assign=function(h){for(var g=Array.prototype.slice.call(arguments,1);g.length;){var M=g.shift();if(M){if(typeof M!="object")throw new TypeError(M+"must be non-object");for(var w in M)M.hasOwnProperty(w)&&(h[w]=M[w])}}return h},a.shrinkBuf=function(h,g){return h.length===g?h:h.subarray?h.subarray(0,g):(h.length=g,h)};var f={arraySet:function(h,g,M,w,C){if(g.subarray&&h.subarray)h.set(g.subarray(M,M+w),C);else for(var k=0;k<w;k++)h[C+k]=g[M+k]},flattenChunks:function(h){var g,M,w,C,k,z;for(g=w=0,M=h.length;g<M;g++)w+=h[g].length;for(z=new Uint8Array(w),g=C=0,M=h.length;g<M;g++)k=h[g],z.set(k,C),C+=k.length;return z}},_={arraySet:function(h,g,M,w,C){for(var k=0;k<w;k++)h[C+k]=g[M+k]},flattenChunks:function(h){return[].concat.apply([],h)}};a.setTyped=function(h){h?(a.Buf8=Uint8Array,a.Buf16=Uint16Array,a.Buf32=Int32Array,a.assign(a,f)):(a.Buf8=Array,a.Buf16=Array,a.Buf32=Array,a.assign(a,_))},a.setTyped(l)},{}],42:[function(n,o,a){var l=n("./common"),f=!0,_=!0;try{String.fromCharCode.apply(null,[0])}catch{f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{_=!1}for(var h=new l.Buf8(256),g=0;g<256;g++)h[g]=252<=g?6:248<=g?5:240<=g?4:224<=g?3:192<=g?2:1;function M(w,C){if(C<65537&&(w.subarray&&_||!w.subarray&&f))return String.fromCharCode.apply(null,l.shrinkBuf(w,C));for(var k="",z=0;z<C;z++)k+=String.fromCharCode(w[z]);return k}h[254]=h[254]=1,a.string2buf=function(w){var C,k,z,S,P,y=w.length,x=0;for(S=0;S<y;S++)(64512&(k=w.charCodeAt(S)))==55296&&S+1<y&&(64512&(z=w.charCodeAt(S+1)))==56320&&(k=65536+(k-55296<<10)+(z-56320),S++),x+=k<128?1:k<2048?2:k<65536?3:4;for(C=new l.Buf8(x),S=P=0;P<x;S++)(64512&(k=w.charCodeAt(S)))==55296&&S+1<y&&(64512&(z=w.charCodeAt(S+1)))==56320&&(k=65536+(k-55296<<10)+(z-56320),S++),k<128?C[P++]=k:(k<2048?C[P++]=192|k>>>6:(k<65536?C[P++]=224|k>>>12:(C[P++]=240|k>>>18,C[P++]=128|k>>>12&63),C[P++]=128|k>>>6&63),C[P++]=128|63&k);return C},a.buf2binstring=function(w){return M(w,w.length)},a.binstring2buf=function(w){for(var C=new l.Buf8(w.length),k=0,z=C.length;k<z;k++)C[k]=w.charCodeAt(k);return C},a.buf2string=function(w,C){var k,z,S,P,y=C||w.length,x=new Array(2*y);for(k=z=0;k<y;)if((S=w[k++])<128)x[z++]=S;else if(4<(P=h[S]))x[z++]=65533,k+=P-1;else{for(S&=P===2?31:P===3?15:7;1<P&&k<y;)S=S<<6|63&w[k++],P--;1<P?x[z++]=65533:S<65536?x[z++]=S:(S-=65536,x[z++]=55296|S>>10&1023,x[z++]=56320|1023&S)}return M(x,z)},a.utf8border=function(w,C){var k;for((C=C||w.length)>w.length&&(C=w.length),k=C-1;0<=k&&(192&w[k])==128;)k--;return k<0||k===0?C:k+h[w[k]]>C?k:C}},{"./common":41}],43:[function(n,o,a){o.exports=function(l,f,_,h){for(var g=65535&l|0,M=l>>>16&65535|0,w=0;_!==0;){for(_-=w=2e3<_?2e3:_;M=M+(g=g+f[h++]|0)|0,--w;);g%=65521,M%=65521}return g|M<<16|0}},{}],44:[function(n,o,a){o.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(n,o,a){var l=function(){for(var f,_=[],h=0;h<256;h++){f=h;for(var g=0;g<8;g++)f=1&f?3988292384^f>>>1:f>>>1;_[h]=f}return _}();o.exports=function(f,_,h,g){var M=l,w=g+h;f^=-1;for(var C=g;C<w;C++)f=f>>>8^M[255&(f^_[C])];return-1^f}},{}],46:[function(n,o,a){var l,f=n("../utils/common"),_=n("./trees"),h=n("./adler32"),g=n("./crc32"),M=n("./messages"),w=0,C=4,k=0,z=-2,S=-1,P=4,y=2,x=8,I=9,U=286,O=30,N=19,j=2*U+1,D=15,Y=3,de=258,Ce=de+Y+1,ee=42,ye=113,R=1,Me=2,Qe=3,ge=4;function Q(A,Ae){return A.msg=M[Ae],Ae}function ae(A){return(A<<1)-(4<A?9:0)}function Se(A){for(var Ae=A.length;0<=--Ae;)A[Ae]=0}function X(A){var Ae=A.state,$e=Ae.pending;$e>A.avail_out&&($e=A.avail_out),$e!==0&&(f.arraySet(A.output,Ae.pending_buf,Ae.pending_out,$e,A.next_out),A.next_out+=$e,Ae.pending_out+=$e,A.total_out+=$e,A.avail_out-=$e,Ae.pending-=$e,Ae.pending===0&&(Ae.pending_out=0))}function me(A,Ae){_._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,Ae),A.block_start=A.strstart,X(A.strm)}function Ke(A,Ae){A.pending_buf[A.pending++]=Ae}function De(A,Ae){A.pending_buf[A.pending++]=Ae>>>8&255,A.pending_buf[A.pending++]=255&Ae}function Be(A,Ae){var $e,se,te=A.max_chain_length,we=A.strstart,B=A.prev_length,J=A.nice_match,L=A.strstart>A.w_size-Ce?A.strstart-(A.w_size-Ce):0,ue=A.window,le=A.w_mask,ke=A.prev,Ne=A.strstart+de,ut=ue[we+B-1],Je=ue[we+B];A.prev_length>=A.good_match&&(te>>=2),J>A.lookahead&&(J=A.lookahead);do if(ue[($e=Ae)+B]===Je&&ue[$e+B-1]===ut&&ue[$e]===ue[we]&&ue[++$e]===ue[we+1]){we+=2,$e++;do;while(ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&we<Ne);if(se=de-(Ne-we),we=Ne-de,B<se){if(A.match_start=Ae,J<=(B=se))break;ut=ue[we+B-1],Je=ue[we+B]}}while((Ae=ke[Ae&le])>L&&--te!=0);return B<=A.lookahead?B:A.lookahead}function We(A){var Ae,$e,se,te,we,B,J,L,ue,le,ke=A.w_size;do{if(te=A.window_size-A.lookahead-A.strstart,A.strstart>=ke+(ke-Ce)){for(f.arraySet(A.window,A.window,ke,ke,0),A.match_start-=ke,A.strstart-=ke,A.block_start-=ke,Ae=$e=A.hash_size;se=A.head[--Ae],A.head[Ae]=ke<=se?se-ke:0,--$e;);for(Ae=$e=ke;se=A.prev[--Ae],A.prev[Ae]=ke<=se?se-ke:0,--$e;);te+=ke}if(A.strm.avail_in===0)break;if(B=A.strm,J=A.window,L=A.strstart+A.lookahead,ue=te,le=void 0,le=B.avail_in,ue<le&&(le=ue),$e=le===0?0:(B.avail_in-=le,f.arraySet(J,B.input,B.next_in,le,L),B.state.wrap===1?B.adler=h(B.adler,J,le,L):B.state.wrap===2&&(B.adler=g(B.adler,J,le,L)),B.next_in+=le,B.total_in+=le,le),A.lookahead+=$e,A.lookahead+A.insert>=Y)for(we=A.strstart-A.insert,A.ins_h=A.window[we],A.ins_h=(A.ins_h<<A.hash_shift^A.window[we+1])&A.hash_mask;A.insert&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[we+Y-1])&A.hash_mask,A.prev[we&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=we,we++,A.insert--,!(A.lookahead+A.insert<Y)););}while(A.lookahead<Ce&&A.strm.avail_in!==0)}function ot(A,Ae){for(var $e,se;;){if(A.lookahead<Ce){if(We(A),A.lookahead<Ce&&Ae===w)return R;if(A.lookahead===0)break}if($e=0,A.lookahead>=Y&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+Y-1])&A.hash_mask,$e=A.prev[A.strstart&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=A.strstart),$e!==0&&A.strstart-$e<=A.w_size-Ce&&(A.match_length=Be(A,$e)),A.match_length>=Y)if(se=_._tr_tally(A,A.strstart-A.match_start,A.match_length-Y),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=Y){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+Y-1])&A.hash_mask,$e=A.prev[A.strstart&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=A.strstart,--A.match_length!=0;);A.strstart++}else A.strstart+=A.match_length,A.match_length=0,A.ins_h=A.window[A.strstart],A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+1])&A.hash_mask;else se=_._tr_tally(A,0,A.window[A.strstart]),A.lookahead--,A.strstart++;if(se&&(me(A,!1),A.strm.avail_out===0))return R}return A.insert=A.strstart<Y-1?A.strstart:Y-1,Ae===C?(me(A,!0),A.strm.avail_out===0?Qe:ge):A.last_lit&&(me(A,!1),A.strm.avail_out===0)?R:Me}function dt(A,Ae){for(var $e,se,te;;){if(A.lookahead<Ce){if(We(A),A.lookahead<Ce&&Ae===w)return R;if(A.lookahead===0)break}if($e=0,A.lookahead>=Y&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+Y-1])&A.hash_mask,$e=A.prev[A.strstart&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=A.strstart),A.prev_length=A.match_length,A.prev_match=A.match_start,A.match_length=Y-1,$e!==0&&A.prev_length<A.max_lazy_match&&A.strstart-$e<=A.w_size-Ce&&(A.match_length=Be(A,$e),A.match_length<=5&&(A.strategy===1||A.match_length===Y&&4096<A.strstart-A.match_start)&&(A.match_length=Y-1)),A.prev_length>=Y&&A.match_length<=A.prev_length){for(te=A.strstart+A.lookahead-Y,se=_._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-Y),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=te&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+Y-1])&A.hash_mask,$e=A.prev[A.strstart&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=A.strstart),--A.prev_length!=0;);if(A.match_available=0,A.match_length=Y-1,A.strstart++,se&&(me(A,!1),A.strm.avail_out===0))return R}else if(A.match_available){if((se=_._tr_tally(A,0,A.window[A.strstart-1]))&&me(A,!1),A.strstart++,A.lookahead--,A.strm.avail_out===0)return R}else A.match_available=1,A.strstart++,A.lookahead--}return A.match_available&&(se=_._tr_tally(A,0,A.window[A.strstart-1]),A.match_available=0),A.insert=A.strstart<Y-1?A.strstart:Y-1,Ae===C?(me(A,!0),A.strm.avail_out===0?Qe:ge):A.last_lit&&(me(A,!1),A.strm.avail_out===0)?R:Me}function Ge(A,Ae,$e,se,te){this.good_length=A,this.max_lazy=Ae,this.nice_length=$e,this.max_chain=se,this.func=te}function Te(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=x,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new f.Buf16(2*j),this.dyn_dtree=new f.Buf16(2*(2*O+1)),this.bl_tree=new f.Buf16(2*(2*N+1)),Se(this.dyn_ltree),Se(this.dyn_dtree),Se(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new f.Buf16(D+1),this.heap=new f.Buf16(2*U+1),Se(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new f.Buf16(2*U+1),Se(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function je(A){var Ae;return A&&A.state?(A.total_in=A.total_out=0,A.data_type=y,(Ae=A.state).pending=0,Ae.pending_out=0,Ae.wrap<0&&(Ae.wrap=-Ae.wrap),Ae.status=Ae.wrap?ee:ye,A.adler=Ae.wrap===2?0:1,Ae.last_flush=w,_._tr_init(Ae),k):Q(A,z)}function Ye(A){var Ae=je(A);return Ae===k&&function($e){$e.window_size=2*$e.w_size,Se($e.head),$e.max_lazy_match=l[$e.level].max_lazy,$e.good_match=l[$e.level].good_length,$e.nice_match=l[$e.level].nice_length,$e.max_chain_length=l[$e.level].max_chain,$e.strstart=0,$e.block_start=0,$e.lookahead=0,$e.insert=0,$e.match_length=$e.prev_length=Y-1,$e.match_available=0,$e.ins_h=0}(A.state),Ae}function tt(A,Ae,$e,se,te,we){if(!A)return z;var B=1;if(Ae===S&&(Ae=6),se<0?(B=0,se=-se):15<se&&(B=2,se-=16),te<1||I<te||$e!==x||se<8||15<se||Ae<0||9<Ae||we<0||P<we)return Q(A,z);se===8&&(se=9);var J=new Te;return(A.state=J).strm=A,J.wrap=B,J.gzhead=null,J.w_bits=se,J.w_size=1<<J.w_bits,J.w_mask=J.w_size-1,J.hash_bits=te+7,J.hash_size=1<<J.hash_bits,J.hash_mask=J.hash_size-1,J.hash_shift=~~((J.hash_bits+Y-1)/Y),J.window=new f.Buf8(2*J.w_size),J.head=new f.Buf16(J.hash_size),J.prev=new f.Buf16(J.w_size),J.lit_bufsize=1<<te+6,J.pending_buf_size=4*J.lit_bufsize,J.pending_buf=new f.Buf8(J.pending_buf_size),J.d_buf=1*J.lit_bufsize,J.l_buf=3*J.lit_bufsize,J.level=Ae,J.strategy=we,J.method=$e,Ye(A)}l=[new Ge(0,0,0,0,function(A,Ae){var $e=65535;for($e>A.pending_buf_size-5&&($e=A.pending_buf_size-5);;){if(A.lookahead<=1){if(We(A),A.lookahead===0&&Ae===w)return R;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var se=A.block_start+$e;if((A.strstart===0||A.strstart>=se)&&(A.lookahead=A.strstart-se,A.strstart=se,me(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-Ce&&(me(A,!1),A.strm.avail_out===0))return R}return A.insert=0,Ae===C?(me(A,!0),A.strm.avail_out===0?Qe:ge):(A.strstart>A.block_start&&(me(A,!1),A.strm.avail_out),R)}),new Ge(4,4,8,4,ot),new Ge(4,5,16,8,ot),new Ge(4,6,32,32,ot),new Ge(4,4,16,16,dt),new Ge(8,16,32,32,dt),new Ge(8,16,128,128,dt),new Ge(8,32,128,256,dt),new Ge(32,128,258,1024,dt),new Ge(32,258,258,4096,dt)],a.deflateInit=function(A,Ae){return tt(A,Ae,x,15,8,0)},a.deflateInit2=tt,a.deflateReset=Ye,a.deflateResetKeep=je,a.deflateSetHeader=function(A,Ae){return A&&A.state?A.state.wrap!==2?z:(A.state.gzhead=Ae,k):z},a.deflate=function(A,Ae){var $e,se,te,we;if(!A||!A.state||5<Ae||Ae<0)return A?Q(A,z):z;if(se=A.state,!A.output||!A.input&&A.avail_in!==0||se.status===666&&Ae!==C)return Q(A,A.avail_out===0?-5:z);if(se.strm=A,$e=se.last_flush,se.last_flush=Ae,se.status===ee)if(se.wrap===2)A.adler=0,Ke(se,31),Ke(se,139),Ke(se,8),se.gzhead?(Ke(se,(se.gzhead.text?1:0)+(se.gzhead.hcrc?2:0)+(se.gzhead.extra?4:0)+(se.gzhead.name?8:0)+(se.gzhead.comment?16:0)),Ke(se,255&se.gzhead.time),Ke(se,se.gzhead.time>>8&255),Ke(se,se.gzhead.time>>16&255),Ke(se,se.gzhead.time>>24&255),Ke(se,se.level===9?2:2<=se.strategy||se.level<2?4:0),Ke(se,255&se.gzhead.os),se.gzhead.extra&&se.gzhead.extra.length&&(Ke(se,255&se.gzhead.extra.length),Ke(se,se.gzhead.extra.length>>8&255)),se.gzhead.hcrc&&(A.adler=g(A.adler,se.pending_buf,se.pending,0)),se.gzindex=0,se.status=69):(Ke(se,0),Ke(se,0),Ke(se,0),Ke(se,0),Ke(se,0),Ke(se,se.level===9?2:2<=se.strategy||se.level<2?4:0),Ke(se,3),se.status=ye);else{var B=x+(se.w_bits-8<<4)<<8;B|=(2<=se.strategy||se.level<2?0:se.level<6?1:se.level===6?2:3)<<6,se.strstart!==0&&(B|=32),B+=31-B%31,se.status=ye,De(se,B),se.strstart!==0&&(De(se,A.adler>>>16),De(se,65535&A.adler)),A.adler=1}if(se.status===69)if(se.gzhead.extra){for(te=se.pending;se.gzindex<(65535&se.gzhead.extra.length)&&(se.pending!==se.pending_buf_size||(se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),X(A),te=se.pending,se.pending!==se.pending_buf_size));)Ke(se,255&se.gzhead.extra[se.gzindex]),se.gzindex++;se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),se.gzindex===se.gzhead.extra.length&&(se.gzindex=0,se.status=73)}else se.status=73;if(se.status===73)if(se.gzhead.name){te=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),X(A),te=se.pending,se.pending===se.pending_buf_size)){we=1;break}we=se.gzindex<se.gzhead.name.length?255&se.gzhead.name.charCodeAt(se.gzindex++):0,Ke(se,we)}while(we!==0);se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),we===0&&(se.gzindex=0,se.status=91)}else se.status=91;if(se.status===91)if(se.gzhead.comment){te=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),X(A),te=se.pending,se.pending===se.pending_buf_size)){we=1;break}we=se.gzindex<se.gzhead.comment.length?255&se.gzhead.comment.charCodeAt(se.gzindex++):0,Ke(se,we)}while(we!==0);se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),we===0&&(se.status=103)}else se.status=103;if(se.status===103&&(se.gzhead.hcrc?(se.pending+2>se.pending_buf_size&&X(A),se.pending+2<=se.pending_buf_size&&(Ke(se,255&A.adler),Ke(se,A.adler>>8&255),A.adler=0,se.status=ye)):se.status=ye),se.pending!==0){if(X(A),A.avail_out===0)return se.last_flush=-1,k}else if(A.avail_in===0&&ae(Ae)<=ae($e)&&Ae!==C)return Q(A,-5);if(se.status===666&&A.avail_in!==0)return Q(A,-5);if(A.avail_in!==0||se.lookahead!==0||Ae!==w&&se.status!==666){var J=se.strategy===2?function(L,ue){for(var le;;){if(L.lookahead===0&&(We(L),L.lookahead===0)){if(ue===w)return R;break}if(L.match_length=0,le=_._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++,le&&(me(L,!1),L.strm.avail_out===0))return R}return L.insert=0,ue===C?(me(L,!0),L.strm.avail_out===0?Qe:ge):L.last_lit&&(me(L,!1),L.strm.avail_out===0)?R:Me}(se,Ae):se.strategy===3?function(L,ue){for(var le,ke,Ne,ut,Je=L.window;;){if(L.lookahead<=de){if(We(L),L.lookahead<=de&&ue===w)return R;if(L.lookahead===0)break}if(L.match_length=0,L.lookahead>=Y&&0<L.strstart&&(ke=Je[Ne=L.strstart-1])===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]){ut=L.strstart+de;do;while(ke===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]&&Ne<ut);L.match_length=de-(ut-Ne),L.match_length>L.lookahead&&(L.match_length=L.lookahead)}if(L.match_length>=Y?(le=_._tr_tally(L,1,L.match_length-Y),L.lookahead-=L.match_length,L.strstart+=L.match_length,L.match_length=0):(le=_._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++),le&&(me(L,!1),L.strm.avail_out===0))return R}return L.insert=0,ue===C?(me(L,!0),L.strm.avail_out===0?Qe:ge):L.last_lit&&(me(L,!1),L.strm.avail_out===0)?R:Me}(se,Ae):l[se.level].func(se,Ae);if(J!==Qe&&J!==ge||(se.status=666),J===R||J===Qe)return A.avail_out===0&&(se.last_flush=-1),k;if(J===Me&&(Ae===1?_._tr_align(se):Ae!==5&&(_._tr_stored_block(se,0,0,!1),Ae===3&&(Se(se.head),se.lookahead===0&&(se.strstart=0,se.block_start=0,se.insert=0))),X(A),A.avail_out===0))return se.last_flush=-1,k}return Ae!==C?k:se.wrap<=0?1:(se.wrap===2?(Ke(se,255&A.adler),Ke(se,A.adler>>8&255),Ke(se,A.adler>>16&255),Ke(se,A.adler>>24&255),Ke(se,255&A.total_in),Ke(se,A.total_in>>8&255),Ke(se,A.total_in>>16&255),Ke(se,A.total_in>>24&255)):(De(se,A.adler>>>16),De(se,65535&A.adler)),X(A),0<se.wrap&&(se.wrap=-se.wrap),se.pending!==0?k:1)},a.deflateEnd=function(A){var Ae;return A&&A.state?(Ae=A.state.status)!==ee&&Ae!==69&&Ae!==73&&Ae!==91&&Ae!==103&&Ae!==ye&&Ae!==666?Q(A,z):(A.state=null,Ae===ye?Q(A,-3):k):z},a.deflateSetDictionary=function(A,Ae){var $e,se,te,we,B,J,L,ue,le=Ae.length;if(!A||!A.state||(we=($e=A.state).wrap)===2||we===1&&$e.status!==ee||$e.lookahead)return z;for(we===1&&(A.adler=h(A.adler,Ae,le,0)),$e.wrap=0,le>=$e.w_size&&(we===0&&(Se($e.head),$e.strstart=0,$e.block_start=0,$e.insert=0),ue=new f.Buf8($e.w_size),f.arraySet(ue,Ae,le-$e.w_size,$e.w_size,0),Ae=ue,le=$e.w_size),B=A.avail_in,J=A.next_in,L=A.input,A.avail_in=le,A.next_in=0,A.input=Ae,We($e);$e.lookahead>=Y;){for(se=$e.strstart,te=$e.lookahead-(Y-1);$e.ins_h=($e.ins_h<<$e.hash_shift^$e.window[se+Y-1])&$e.hash_mask,$e.prev[se&$e.w_mask]=$e.head[$e.ins_h],$e.head[$e.ins_h]=se,se++,--te;);$e.strstart=se,$e.lookahead=Y-1,We($e)}return $e.strstart+=$e.lookahead,$e.block_start=$e.strstart,$e.insert=$e.lookahead,$e.lookahead=0,$e.match_length=$e.prev_length=Y-1,$e.match_available=0,A.next_in=J,A.input=L,A.avail_in=B,$e.wrap=we,k},a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,o,a){o.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(n,o,a){o.exports=function(l,f){var _,h,g,M,w,C,k,z,S,P,y,x,I,U,O,N,j,D,Y,de,Ce,ee,ye,R,Me;_=l.state,h=l.next_in,R=l.input,g=h+(l.avail_in-5),M=l.next_out,Me=l.output,w=M-(f-l.avail_out),C=M+(l.avail_out-257),k=_.dmax,z=_.wsize,S=_.whave,P=_.wnext,y=_.window,x=_.hold,I=_.bits,U=_.lencode,O=_.distcode,N=(1<<_.lenbits)-1,j=(1<<_.distbits)-1;e:do{I<15&&(x+=R[h++]<<I,I+=8,x+=R[h++]<<I,I+=8),D=U[x&N];t:for(;;){if(x>>>=Y=D>>>24,I-=Y,(Y=D>>>16&255)===0)Me[M++]=65535&D;else{if(!(16&Y)){if(!(64&Y)){D=U[(65535&D)+(x&(1<<Y)-1)];continue t}if(32&Y){_.mode=12;break e}l.msg="invalid literal/length code",_.mode=30;break e}de=65535&D,(Y&=15)&&(I<Y&&(x+=R[h++]<<I,I+=8),de+=x&(1<<Y)-1,x>>>=Y,I-=Y),I<15&&(x+=R[h++]<<I,I+=8,x+=R[h++]<<I,I+=8),D=O[x&j];r:for(;;){if(x>>>=Y=D>>>24,I-=Y,!(16&(Y=D>>>16&255))){if(!(64&Y)){D=O[(65535&D)+(x&(1<<Y)-1)];continue r}l.msg="invalid distance code",_.mode=30;break e}if(Ce=65535&D,I<(Y&=15)&&(x+=R[h++]<<I,(I+=8)<Y&&(x+=R[h++]<<I,I+=8)),k<(Ce+=x&(1<<Y)-1)){l.msg="invalid distance too far back",_.mode=30;break e}if(x>>>=Y,I-=Y,(Y=M-w)<Ce){if(S<(Y=Ce-Y)&&_.sane){l.msg="invalid distance too far back",_.mode=30;break e}if(ye=y,(ee=0)===P){if(ee+=z-Y,Y<de){for(de-=Y;Me[M++]=y[ee++],--Y;);ee=M-Ce,ye=Me}}else if(P<Y){if(ee+=z+P-Y,(Y-=P)<de){for(de-=Y;Me[M++]=y[ee++],--Y;);if(ee=0,P<de){for(de-=Y=P;Me[M++]=y[ee++],--Y;);ee=M-Ce,ye=Me}}}else if(ee+=P-Y,Y<de){for(de-=Y;Me[M++]=y[ee++],--Y;);ee=M-Ce,ye=Me}for(;2<de;)Me[M++]=ye[ee++],Me[M++]=ye[ee++],Me[M++]=ye[ee++],de-=3;de&&(Me[M++]=ye[ee++],1<de&&(Me[M++]=ye[ee++]))}else{for(ee=M-Ce;Me[M++]=Me[ee++],Me[M++]=Me[ee++],Me[M++]=Me[ee++],2<(de-=3););de&&(Me[M++]=Me[ee++],1<de&&(Me[M++]=Me[ee++]))}break}}break}}while(h<g&&M<C);h-=de=I>>3,x&=(1<<(I-=de<<3))-1,l.next_in=h,l.next_out=M,l.avail_in=h<g?g-h+5:5-(h-g),l.avail_out=M<C?C-M+257:257-(M-C),_.hold=x,_.bits=I}},{}],49:[function(n,o,a){var l=n("../utils/common"),f=n("./adler32"),_=n("./crc32"),h=n("./inffast"),g=n("./inftrees"),M=1,w=2,C=0,k=-2,z=1,S=852,P=592;function y(ee){return(ee>>>24&255)+(ee>>>8&65280)+((65280&ee)<<8)+((255&ee)<<24)}function x(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new l.Buf16(320),this.work=new l.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function I(ee){var ye;return ee&&ee.state?(ye=ee.state,ee.total_in=ee.total_out=ye.total=0,ee.msg="",ye.wrap&&(ee.adler=1&ye.wrap),ye.mode=z,ye.last=0,ye.havedict=0,ye.dmax=32768,ye.head=null,ye.hold=0,ye.bits=0,ye.lencode=ye.lendyn=new l.Buf32(S),ye.distcode=ye.distdyn=new l.Buf32(P),ye.sane=1,ye.back=-1,C):k}function U(ee){var ye;return ee&&ee.state?((ye=ee.state).wsize=0,ye.whave=0,ye.wnext=0,I(ee)):k}function O(ee,ye){var R,Me;return ee&&ee.state?(Me=ee.state,ye<0?(R=0,ye=-ye):(R=1+(ye>>4),ye<48&&(ye&=15)),ye&&(ye<8||15<ye)?k:(Me.window!==null&&Me.wbits!==ye&&(Me.window=null),Me.wrap=R,Me.wbits=ye,U(ee))):k}function N(ee,ye){var R,Me;return ee?(Me=new x,(ee.state=Me).window=null,(R=O(ee,ye))!==C&&(ee.state=null),R):k}var j,D,Y=!0;function de(ee){if(Y){var ye;for(j=new l.Buf32(512),D=new l.Buf32(32),ye=0;ye<144;)ee.lens[ye++]=8;for(;ye<256;)ee.lens[ye++]=9;for(;ye<280;)ee.lens[ye++]=7;for(;ye<288;)ee.lens[ye++]=8;for(g(M,ee.lens,0,288,j,0,ee.work,{bits:9}),ye=0;ye<32;)ee.lens[ye++]=5;g(w,ee.lens,0,32,D,0,ee.work,{bits:5}),Y=!1}ee.lencode=j,ee.lenbits=9,ee.distcode=D,ee.distbits=5}function Ce(ee,ye,R,Me){var Qe,ge=ee.state;return ge.window===null&&(ge.wsize=1<<ge.wbits,ge.wnext=0,ge.whave=0,ge.window=new l.Buf8(ge.wsize)),Me>=ge.wsize?(l.arraySet(ge.window,ye,R-ge.wsize,ge.wsize,0),ge.wnext=0,ge.whave=ge.wsize):(Me<(Qe=ge.wsize-ge.wnext)&&(Qe=Me),l.arraySet(ge.window,ye,R-Me,Qe,ge.wnext),(Me-=Qe)?(l.arraySet(ge.window,ye,R-Me,Me,0),ge.wnext=Me,ge.whave=ge.wsize):(ge.wnext+=Qe,ge.wnext===ge.wsize&&(ge.wnext=0),ge.whave<ge.wsize&&(ge.whave+=Qe))),0}a.inflateReset=U,a.inflateReset2=O,a.inflateResetKeep=I,a.inflateInit=function(ee){return N(ee,15)},a.inflateInit2=N,a.inflate=function(ee,ye){var R,Me,Qe,ge,Q,ae,Se,X,me,Ke,De,Be,We,ot,dt,Ge,Te,je,Ye,tt,A,Ae,$e,se,te=0,we=new l.Buf8(4),B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!ee||!ee.state||!ee.output||!ee.input&&ee.avail_in!==0)return k;(R=ee.state).mode===12&&(R.mode=13),Q=ee.next_out,Qe=ee.output,Se=ee.avail_out,ge=ee.next_in,Me=ee.input,ae=ee.avail_in,X=R.hold,me=R.bits,Ke=ae,De=Se,Ae=C;e:for(;;)switch(R.mode){case z:if(R.wrap===0){R.mode=13;break}for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(2&R.wrap&&X===35615){we[R.check=0]=255&X,we[1]=X>>>8&255,R.check=_(R.check,we,2,0),me=X=0,R.mode=2;break}if(R.flags=0,R.head&&(R.head.done=!1),!(1&R.wrap)||(((255&X)<<8)+(X>>8))%31){ee.msg="incorrect header check",R.mode=30;break}if((15&X)!=8){ee.msg="unknown compression method",R.mode=30;break}if(me-=4,A=8+(15&(X>>>=4)),R.wbits===0)R.wbits=A;else if(A>R.wbits){ee.msg="invalid window size",R.mode=30;break}R.dmax=1<<A,ee.adler=R.check=1,R.mode=512&X?10:12,me=X=0;break;case 2:for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(R.flags=X,(255&R.flags)!=8){ee.msg="unknown compression method",R.mode=30;break}if(57344&R.flags){ee.msg="unknown header flags set",R.mode=30;break}R.head&&(R.head.text=X>>8&1),512&R.flags&&(we[0]=255&X,we[1]=X>>>8&255,R.check=_(R.check,we,2,0)),me=X=0,R.mode=3;case 3:for(;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}R.head&&(R.head.time=X),512&R.flags&&(we[0]=255&X,we[1]=X>>>8&255,we[2]=X>>>16&255,we[3]=X>>>24&255,R.check=_(R.check,we,4,0)),me=X=0,R.mode=4;case 4:for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}R.head&&(R.head.xflags=255&X,R.head.os=X>>8),512&R.flags&&(we[0]=255&X,we[1]=X>>>8&255,R.check=_(R.check,we,2,0)),me=X=0,R.mode=5;case 5:if(1024&R.flags){for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}R.length=X,R.head&&(R.head.extra_len=X),512&R.flags&&(we[0]=255&X,we[1]=X>>>8&255,R.check=_(R.check,we,2,0)),me=X=0}else R.head&&(R.head.extra=null);R.mode=6;case 6:if(1024&R.flags&&(ae<(Be=R.length)&&(Be=ae),Be&&(R.head&&(A=R.head.extra_len-R.length,R.head.extra||(R.head.extra=new Array(R.head.extra_len)),l.arraySet(R.head.extra,Me,ge,Be,A)),512&R.flags&&(R.check=_(R.check,Me,Be,ge)),ae-=Be,ge+=Be,R.length-=Be),R.length))break e;R.length=0,R.mode=7;case 7:if(2048&R.flags){if(ae===0)break e;for(Be=0;A=Me[ge+Be++],R.head&&A&&R.length<65536&&(R.head.name+=String.fromCharCode(A)),A&&Be<ae;);if(512&R.flags&&(R.check=_(R.check,Me,Be,ge)),ae-=Be,ge+=Be,A)break e}else R.head&&(R.head.name=null);R.length=0,R.mode=8;case 8:if(4096&R.flags){if(ae===0)break e;for(Be=0;A=Me[ge+Be++],R.head&&A&&R.length<65536&&(R.head.comment+=String.fromCharCode(A)),A&&Be<ae;);if(512&R.flags&&(R.check=_(R.check,Me,Be,ge)),ae-=Be,ge+=Be,A)break e}else R.head&&(R.head.comment=null);R.mode=9;case 9:if(512&R.flags){for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(X!==(65535&R.check)){ee.msg="header crc mismatch",R.mode=30;break}me=X=0}R.head&&(R.head.hcrc=R.flags>>9&1,R.head.done=!0),ee.adler=R.check=0,R.mode=12;break;case 10:for(;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}ee.adler=R.check=y(X),me=X=0,R.mode=11;case 11:if(R.havedict===0)return ee.next_out=Q,ee.avail_out=Se,ee.next_in=ge,ee.avail_in=ae,R.hold=X,R.bits=me,2;ee.adler=R.check=1,R.mode=12;case 12:if(ye===5||ye===6)break e;case 13:if(R.last){X>>>=7&me,me-=7&me,R.mode=27;break}for(;me<3;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}switch(R.last=1&X,me-=1,3&(X>>>=1)){case 0:R.mode=14;break;case 1:if(de(R),R.mode=20,ye!==6)break;X>>>=2,me-=2;break e;case 2:R.mode=17;break;case 3:ee.msg="invalid block type",R.mode=30}X>>>=2,me-=2;break;case 14:for(X>>>=7&me,me-=7&me;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if((65535&X)!=(X>>>16^65535)){ee.msg="invalid stored block lengths",R.mode=30;break}if(R.length=65535&X,me=X=0,R.mode=15,ye===6)break e;case 15:R.mode=16;case 16:if(Be=R.length){if(ae<Be&&(Be=ae),Se<Be&&(Be=Se),Be===0)break e;l.arraySet(Qe,Me,ge,Be,Q),ae-=Be,ge+=Be,Se-=Be,Q+=Be,R.length-=Be;break}R.mode=12;break;case 17:for(;me<14;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(R.nlen=257+(31&X),X>>>=5,me-=5,R.ndist=1+(31&X),X>>>=5,me-=5,R.ncode=4+(15&X),X>>>=4,me-=4,286<R.nlen||30<R.ndist){ee.msg="too many length or distance symbols",R.mode=30;break}R.have=0,R.mode=18;case 18:for(;R.have<R.ncode;){for(;me<3;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}R.lens[B[R.have++]]=7&X,X>>>=3,me-=3}for(;R.have<19;)R.lens[B[R.have++]]=0;if(R.lencode=R.lendyn,R.lenbits=7,$e={bits:R.lenbits},Ae=g(0,R.lens,0,19,R.lencode,0,R.work,$e),R.lenbits=$e.bits,Ae){ee.msg="invalid code lengths set",R.mode=30;break}R.have=0,R.mode=19;case 19:for(;R.have<R.nlen+R.ndist;){for(;Ge=(te=R.lencode[X&(1<<R.lenbits)-1])>>>16&255,Te=65535&te,!((dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(Te<16)X>>>=dt,me-=dt,R.lens[R.have++]=Te;else{if(Te===16){for(se=dt+2;me<se;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(X>>>=dt,me-=dt,R.have===0){ee.msg="invalid bit length repeat",R.mode=30;break}A=R.lens[R.have-1],Be=3+(3&X),X>>>=2,me-=2}else if(Te===17){for(se=dt+3;me<se;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}me-=dt,A=0,Be=3+(7&(X>>>=dt)),X>>>=3,me-=3}else{for(se=dt+7;me<se;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}me-=dt,A=0,Be=11+(127&(X>>>=dt)),X>>>=7,me-=7}if(R.have+Be>R.nlen+R.ndist){ee.msg="invalid bit length repeat",R.mode=30;break}for(;Be--;)R.lens[R.have++]=A}}if(R.mode===30)break;if(R.lens[256]===0){ee.msg="invalid code -- missing end-of-block",R.mode=30;break}if(R.lenbits=9,$e={bits:R.lenbits},Ae=g(M,R.lens,0,R.nlen,R.lencode,0,R.work,$e),R.lenbits=$e.bits,Ae){ee.msg="invalid literal/lengths set",R.mode=30;break}if(R.distbits=6,R.distcode=R.distdyn,$e={bits:R.distbits},Ae=g(w,R.lens,R.nlen,R.ndist,R.distcode,0,R.work,$e),R.distbits=$e.bits,Ae){ee.msg="invalid distances set",R.mode=30;break}if(R.mode=20,ye===6)break e;case 20:R.mode=21;case 21:if(6<=ae&&258<=Se){ee.next_out=Q,ee.avail_out=Se,ee.next_in=ge,ee.avail_in=ae,R.hold=X,R.bits=me,h(ee,De),Q=ee.next_out,Qe=ee.output,Se=ee.avail_out,ge=ee.next_in,Me=ee.input,ae=ee.avail_in,X=R.hold,me=R.bits,R.mode===12&&(R.back=-1);break}for(R.back=0;Ge=(te=R.lencode[X&(1<<R.lenbits)-1])>>>16&255,Te=65535&te,!((dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(Ge&&!(240&Ge)){for(je=dt,Ye=Ge,tt=Te;Ge=(te=R.lencode[tt+((X&(1<<je+Ye)-1)>>je)])>>>16&255,Te=65535&te,!(je+(dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}X>>>=je,me-=je,R.back+=je}if(X>>>=dt,me-=dt,R.back+=dt,R.length=Te,Ge===0){R.mode=26;break}if(32&Ge){R.back=-1,R.mode=12;break}if(64&Ge){ee.msg="invalid literal/length code",R.mode=30;break}R.extra=15&Ge,R.mode=22;case 22:if(R.extra){for(se=R.extra;me<se;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}R.length+=X&(1<<R.extra)-1,X>>>=R.extra,me-=R.extra,R.back+=R.extra}R.was=R.length,R.mode=23;case 23:for(;Ge=(te=R.distcode[X&(1<<R.distbits)-1])>>>16&255,Te=65535&te,!((dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(!(240&Ge)){for(je=dt,Ye=Ge,tt=Te;Ge=(te=R.distcode[tt+((X&(1<<je+Ye)-1)>>je)])>>>16&255,Te=65535&te,!(je+(dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}X>>>=je,me-=je,R.back+=je}if(X>>>=dt,me-=dt,R.back+=dt,64&Ge){ee.msg="invalid distance code",R.mode=30;break}R.offset=Te,R.extra=15&Ge,R.mode=24;case 24:if(R.extra){for(se=R.extra;me<se;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}R.offset+=X&(1<<R.extra)-1,X>>>=R.extra,me-=R.extra,R.back+=R.extra}if(R.offset>R.dmax){ee.msg="invalid distance too far back",R.mode=30;break}R.mode=25;case 25:if(Se===0)break e;if(Be=De-Se,R.offset>Be){if((Be=R.offset-Be)>R.whave&&R.sane){ee.msg="invalid distance too far back",R.mode=30;break}We=Be>R.wnext?(Be-=R.wnext,R.wsize-Be):R.wnext-Be,Be>R.length&&(Be=R.length),ot=R.window}else ot=Qe,We=Q-R.offset,Be=R.length;for(Se<Be&&(Be=Se),Se-=Be,R.length-=Be;Qe[Q++]=ot[We++],--Be;);R.length===0&&(R.mode=21);break;case 26:if(Se===0)break e;Qe[Q++]=R.length,Se--,R.mode=21;break;case 27:if(R.wrap){for(;me<32;){if(ae===0)break e;ae--,X|=Me[ge++]<<me,me+=8}if(De-=Se,ee.total_out+=De,R.total+=De,De&&(ee.adler=R.check=R.flags?_(R.check,Qe,De,Q-De):f(R.check,Qe,De,Q-De)),De=Se,(R.flags?X:y(X))!==R.check){ee.msg="incorrect data check",R.mode=30;break}me=X=0}R.mode=28;case 28:if(R.wrap&&R.flags){for(;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<<me,me+=8}if(X!==(4294967295&R.total)){ee.msg="incorrect length check",R.mode=30;break}me=X=0}R.mode=29;case 29:Ae=1;break e;case 30:Ae=-3;break e;case 31:return-4;case 32:default:return k}return ee.next_out=Q,ee.avail_out=Se,ee.next_in=ge,ee.avail_in=ae,R.hold=X,R.bits=me,(R.wsize||De!==ee.avail_out&&R.mode<30&&(R.mode<27||ye!==4))&&Ce(ee,ee.output,ee.next_out,De-ee.avail_out)?(R.mode=31,-4):(Ke-=ee.avail_in,De-=ee.avail_out,ee.total_in+=Ke,ee.total_out+=De,R.total+=De,R.wrap&&De&&(ee.adler=R.check=R.flags?_(R.check,Qe,De,ee.next_out-De):f(R.check,Qe,De,ee.next_out-De)),ee.data_type=R.bits+(R.last?64:0)+(R.mode===12?128:0)+(R.mode===20||R.mode===15?256:0),(Ke==0&&De===0||ye===4)&&Ae===C&&(Ae=-5),Ae)},a.inflateEnd=function(ee){if(!ee||!ee.state)return k;var ye=ee.state;return ye.window&&(ye.window=null),ee.state=null,C},a.inflateGetHeader=function(ee,ye){var R;return ee&&ee.state&&2&(R=ee.state).wrap?((R.head=ye).done=!1,C):k},a.inflateSetDictionary=function(ee,ye){var R,Me=ye.length;return ee&&ee.state?(R=ee.state).wrap!==0&&R.mode!==11?k:R.mode===11&&f(1,ye,Me,0)!==R.check?-3:Ce(ee,ye,Me,Me)?(R.mode=31,-4):(R.havedict=1,C):k},a.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(n,o,a){var l=n("../utils/common"),f=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],_=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],h=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],g=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];o.exports=function(M,w,C,k,z,S,P,y){var x,I,U,O,N,j,D,Y,de,Ce=y.bits,ee=0,ye=0,R=0,Me=0,Qe=0,ge=0,Q=0,ae=0,Se=0,X=0,me=null,Ke=0,De=new l.Buf16(16),Be=new l.Buf16(16),We=null,ot=0;for(ee=0;ee<=15;ee++)De[ee]=0;for(ye=0;ye<k;ye++)De[w[C+ye]]++;for(Qe=Ce,Me=15;1<=Me&&De[Me]===0;Me--);if(Me<Qe&&(Qe=Me),Me===0)return z[S++]=20971520,z[S++]=20971520,y.bits=1,0;for(R=1;R<Me&&De[R]===0;R++);for(Qe<R&&(Qe=R),ee=ae=1;ee<=15;ee++)if(ae<<=1,(ae-=De[ee])<0)return-1;if(0<ae&&(M===0||Me!==1))return-1;for(Be[1]=0,ee=1;ee<15;ee++)Be[ee+1]=Be[ee]+De[ee];for(ye=0;ye<k;ye++)w[C+ye]!==0&&(P[Be[w[C+ye]]++]=ye);if(j=M===0?(me=We=P,19):M===1?(me=f,Ke-=257,We=_,ot-=257,256):(me=h,We=g,-1),ee=R,N=S,Q=ye=X=0,U=-1,O=(Se=1<<(ge=Qe))-1,M===1&&852<Se||M===2&&592<Se)return 1;for(;;){for(D=ee-Q,de=P[ye]<j?(Y=0,P[ye]):P[ye]>j?(Y=We[ot+P[ye]],me[Ke+P[ye]]):(Y=96,0),x=1<<ee-Q,R=I=1<<ge;z[N+(X>>Q)+(I-=x)]=D<<24|Y<<16|de|0,I!==0;);for(x=1<<ee-1;X&x;)x>>=1;if(x!==0?(X&=x-1,X+=x):X=0,ye++,--De[ee]==0){if(ee===Me)break;ee=w[C+P[ye]]}if(Qe<ee&&(X&O)!==U){for(Q===0&&(Q=Qe),N+=R,ae=1<<(ge=ee-Q);ge+Q<Me&&!((ae-=De[ge+Q])<=0);)ge++,ae<<=1;if(Se+=1<<ge,M===1&&852<Se||M===2&&592<Se)return 1;z[U=X&O]=Qe<<24|ge<<16|N-S|0}}return X!==0&&(z[N+X]=ee-Q<<24|64<<16|0),y.bits=Qe,0}},{"../utils/common":41}],51:[function(n,o,a){o.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(n,o,a){var l=n("../utils/common"),f=0,_=1;function h(te){for(var we=te.length;0<=--we;)te[we]=0}var g=0,M=29,w=256,C=w+1+M,k=30,z=19,S=2*C+1,P=15,y=16,x=7,I=256,U=16,O=17,N=18,j=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],D=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Y=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],de=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Ce=new Array(2*(C+2));h(Ce);var ee=new Array(2*k);h(ee);var ye=new Array(512);h(ye);var R=new Array(256);h(R);var Me=new Array(M);h(Me);var Qe,ge,Q,ae=new Array(k);function Se(te,we,B,J,L){this.static_tree=te,this.extra_bits=we,this.extra_base=B,this.elems=J,this.max_length=L,this.has_stree=te&&te.length}function X(te,we){this.dyn_tree=te,this.max_code=0,this.stat_desc=we}function me(te){return te<256?ye[te]:ye[256+(te>>>7)]}function Ke(te,we){te.pending_buf[te.pending++]=255&we,te.pending_buf[te.pending++]=we>>>8&255}function De(te,we,B){te.bi_valid>y-B?(te.bi_buf|=we<<te.bi_valid&65535,Ke(te,te.bi_buf),te.bi_buf=we>>y-te.bi_valid,te.bi_valid+=B-y):(te.bi_buf|=we<<te.bi_valid&65535,te.bi_valid+=B)}function Be(te,we,B){De(te,B[2*we],B[2*we+1])}function We(te,we){for(var B=0;B|=1&te,te>>>=1,B<<=1,0<--we;);return B>>>1}function ot(te,we,B){var J,L,ue=new Array(P+1),le=0;for(J=1;J<=P;J++)ue[J]=le=le+B[J-1]<<1;for(L=0;L<=we;L++){var ke=te[2*L+1];ke!==0&&(te[2*L]=We(ue[ke]++,ke))}}function dt(te){var we;for(we=0;we<C;we++)te.dyn_ltree[2*we]=0;for(we=0;we<k;we++)te.dyn_dtree[2*we]=0;for(we=0;we<z;we++)te.bl_tree[2*we]=0;te.dyn_ltree[2*I]=1,te.opt_len=te.static_len=0,te.last_lit=te.matches=0}function Ge(te){8<te.bi_valid?Ke(te,te.bi_buf):0<te.bi_valid&&(te.pending_buf[te.pending++]=te.bi_buf),te.bi_buf=0,te.bi_valid=0}function Te(te,we,B,J){var L=2*we,ue=2*B;return te[L]<te[ue]||te[L]===te[ue]&&J[we]<=J[B]}function je(te,we,B){for(var J=te.heap[B],L=B<<1;L<=te.heap_len&&(L<te.heap_len&&Te(we,te.heap[L+1],te.heap[L],te.depth)&&L++,!Te(we,J,te.heap[L],te.depth));)te.heap[B]=te.heap[L],B=L,L<<=1;te.heap[B]=J}function Ye(te,we,B){var J,L,ue,le,ke=0;if(te.last_lit!==0)for(;J=te.pending_buf[te.d_buf+2*ke]<<8|te.pending_buf[te.d_buf+2*ke+1],L=te.pending_buf[te.l_buf+ke],ke++,J===0?Be(te,L,we):(Be(te,(ue=R[L])+w+1,we),(le=j[ue])!==0&&De(te,L-=Me[ue],le),Be(te,ue=me(--J),B),(le=D[ue])!==0&&De(te,J-=ae[ue],le)),ke<te.last_lit;);Be(te,I,we)}function tt(te,we){var B,J,L,ue=we.dyn_tree,le=we.stat_desc.static_tree,ke=we.stat_desc.has_stree,Ne=we.stat_desc.elems,ut=-1;for(te.heap_len=0,te.heap_max=S,B=0;B<Ne;B++)ue[2*B]!==0?(te.heap[++te.heap_len]=ut=B,te.depth[B]=0):ue[2*B+1]=0;for(;te.heap_len<2;)ue[2*(L=te.heap[++te.heap_len]=ut<2?++ut:0)]=1,te.depth[L]=0,te.opt_len--,ke&&(te.static_len-=le[2*L+1]);for(we.max_code=ut,B=te.heap_len>>1;1<=B;B--)je(te,ue,B);for(L=Ne;B=te.heap[1],te.heap[1]=te.heap[te.heap_len--],je(te,ue,1),J=te.heap[1],te.heap[--te.heap_max]=B,te.heap[--te.heap_max]=J,ue[2*L]=ue[2*B]+ue[2*J],te.depth[L]=(te.depth[B]>=te.depth[J]?te.depth[B]:te.depth[J])+1,ue[2*B+1]=ue[2*J+1]=L,te.heap[1]=L++,je(te,ue,1),2<=te.heap_len;);te.heap[--te.heap_max]=te.heap[1],function(Je,Ve){var Z,ve,Re,He,Xe,rt,ft=Ve.dyn_tree,ht=Ve.max_code,Mt=Ve.stat_desc.static_tree,wt=Ve.stat_desc.has_stree,St=Ve.stat_desc.extra_bits,Rt=Ve.stat_desc.extra_base,at=Ve.stat_desc.max_length,Ot=0;for(He=0;He<=P;He++)Je.bl_count[He]=0;for(ft[2*Je.heap[Je.heap_max]+1]=0,Z=Je.heap_max+1;Z<S;Z++)at<(He=ft[2*ft[2*(ve=Je.heap[Z])+1]+1]+1)&&(He=at,Ot++),ft[2*ve+1]=He,ht<ve||(Je.bl_count[He]++,Xe=0,Rt<=ve&&(Xe=St[ve-Rt]),rt=ft[2*ve],Je.opt_len+=rt*(He+Xe),wt&&(Je.static_len+=rt*(Mt[2*ve+1]+Xe)));if(Ot!==0){do{for(He=at-1;Je.bl_count[He]===0;)He--;Je.bl_count[He]--,Je.bl_count[He+1]+=2,Je.bl_count[at]--,Ot-=2}while(0<Ot);for(He=at;He!==0;He--)for(ve=Je.bl_count[He];ve!==0;)ht<(Re=Je.heap[--Z])||(ft[2*Re+1]!==He&&(Je.opt_len+=(He-ft[2*Re+1])*ft[2*Re],ft[2*Re+1]=He),ve--)}}(te,we),ot(ue,ut,te.bl_count)}function A(te,we,B){var J,L,ue=-1,le=we[1],ke=0,Ne=7,ut=4;for(le===0&&(Ne=138,ut=3),we[2*(B+1)+1]=65535,J=0;J<=B;J++)L=le,le=we[2*(J+1)+1],++ke<Ne&&L===le||(ke<ut?te.bl_tree[2*L]+=ke:L!==0?(L!==ue&&te.bl_tree[2*L]++,te.bl_tree[2*U]++):ke<=10?te.bl_tree[2*O]++:te.bl_tree[2*N]++,ue=L,ut=(ke=0)===le?(Ne=138,3):L===le?(Ne=6,3):(Ne=7,4))}function Ae(te,we,B){var J,L,ue=-1,le=we[1],ke=0,Ne=7,ut=4;for(le===0&&(Ne=138,ut=3),J=0;J<=B;J++)if(L=le,le=we[2*(J+1)+1],!(++ke<Ne&&L===le)){if(ke<ut)for(;Be(te,L,te.bl_tree),--ke!=0;);else L!==0?(L!==ue&&(Be(te,L,te.bl_tree),ke--),Be(te,U,te.bl_tree),De(te,ke-3,2)):ke<=10?(Be(te,O,te.bl_tree),De(te,ke-3,3)):(Be(te,N,te.bl_tree),De(te,ke-11,7));ue=L,ut=(ke=0)===le?(Ne=138,3):L===le?(Ne=6,3):(Ne=7,4)}}h(ae);var $e=!1;function se(te,we,B,J){De(te,(g<<1)+(J?1:0),3),function(L,ue,le,ke){Ge(L),Ke(L,le),Ke(L,~le),l.arraySet(L.pending_buf,L.window,ue,le,L.pending),L.pending+=le}(te,we,B)}a._tr_init=function(te){$e||(function(){var we,B,J,L,ue,le=new Array(P+1);for(L=J=0;L<M-1;L++)for(Me[L]=J,we=0;we<1<<j[L];we++)R[J++]=L;for(R[J-1]=L,L=ue=0;L<16;L++)for(ae[L]=ue,we=0;we<1<<D[L];we++)ye[ue++]=L;for(ue>>=7;L<k;L++)for(ae[L]=ue<<7,we=0;we<1<<D[L]-7;we++)ye[256+ue++]=L;for(B=0;B<=P;B++)le[B]=0;for(we=0;we<=143;)Ce[2*we+1]=8,we++,le[8]++;for(;we<=255;)Ce[2*we+1]=9,we++,le[9]++;for(;we<=279;)Ce[2*we+1]=7,we++,le[7]++;for(;we<=287;)Ce[2*we+1]=8,we++,le[8]++;for(ot(Ce,C+1,le),we=0;we<k;we++)ee[2*we+1]=5,ee[2*we]=We(we,5);Qe=new Se(Ce,j,w+1,C,P),ge=new Se(ee,D,0,k,P),Q=new Se(new Array(0),Y,0,z,x)}(),$e=!0),te.l_desc=new X(te.dyn_ltree,Qe),te.d_desc=new X(te.dyn_dtree,ge),te.bl_desc=new X(te.bl_tree,Q),te.bi_buf=0,te.bi_valid=0,dt(te)},a._tr_stored_block=se,a._tr_flush_block=function(te,we,B,J){var L,ue,le=0;0<te.level?(te.strm.data_type===2&&(te.strm.data_type=function(ke){var Ne,ut=4093624447;for(Ne=0;Ne<=31;Ne++,ut>>>=1)if(1&ut&&ke.dyn_ltree[2*Ne]!==0)return f;if(ke.dyn_ltree[18]!==0||ke.dyn_ltree[20]!==0||ke.dyn_ltree[26]!==0)return _;for(Ne=32;Ne<w;Ne++)if(ke.dyn_ltree[2*Ne]!==0)return _;return f}(te)),tt(te,te.l_desc),tt(te,te.d_desc),le=function(ke){var Ne;for(A(ke,ke.dyn_ltree,ke.l_desc.max_code),A(ke,ke.dyn_dtree,ke.d_desc.max_code),tt(ke,ke.bl_desc),Ne=z-1;3<=Ne&&ke.bl_tree[2*de[Ne]+1]===0;Ne--);return ke.opt_len+=3*(Ne+1)+5+5+4,Ne}(te),L=te.opt_len+3+7>>>3,(ue=te.static_len+3+7>>>3)<=L&&(L=ue)):L=ue=B+5,B+4<=L&&we!==-1?se(te,we,B,J):te.strategy===4||ue===L?(De(te,2+(J?1:0),3),Ye(te,Ce,ee)):(De(te,4+(J?1:0),3),function(ke,Ne,ut,Je){var Ve;for(De(ke,Ne-257,5),De(ke,ut-1,5),De(ke,Je-4,4),Ve=0;Ve<Je;Ve++)De(ke,ke.bl_tree[2*de[Ve]+1],3);Ae(ke,ke.dyn_ltree,Ne-1),Ae(ke,ke.dyn_dtree,ut-1)}(te,te.l_desc.max_code+1,te.d_desc.max_code+1,le+1),Ye(te,te.dyn_ltree,te.dyn_dtree)),dt(te),J&&Ge(te)},a._tr_tally=function(te,we,B){return te.pending_buf[te.d_buf+2*te.last_lit]=we>>>8&255,te.pending_buf[te.d_buf+2*te.last_lit+1]=255&we,te.pending_buf[te.l_buf+te.last_lit]=255&B,te.last_lit++,we===0?te.dyn_ltree[2*B]++:(te.matches++,we--,te.dyn_ltree[2*(R[B]+w+1)]++,te.dyn_dtree[2*me(we)]++),te.last_lit===te.lit_bufsize-1},a._tr_align=function(te){De(te,2,3),Be(te,I,Ce),function(we){we.bi_valid===16?(Ke(we,we.bi_buf),we.bi_buf=0,we.bi_valid=0):8<=we.bi_valid&&(we.pending_buf[we.pending++]=255&we.bi_buf,we.bi_buf>>=8,we.bi_valid-=8)}(te)}},{"../utils/common":41}],53:[function(n,o,a){o.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,o,a){(function(l){(function(f,_){if(!f.setImmediate){var h,g,M,w,C=1,k={},z=!1,S=f.document,P=Object.getPrototypeOf&&Object.getPrototypeOf(f);P=P&&P.setTimeout?P:f,h={}.toString.call(f.process)==="[object process]"?function(U){process.nextTick(function(){x(U)})}:function(){if(f.postMessage&&!f.importScripts){var U=!0,O=f.onmessage;return f.onmessage=function(){U=!1},f.postMessage("","*"),f.onmessage=O,U}}()?(w="setImmediate$"+Math.random()+"$",f.addEventListener?f.addEventListener("message",I,!1):f.attachEvent("onmessage",I),function(U){f.postMessage(w+U,"*")}):f.MessageChannel?((M=new MessageChannel).port1.onmessage=function(U){x(U.data)},function(U){M.port2.postMessage(U)}):S&&"onreadystatechange"in S.createElement("script")?(g=S.documentElement,function(U){var O=S.createElement("script");O.onreadystatechange=function(){x(U),O.onreadystatechange=null,g.removeChild(O),O=null},g.appendChild(O)}):function(U){setTimeout(x,0,U)},P.setImmediate=function(U){typeof U!="function"&&(U=new Function(""+U));for(var O=new Array(arguments.length-1),N=0;N<O.length;N++)O[N]=arguments[N+1];var j={callback:U,args:O};return k[C]=j,h(C),C++},P.clearImmediate=y}function y(U){delete k[U]}function x(U){if(z)setTimeout(x,0,U);else{var O=k[U];if(O){z=!0;try{(function(N){var j=N.callback,D=N.args;switch(D.length){case 0:j();break;case 1:j(D[0]);break;case 2:j(D[0],D[1]);break;case 3:j(D[0],D[1],D[2]);break;default:j.apply(_,D)}})(O)}finally{y(U),z=!1}}}}function I(U){U.source===f&&typeof U.data=="string"&&U.data.indexOf(w)===0&&x(+U.data.slice(w.length))}})(typeof self>"u"?l===void 0?this:l:self)}).call(this,typeof So<"u"?So:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Y2);var cE=Y2.exports;const dE=b_(cE);var Z2={exports:{}};(function(e,t){(function(n,o){o()})(So,function(){function n(g,M){return typeof M>"u"?M={autoBom:!1}:typeof M!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),M={autoBom:!M}),M.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(g.type)?new Blob(["\uFEFF",g],{type:g.type}):g}function o(g,M,w){var C=new XMLHttpRequest;C.open("GET",g),C.responseType="blob",C.onload=function(){h(C.response,M,w)},C.onerror=function(){console.error("could not download file")},C.send()}function a(g){var M=new XMLHttpRequest;M.open("HEAD",g,!1);try{M.send()}catch{}return 200<=M.status&&299>=M.status}function l(g){try{g.dispatchEvent(new MouseEvent("click"))}catch{var M=document.createEvent("MouseEvents");M.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),g.dispatchEvent(M)}}var f=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof So=="object"&&So.global===So?So:void 0,_=f.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),h=f.saveAs||(typeof window!="object"||window!==f?function(){}:"download"in HTMLAnchorElement.prototype&&!_?function(g,M,w){var C=f.URL||f.webkitURL,k=document.createElement("a");M=M||g.name||"download",k.download=M,k.rel="noopener",typeof g=="string"?(k.href=g,k.origin===location.origin?l(k):a(k.href)?o(g,M,w):l(k,k.target="_blank")):(k.href=C.createObjectURL(g),setTimeout(function(){C.revokeObjectURL(k.href)},4e4),setTimeout(function(){l(k)},0))}:"msSaveOrOpenBlob"in navigator?function(g,M,w){if(M=M||g.name||"download",typeof g!="string")navigator.msSaveOrOpenBlob(n(g,w),M);else if(a(g))o(g,M,w);else{var C=document.createElement("a");C.href=g,C.target="_blank",setTimeout(function(){l(C)})}}:function(g,M,w,C){if(C=C||open("","_blank"),C&&(C.document.title=C.document.body.innerText="downloading..."),typeof g=="string")return o(g,M,w);var k=g.type==="application/octet-stream",z=/constructor/i.test(f.HTMLElement)||f.safari,S=/CriOS\/[\d]+/.test(navigator.userAgent);if((S||k&&z||_)&&typeof FileReader<"u"){var P=new FileReader;P.onloadend=function(){var I=P.result;I=S?I:I.replace(/^data:[^;]*;/,"data:attachment/file;"),C?C.location.href=I:location=I,C=null},P.readAsDataURL(g)}else{var y=f.URL||f.webkitURL,x=y.createObjectURL(g);C?C.location=x:location.href=x,C=null,setTimeout(function(){y.revokeObjectURL(x)},4e4)}});f.saveAs=h.saveAs=h,e.exports=h})})(Z2);var fE=Z2.exports;function pE(){const[e,t]=hr.useState([]),[n,o]=hr.useState([]),[a,l]=hr.useState(!1),[f,_]=hr.useState(!1),[h,g]=hr.useState(!0),M=hr.useRef(null),w=hr.useRef(null);hr.useEffect(()=>{(async()=>{const D="Xenova/modnet";uE.backends.onnx.wasm.proxy=!1,M.current??(M.current=await aE.from_pretrained(D,{device:"webgpu"})),w.current??(w.current=await lE.from_pretrained(D)),g(!1)})()},[]);const C=hr.useCallback(D=>{t(Y=>[...Y,...D.map(de=>URL.createObjectURL(de))])},[]),{getRootProps:k,getInputProps:z,isDragActive:S,isDragAccept:P,isDragReject:y}=H2({onDrop:C,accept:{"image/*":[".jpeg",".jpg",".png"]}}),x=D=>{t(Y=>Y.filter((de,Ce)=>Ce!==D)),o(Y=>Y.filter((de,Ce)=>Ce!==D))},I=async()=>{l(!0),o([]);const D=M.current,Y=w.current;for(let de=0;de<e.length;++de){const Ce=await v1.fromURL(e[de]),{pixel_values:ee}=await Y(Ce),{output:ye}=await D({input:ee}),R=(await v1.fromTensor(ye[0].mul(255).to("uint8")).resize(Ce.width,Ce.height)).data,Me=document.createElement("canvas");Me.width=Ce.width,Me.height=Ce.height;const Qe=Me.getContext("2d");Qe.drawImage(Ce.toCanvas(),0,0);const ge=Qe.getImageData(0,0,Ce.width,Ce.height);for(let Q=0;Q<R.length;++Q)ge.data[4*Q+3]=R[Q];Qe.putImageData(ge,0,0),o(Q=>[...Q,Me.toDataURL("image/png")])}l(!1),_(!0)},U=async()=>{const D=new dE;for(let de=0;de<e.length;de++){const Ce=document.createElement("canvas"),ee=Ce.getContext("2d"),ye=new Image;ye.src=n[de]||e[de],await new Promise(R=>{ye.onload=()=>{Ce.width=ye.width,Ce.height=ye.height,ee.drawImage(ye,0,0),Ce.toBlob(Me=>{Me&&D.file(`image${de+1}.png`,Me),R(null)},"image/png")}})}const Y=await D.generateAsync({type:"blob"});fE.saveAs(Y,"images.zip")},O=()=>{t([]),o([]),_(!1)},N=async D=>{try{const de=await(await fetch(D)).blob(),Ce=new ClipboardItem({[de.type]:de});await navigator.clipboard.write([Ce]),console.log("Image copied to clipboard")}catch(Y){console.error("Failed to copy image: ",Y)}},j=D=>{const Y=document.createElement("a");Y.href=D,Y.download="image.png",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y)};return h?Vr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:Vr.jsxs("div",{className:"text-center",children:[Vr.jsx("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-white mb-4"}),Vr.jsx("p",{className:"text-lg",children:"Loading background removal model..."})]})}):Vr.jsx("div",{className:"min-h-screen bg-black text-white p-8",children:Vr.jsxs("div",{className:"max-w-4xl mx-auto",children:[Vr.jsx("h1",{className:"text-4xl font-bold mb-2 text-center",children:"Remove Background WebGPU"}),Vr.jsxs("h2",{className:"text-lg font-semibold mb-8 text-center",children:["In-browser background removal, powered by"," ",Vr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),Vr.jsxs("div",{...k(),className:`p-8 mb-8 border-2 border-dashed rounded-lg text-center cursor-pointer transition-colors duration-300 ease-in-out + ${P?"border-green-500 bg-green-900/20":""} + ${y?"border-red-500 bg-red-900/20":""} + ${S?"border-blue-500 bg-blue-900/20":"border-gray-700 hover:border-blue-500 hover:bg-blue-900/10"} + `,children:[Vr.jsx("input",{...z(),className:"hidden"}),Vr.jsx("p",{className:"text-lg mb-2",children:S?"Drop the images here...":"Drag and drop some images here"}),Vr.jsx("p",{className:"text-sm text-gray-400",children:"or click to select files"})]}),Vr.jsxs("div",{className:"flex flex-col items-center gap-4 mb-8",children:[Vr.jsx("button",{onClick:I,disabled:a||e.length===0,className:"px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-black disabled:bg-gray-700 disabled:cursor-not-allowed transition-colors duration-200 text-lg font-semibold",children:a?"Processing...":"Process"}),Vr.jsxs("div",{className:"flex gap-4",children:[Vr.jsx("button",{onClick:U,disabled:!f,className:"px-3 py-1 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 focus:ring-offset-black disabled:bg-gray-700 disabled:cursor-not-allowed transition-colors duration-200 text-sm",children:"Download as ZIP"}),Vr.jsx("button",{onClick:O,className:"px-3 py-1 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-black transition-colors duration-200 text-sm",children:"Clear All"})]})]}),Vr.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6",children:e.map((D,Y)=>Vr.jsxs("div",{className:"relative group",children:[Vr.jsx("img",{src:n[Y]||D,alt:`Image ${Y+1}`,className:"rounded-lg object-cover w-full h-48"}),n[Y]&&Vr.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-70 opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-lg flex items-center justify-center",children:[Vr.jsx("button",{onClick:()=>N(n[Y]||D),className:"mx-2 px-3 py-1 bg-white text-gray-900 rounded-md hover:bg-gray-200 transition-colors duration-200 text-sm","aria-label":`Copy image ${Y+1} to clipboard`,children:"Copy"}),Vr.jsx("button",{onClick:()=>j(n[Y]||D),className:"mx-2 px-3 py-1 bg-white text-gray-900 rounded-md hover:bg-gray-200 transition-colors duration-200 text-sm","aria-label":`Download image ${Y+1}`,children:"Download"})]}),Vr.jsx("button",{onClick:()=>x(Y),className:"absolute top-2 right-2 bg-black bg-opacity-50 text-white w-6 h-6 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300 hover:bg-opacity-70","aria-label":`Remove image ${Y+1}`,children:"✕"})]},Y))})]})})}F2(document.getElementById("root")).render(Vr.jsx(hr.StrictMode,{children:Vr.jsx(pE,{})}));