var DM=Object.defineProperty;var LM=(e,t,r)=>t in e?DM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var He=(e,t,r)=>LM(e,typeof t!="symbol"?t+"":t,r);(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 p of l.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&o(p)}).observe(document,{childList:!0,subtree:!0});function r(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=r(a);fetch(a.href,l)}})();var Co=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function k_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var k1={exports:{}},Jh={},S1={exports:{}},kr={};/** * @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 Qp=Symbol.for("react.element"),RM=Symbol.for("react.portal"),BM=Symbol.for("react.fragment"),NM=Symbol.for("react.strict_mode"),jM=Symbol.for("react.profiler"),UM=Symbol.for("react.provider"),VM=Symbol.for("react.context"),WM=Symbol.for("react.forward_ref"),GM=Symbol.for("react.suspense"),HM=Symbol.for("react.memo"),qM=Symbol.for("react.lazy"),rv=Symbol.iterator;function KM(e){return e===null||typeof e!="object"?null:(e=rv&&e[rv]||e["@@iterator"],typeof e=="function"?e:null)}var E1={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C1=Object.assign,P1={};function ou(e,t,r){this.props=e,this.context=t,this.refs=P1,this.updater=r||E1}ou.prototype.isReactComponent={};ou.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")};ou.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function $1(){}$1.prototype=ou.prototype;function S_(e,t,r){this.props=e,this.context=t,this.refs=P1,this.updater=r||E1}var E_=S_.prototype=new $1;E_.constructor=S_;C1(E_,ou.prototype);E_.isPureReactComponent=!0;var nv=Array.isArray,A1=Object.prototype.hasOwnProperty,C_={current:null},I1={key:!0,ref:!0,__self:!0,__source:!0};function F1(e,t,r){var o,a={},l=null,p=null;if(t!=null)for(o in t.ref!==void 0&&(p=t.ref),t.key!==void 0&&(l=""+t.key),t)A1.call(t,o)&&!I1.hasOwnProperty(o)&&(a[o]=t[o]);var _=arguments.length-2;if(_===1)a.children=r;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:Qp,type:e,key:l,ref:p,props:a,_owner:C_.current}}function XM(e,t){return{$$typeof:Qp,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function P_(e){return typeof e=="object"&&e!==null&&e.$$typeof===Qp}function QM(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var iv=/\/+/g;function tg(e,t){return typeof e=="object"&&e!==null&&e.key!=null?QM(""+e.key):t.toString(36)}function fh(e,t,r,o,a){var l=typeof e;(l==="undefined"||l==="boolean")&&(e=null);var p=!1;if(e===null)p=!0;else switch(l){case"string":case"number":p=!0;break;case"object":switch(e.$$typeof){case Qp:case RM:p=!0}}if(p)return p=e,a=a(p),e=o===""?"."+tg(p,0):o,nv(a)?(r="",e!=null&&(r=e.replace(iv,"$&/")+"/"),fh(a,t,r,"",function(g){return g})):a!=null&&(P_(a)&&(a=XM(a,r+(!a.key||p&&p.key===a.key?"":(""+a.key).replace(iv,"$&/")+"/")+e)),t.push(a)),1;if(p=0,o=o===""?".":o+":",nv(e))for(var _=0;_<e.length;_++){l=e[_];var h=o+tg(l,_);p+=fh(l,t,r,h,a)}else if(h=KM(e),typeof h=="function")for(e=h.call(e),_=0;!(l=e.next()).done;)l=l.value,h=o+tg(l,_++),p+=fh(l,t,r,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 p}function Kf(e,t,r){if(e==null)return e;var o=[],a=0;return fh(e,o,"","",function(l){return t.call(r,l,a++)}),o}function YM(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ri={current:null},hh={transition:null},ZM={ReactCurrentDispatcher:ri,ReactCurrentBatchConfig:hh,ReactCurrentOwner:C_};function O1(){throw Error("act(...) is not supported in production builds of React.")}kr.Children={map:Kf,forEach:function(e,t,r){Kf(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return Kf(e,function(){t++}),t},toArray:function(e){return Kf(e,function(t){return t})||[]},only:function(e){if(!P_(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};kr.Component=ou;kr.Fragment=BM;kr.Profiler=jM;kr.PureComponent=S_;kr.StrictMode=NM;kr.Suspense=GM;kr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ZM;kr.act=O1;kr.cloneElement=function(e,t,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var o=C1({},e.props),a=e.key,l=e.ref,p=e._owner;if(t!=null){if(t.ref!==void 0&&(l=t.ref,p=C_.current),t.key!==void 0&&(a=""+t.key),e.type&&e.type.defaultProps)var _=e.type.defaultProps;for(h in t)A1.call(t,h)&&!I1.hasOwnProperty(h)&&(o[h]=t[h]===void 0&&_!==void 0?_[h]:t[h])}var h=arguments.length-2;if(h===1)o.children=r;else if(1<h){_=Array(h);for(var g=0;g<h;g++)_[g]=arguments[g+2];o.children=_}return{$$typeof:Qp,type:e.type,key:a,ref:l,props:o,_owner:p}};kr.createContext=function(e){return e={$$typeof:VM,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:UM,_context:e},e.Consumer=e};kr.createElement=F1;kr.createFactory=function(e){var t=F1.bind(null,e);return t.type=e,t};kr.createRef=function(){return{current:null}};kr.forwardRef=function(e){return{$$typeof:WM,render:e}};kr.isValidElement=P_;kr.lazy=function(e){return{$$typeof:qM,_payload:{_status:-1,_result:e},_init:YM}};kr.memo=function(e,t){return{$$typeof:HM,type:e,compare:t===void 0?null:t}};kr.startTransition=function(e){var t=hh.transition;hh.transition={};try{e()}finally{hh.transition=t}};kr.unstable_act=O1;kr.useCallback=function(e,t){return ri.current.useCallback(e,t)};kr.useContext=function(e){return ri.current.useContext(e)};kr.useDebugValue=function(){};kr.useDeferredValue=function(e){return ri.current.useDeferredValue(e)};kr.useEffect=function(e,t){return ri.current.useEffect(e,t)};kr.useId=function(){return ri.current.useId()};kr.useImperativeHandle=function(e,t,r){return ri.current.useImperativeHandle(e,t,r)};kr.useInsertionEffect=function(e,t){return ri.current.useInsertionEffect(e,t)};kr.useLayoutEffect=function(e,t){return ri.current.useLayoutEffect(e,t)};kr.useMemo=function(e,t){return ri.current.useMemo(e,t)};kr.useReducer=function(e,t,r){return ri.current.useReducer(e,t,r)};kr.useRef=function(e){return ri.current.useRef(e)};kr.useState=function(e){return ri.current.useState(e)};kr.useSyncExternalStore=function(e,t,r){return ri.current.useSyncExternalStore(e,t,r)};kr.useTransition=function(){return ri.current.useTransition()};kr.version="18.3.1";S1.exports=kr;var fr=S1.exports;const JM=k_(fr);/** * @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 eT=fr,tT=Symbol.for("react.element"),rT=Symbol.for("react.fragment"),nT=Object.prototype.hasOwnProperty,iT=eT.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,oT={key:!0,ref:!0,__self:!0,__source:!0};function z1(e,t,r){var o,a={},l=null,p=null;r!==void 0&&(l=""+r),t.key!==void 0&&(l=""+t.key),t.ref!==void 0&&(p=t.ref);for(o in t)nT.call(t,o)&&!oT.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:tT,type:e,key:l,ref:p,props:a,_owner:iT.current}}Jh.Fragment=rT;Jh.jsx=z1;Jh.jsxs=z1;k1.exports=Jh;var Cr=k1.exports,D1={exports:{}},bi={},L1={exports:{}},R1={};/** * @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(X,ie){var Me=X.length;X.push(ie);e:for(;0<Me;){var Q=Me-1>>>1,ge=X[Q];if(0<a(ge,ie))X[Q]=ie,X[Me]=ge,Me=Q;else break e}}function r(X){return X.length===0?null:X[0]}function o(X){if(X.length===0)return null;var ie=X[0],Me=X.pop();if(Me!==ie){X[0]=Me;e:for(var Q=0,ge=X.length,Ke=ge>>>1;Q<Ke;){var Le=2*(Q+1)-1,Be=X[Le],We=Le+1,st=X[We];if(0>a(Be,Me))We<ge&&0>a(st,Be)?(X[Q]=st,X[We]=Me,Q=We):(X[Q]=Be,X[Le]=Me,Q=Le);else if(We<ge&&0>a(st,Me))X[Q]=st,X[We]=Me,Q=We;else break e}}return ie}function a(X,ie){var Me=X.sortIndex-ie.sortIndex;return Me!==0?Me:X.id-ie.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var p=Date,_=p.now();e.unstable_now=function(){return p.now()-_}}var h=[],g=[],M=1,y=null,E=3,T=!1,O=!1,S=!1,C=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,b=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(X){for(var ie=r(g);ie!==null;){if(ie.callback===null)o(g);else if(ie.startTime<=X)o(g),ie.sortIndex=ie.expirationTime,t(h,ie);else break;ie=r(g)}}function U(X){if(S=!1,I(X),!O)if(r(h)!==null)O=!0,Xe(z);else{var ie=r(g);ie!==null&&me(U,ie.startTime-X)}}function z(X,ie){O=!1,S&&(S=!1,w(N),N=-1),T=!0;var Me=E;try{for(I(ie),y=r(h);y!==null&&(!(y.expirationTime>ie)||X&&!xe());){var Q=y.callback;if(typeof Q=="function"){y.callback=null,E=y.priorityLevel;var ge=Q(y.expirationTime<=ie);ie=e.unstable_now(),typeof ge=="function"?y.callback=ge:y===r(h)&&o(h),I(ie)}else o(h);y=r(h)}if(y!==null)var Ke=!0;else{var Le=r(g);Le!==null&&me(U,Le.startTime-ie),Ke=!1}return Ke}finally{y=null,E=Me,T=!1}}var B=!1,j=null,N=-1,ae=5,ce=-1;function xe(){return!(e.unstable_now()-ce<ae)}function Y(){if(j!==null){var X=e.unstable_now();ce=X;var ie=!0;try{ie=j(!0,X)}finally{ie?_e():(B=!1,j=null)}}else B=!1}var _e;if(typeof b=="function")_e=function(){b(Y)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,Se=L.port2;L.port1.onmessage=Y,_e=function(){Se.postMessage(null)}}else _e=function(){C(Y,0)};function Xe(X){j=X,B||(B=!0,_e())}function me(X,ie){N=C(function(){X(e.unstable_now())},ie)}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(X){X.callback=null},e.unstable_continueExecution=function(){O||T||(O=!0,Xe(z))},e.unstable_forceFrameRate=function(X){0>X||125<X?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ae=0<X?Math.floor(1e3/X):5},e.unstable_getCurrentPriorityLevel=function(){return E},e.unstable_getFirstCallbackNode=function(){return r(h)},e.unstable_next=function(X){switch(E){case 1:case 2:case 3:var ie=3;break;default:ie=E}var Me=E;E=ie;try{return X()}finally{E=Me}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(X,ie){switch(X){case 1:case 2:case 3:case 4:case 5:break;default:X=3}var Me=E;E=X;try{return ie()}finally{E=Me}},e.unstable_scheduleCallback=function(X,ie,Me){var Q=e.unstable_now();switch(typeof Me=="object"&&Me!==null?(Me=Me.delay,Me=typeof Me=="number"&&0<Me?Q+Me:Q):Me=Q,X){case 1:var ge=-1;break;case 2:ge=250;break;case 5:ge=1073741823;break;case 4:ge=1e4;break;default:ge=5e3}return ge=Me+ge,X={id:M++,callback:ie,priorityLevel:X,startTime:Me,expirationTime:ge,sortIndex:-1},Me>Q?(X.sortIndex=Me,t(g,X),r(h)===null&&X===r(g)&&(S?(w(N),N=-1):S=!0,me(U,Me-Q))):(X.sortIndex=ge,t(h,X),O||T||(O=!0,Xe(z))),X},e.unstable_shouldYield=xe,e.unstable_wrapCallback=function(X){var ie=E;return function(){var Me=E;E=ie;try{return X.apply(this,arguments)}finally{E=Me}}}})(R1);L1.exports=R1;var sT=L1.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 aT=fr,vi=sT;function xt(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);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 B1=new Set,Ip={};function fa(e,t){Zl(e,t),Zl(e+"Capture",t)}function Zl(e,t){for(Ip[e]=t,e=0;e<t.length;e++)B1.add(t[e])}var Io=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Cg=Object.prototype.hasOwnProperty,lT=/^[: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]*$/,ov={},sv={};function uT(e){return Cg.call(sv,e)?!0:Cg.call(ov,e)?!1:lT.test(e)?sv[e]=!0:(ov[e]=!0,!1)}function cT(e,t,r,o){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function dT(e,t,r,o){if(t===null||typeof t>"u"||cT(e,t,r,o))return!0;if(o)return!1;if(r!==null)switch(r.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 ni(e,t,r,o,a,l,p){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=p}var Nn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Nn[e]=new ni(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Nn[t]=new ni(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Nn[e]=new ni(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Nn[e]=new ni(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){Nn[e]=new ni(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Nn[e]=new ni(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Nn[e]=new ni(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Nn[e]=new ni(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Nn[e]=new ni(e,5,!1,e.toLowerCase(),null,!1,!1)});var $_=/[\-:]([a-z])/g;function A_(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($_,A_);Nn[t]=new ni(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($_,A_);Nn[t]=new ni(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($_,A_);Nn[t]=new ni(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Nn[e]=new ni(e,1,!1,e.toLowerCase(),null,!1,!1)});Nn.xlinkHref=new ni("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Nn[e]=new ni(e,1,!1,e.toLowerCase(),null,!0,!0)});function I_(e,t,r,o){var a=Nn.hasOwnProperty(t)?Nn[t]:null;(a!==null?a.type!==0:o||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(dT(t,r,a,o)&&(r=null),o||a===null?uT(t)&&(r===null?e.removeAttribute(t):e.setAttribute(t,""+r)):a.mustUseProperty?e[a.propertyName]=r===null?a.type===3?!1:"":r:(t=a.attributeName,o=a.attributeNamespace,r===null?e.removeAttribute(t):(a=a.type,r=a===3||a===4&&r===!0?"":""+r,o?e.setAttributeNS(o,t,r):e.setAttribute(t,r))))}var Do=aT.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Xf=Symbol.for("react.element"),Ol=Symbol.for("react.portal"),zl=Symbol.for("react.fragment"),F_=Symbol.for("react.strict_mode"),Pg=Symbol.for("react.profiler"),N1=Symbol.for("react.provider"),j1=Symbol.for("react.context"),O_=Symbol.for("react.forward_ref"),$g=Symbol.for("react.suspense"),Ag=Symbol.for("react.suspense_list"),z_=Symbol.for("react.memo"),us=Symbol.for("react.lazy"),U1=Symbol.for("react.offscreen"),av=Symbol.iterator;function cp(e){return e===null||typeof e!="object"?null:(e=av&&e[av]||e["@@iterator"],typeof e=="function"?e:null)}var ln=Object.assign,rg;function wp(e){if(rg===void 0)try{throw Error()}catch(r){var t=r.stack.trim().match(/\n( *(at )?)/);rg=t&&t[1]||""}return` `+rg+e}var ng=!1;function ig(e,t){if(!e||ng)return"";ng=!0;var r=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(` `),p=a.length-1,_=l.length-1;1<=p&&0<=_&&a[p]!==l[_];)_--;for(;1<=p&&0<=_;p--,_--)if(a[p]!==l[_]){if(p!==1||_!==1)do if(p--,_--,0>_||a[p]!==l[_]){var h=` `+a[p].replace(" at new "," at ");return e.displayName&&h.includes("<anonymous>")&&(h=h.replace("<anonymous>",e.displayName)),h}while(1<=p&&0<=_);break}}}finally{ng=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?wp(e):""}function pT(e){switch(e.tag){case 5:return wp(e.type);case 16:return wp("Lazy");case 13:return wp("Suspense");case 19:return wp("SuspenseList");case 0:case 2:case 15:return e=ig(e.type,!1),e;case 11:return e=ig(e.type.render,!1),e;case 1:return e=ig(e.type,!0),e;default:return""}}function Ig(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 zl:return"Fragment";case Ol:return"Portal";case Pg:return"Profiler";case F_:return"StrictMode";case $g:return"Suspense";case Ag:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case j1:return(e.displayName||"Context")+".Consumer";case N1:return(e._context.displayName||"Context")+".Provider";case O_:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case z_:return t=e.displayName||null,t!==null?t:Ig(e.type)||"Memo";case us:t=e._payload,e=e._init;try{return Ig(e(t))}catch{}}return null}function fT(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 Ig(t);case 8:return t===F_?"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 Ms(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function V1(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function hT(e){var t=V1(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,l=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(p){o=""+p,l.call(this,p)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return o},setValue:function(p){o=""+p},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Qf(e){e._valueTracker||(e._valueTracker=hT(e))}function W1(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),o="";return e&&(o=V1(e)?e.checked?"true":"false":e.value),e=o,e!==r?(t.setValue(e),!0):!1}function Sh(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 Fg(e,t){var r=t.checked;return ln({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function lv(e,t){var r=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;r=Ms(t.value!=null?t.value:r),e._wrapperState={initialChecked:o,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function G1(e,t){t=t.checked,t!=null&&I_(e,"checked",t,!1)}function Og(e,t){G1(e,t);var r=Ms(t.value),o=t.type;if(r!=null)o==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?zg(e,t.type,r):t.hasOwnProperty("defaultValue")&&zg(e,t.type,Ms(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function uv(e,t,r){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,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function zg(e,t,r){(t!=="number"||Sh(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var yp=Array.isArray;function Hl(e,t,r,o){if(e=e.options,t){t={};for(var a=0;a<r.length;a++)t["$"+r[a]]=!0;for(r=0;r<e.length;r++)a=t.hasOwnProperty("$"+e[r].value),e[r].selected!==a&&(e[r].selected=a),a&&o&&(e[r].defaultSelected=!0)}else{for(r=""+Ms(r),t=null,a=0;a<e.length;a++){if(e[a].value===r){e[a].selected=!0,o&&(e[a].defaultSelected=!0);return}t!==null||e[a].disabled||(t=e[a])}t!==null&&(t.selected=!0)}}function Dg(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(xt(91));return ln({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function cv(e,t){var r=t.value;if(r==null){if(r=t.children,t=t.defaultValue,r!=null){if(t!=null)throw Error(xt(92));if(yp(r)){if(1<r.length)throw Error(xt(93));r=r[0]}t=r}t==null&&(t=""),r=t}e._wrapperState={initialValue:Ms(r)}}function H1(e,t){var r=Ms(t.value),o=Ms(t.defaultValue);r!=null&&(r=""+r,r!==e.value&&(e.value=r),t.defaultValue==null&&e.defaultValue!==r&&(e.defaultValue=r)),o!=null&&(e.defaultValue=""+o)}function dv(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function q1(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 Lg(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?q1(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var Yf,K1=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,r,o,a){MSApp.execUnsafeLocalFunction(function(){return e(t,r,o,a)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(Yf=Yf||document.createElement("div"),Yf.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=Yf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fp(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Mp={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},mT=["Webkit","ms","Moz","O"];Object.keys(Mp).forEach(function(e){mT.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Mp[t]=Mp[e]})});function X1(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Mp.hasOwnProperty(e)&&Mp[e]?(""+t).trim():t+"px"}function Q1(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var o=r.indexOf("--")===0,a=X1(r,t[r],o);r==="float"&&(r="cssFloat"),o?e.setProperty(r,a):e[r]=a}}var gT=ln({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 Rg(e,t){if(t){if(gT[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(xt(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(xt(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(xt(61))}if(t.style!=null&&typeof t.style!="object")throw Error(xt(62))}}function Bg(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 Ng=null;function D_(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var jg=null,ql=null,Kl=null;function pv(e){if(e=Jp(e)){if(typeof jg!="function")throw Error(xt(280));var t=e.stateNode;t&&(t=im(t),jg(e.stateNode,e.type,t))}}function Y1(e){ql?Kl?Kl.push(e):Kl=[e]:ql=e}function Z1(){if(ql){var e=ql,t=Kl;if(Kl=ql=null,pv(e),t)for(e=0;e<t.length;e++)pv(t[e])}}function J1(e,t){return e(t)}function eb(){}var og=!1;function tb(e,t,r){if(og)return e(t,r);og=!0;try{return J1(e,t,r)}finally{og=!1,(ql!==null||Kl!==null)&&(eb(),Z1())}}function Op(e,t){var r=e.stateNode;if(r===null)return null;var o=im(r);if(o===null)return null;r=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(r&&typeof r!="function")throw Error(xt(231,t,typeof r));return r}var Ug=!1;if(Io)try{var dp={};Object.defineProperty(dp,"passive",{get:function(){Ug=!0}}),window.addEventListener("test",dp,dp),window.removeEventListener("test",dp,dp)}catch{Ug=!1}function _T(e,t,r,o,a,l,p,_,h){var g=Array.prototype.slice.call(arguments,3);try{t.apply(r,g)}catch(M){this.onError(M)}}var Tp=!1,Eh=null,Ch=!1,Vg=null,wT={onError:function(e){Tp=!0,Eh=e}};function yT(e,t,r,o,a,l,p,_,h){Tp=!1,Eh=null,_T.apply(wT,arguments)}function vT(e,t,r,o,a,l,p,_,h){if(yT.apply(this,arguments),Tp){if(Tp){var g=Eh;Tp=!1,Eh=null}else throw Error(xt(198));Ch||(Ch=!0,Vg=g)}}function ha(e){var t=e,r=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(r=t.return),e=t.return;while(e)}return t.tag===3?r:null}function rb(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 fv(e){if(ha(e)!==e)throw Error(xt(188))}function bT(e){var t=e.alternate;if(!t){if(t=ha(e),t===null)throw Error(xt(188));return t!==e?null:e}for(var r=e,o=t;;){var a=r.return;if(a===null)break;var l=a.alternate;if(l===null){if(o=a.return,o!==null){r=o;continue}break}if(a.child===l.child){for(l=a.child;l;){if(l===r)return fv(a),e;if(l===o)return fv(a),t;l=l.sibling}throw Error(xt(188))}if(r.return!==o.return)r=a,o=l;else{for(var p=!1,_=a.child;_;){if(_===r){p=!0,r=a,o=l;break}if(_===o){p=!0,o=a,r=l;break}_=_.sibling}if(!p){for(_=l.child;_;){if(_===r){p=!0,r=l,o=a;break}if(_===o){p=!0,o=l,r=a;break}_=_.sibling}if(!p)throw Error(xt(189))}}if(r.alternate!==o)throw Error(xt(190))}if(r.tag!==3)throw Error(xt(188));return r.stateNode.current===r?e:t}function nb(e){return e=bT(e),e!==null?ib(e):null}function ib(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=ib(e);if(t!==null)return t;e=e.sibling}return null}var ob=vi.unstable_scheduleCallback,hv=vi.unstable_cancelCallback,xT=vi.unstable_shouldYield,MT=vi.unstable_requestPaint,mn=vi.unstable_now,TT=vi.unstable_getCurrentPriorityLevel,L_=vi.unstable_ImmediatePriority,sb=vi.unstable_UserBlockingPriority,Ph=vi.unstable_NormalPriority,kT=vi.unstable_LowPriority,ab=vi.unstable_IdlePriority,em=null,co=null;function ST(e){if(co&&typeof co.onCommitFiberRoot=="function")try{co.onCommitFiberRoot(em,e,void 0,(e.current.flags&128)===128)}catch{}}var Qi=Math.clz32?Math.clz32:PT,ET=Math.log,CT=Math.LN2;function PT(e){return e>>>=0,e===0?32:31-(ET(e)/CT|0)|0}var Zf=64,Jf=4194304;function vp(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 $h(e,t){var r=e.pendingLanes;if(r===0)return 0;var o=0,a=e.suspendedLanes,l=e.pingedLanes,p=r&268435455;if(p!==0){var _=p&~a;_!==0?o=vp(_):(l&=p,l!==0&&(o=vp(l)))}else p=r&~a,p!==0?o=vp(p):l!==0&&(o=vp(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|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0<t;)r=31-Qi(t),a=1<<r,o|=e[r],t&=~a;return o}function $T(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 AT(e,t){for(var r=e.suspendedLanes,o=e.pingedLanes,a=e.expirationTimes,l=e.pendingLanes;0<l;){var p=31-Qi(l),_=1<<p,h=a[p];h===-1?(!(_&r)||_&o)&&(a[p]=$T(_,t)):h<=t&&(e.expiredLanes|=_),l&=~_}}function Wg(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function lb(){var e=Zf;return Zf<<=1,!(Zf&4194240)&&(Zf=64),e}function sg(e){for(var t=[],r=0;31>r;r++)t.push(e);return t}function Yp(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Qi(t),e[t]=r}function IT(e,t){var r=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<r;){var a=31-Qi(r),l=1<<a;t[a]=0,o[a]=-1,e[a]=-1,r&=~l}}function R_(e,t){var r=e.entangledLanes|=t;for(e=e.entanglements;r;){var o=31-Qi(r),a=1<<o;a&t|e[o]&t&&(e[o]|=t),r&=~a}}var Ur=0;function ub(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var cb,B_,db,pb,fb,Gg=!1,eh=[],ms=null,gs=null,_s=null,zp=new Map,Dp=new Map,ds=[],FT="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 mv(e,t){switch(e){case"focusin":case"focusout":ms=null;break;case"dragenter":case"dragleave":gs=null;break;case"mouseover":case"mouseout":_s=null;break;case"pointerover":case"pointerout":zp.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Dp.delete(t.pointerId)}}function pp(e,t,r,o,a,l){return e===null||e.nativeEvent!==l?(e={blockedOn:t,domEventName:r,eventSystemFlags:o,nativeEvent:l,targetContainers:[a]},t!==null&&(t=Jp(t),t!==null&&B_(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,a!==null&&t.indexOf(a)===-1&&t.push(a),e)}function OT(e,t,r,o,a){switch(t){case"focusin":return ms=pp(ms,e,t,r,o,a),!0;case"dragenter":return gs=pp(gs,e,t,r,o,a),!0;case"mouseover":return _s=pp(_s,e,t,r,o,a),!0;case"pointerover":var l=a.pointerId;return zp.set(l,pp(zp.get(l)||null,e,t,r,o,a)),!0;case"gotpointercapture":return l=a.pointerId,Dp.set(l,pp(Dp.get(l)||null,e,t,r,o,a)),!0}return!1}function hb(e){var t=na(e.target);if(t!==null){var r=ha(t);if(r!==null){if(t=r.tag,t===13){if(t=rb(r),t!==null){e.blockedOn=t,fb(e.priority,function(){db(r)});return}}else if(t===3&&r.stateNode.current.memoizedState.isDehydrated){e.blockedOn=r.tag===3?r.stateNode.containerInfo:null;return}}}e.blockedOn=null}function mh(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var r=Hg(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(r===null){r=e.nativeEvent;var o=new r.constructor(r.type,r);Ng=o,r.target.dispatchEvent(o),Ng=null}else return t=Jp(r),t!==null&&B_(t),e.blockedOn=r,!1;t.shift()}return!0}function gv(e,t,r){mh(e)&&r.delete(t)}function zT(){Gg=!1,ms!==null&&mh(ms)&&(ms=null),gs!==null&&mh(gs)&&(gs=null),_s!==null&&mh(_s)&&(_s=null),zp.forEach(gv),Dp.forEach(gv)}function fp(e,t){e.blockedOn===t&&(e.blockedOn=null,Gg||(Gg=!0,vi.unstable_scheduleCallback(vi.unstable_NormalPriority,zT)))}function Lp(e){function t(a){return fp(a,e)}if(0<eh.length){fp(eh[0],e);for(var r=1;r<eh.length;r++){var o=eh[r];o.blockedOn===e&&(o.blockedOn=null)}}for(ms!==null&&fp(ms,e),gs!==null&&fp(gs,e),_s!==null&&fp(_s,e),zp.forEach(t),Dp.forEach(t),r=0;r<ds.length;r++)o=ds[r],o.blockedOn===e&&(o.blockedOn=null);for(;0<ds.length&&(r=ds[0],r.blockedOn===null);)hb(r),r.blockedOn===null&&ds.shift()}var Xl=Do.ReactCurrentBatchConfig,Ah=!0;function DT(e,t,r,o){var a=Ur,l=Xl.transition;Xl.transition=null;try{Ur=1,N_(e,t,r,o)}finally{Ur=a,Xl.transition=l}}function LT(e,t,r,o){var a=Ur,l=Xl.transition;Xl.transition=null;try{Ur=4,N_(e,t,r,o)}finally{Ur=a,Xl.transition=l}}function N_(e,t,r,o){if(Ah){var a=Hg(e,t,r,o);if(a===null)gg(e,t,o,Ih,r),mv(e,o);else if(OT(a,e,t,r,o))o.stopPropagation();else if(mv(e,o),t&4&&-1<FT.indexOf(e)){for(;a!==null;){var l=Jp(a);if(l!==null&&cb(l),l=Hg(e,t,r,o),l===null&&gg(e,t,o,Ih,r),l===a)break;a=l}a!==null&&o.stopPropagation()}else gg(e,t,o,null,r)}}var Ih=null;function Hg(e,t,r,o){if(Ih=null,e=D_(o),e=na(e),e!==null)if(t=ha(e),t===null)e=null;else if(r=t.tag,r===13){if(e=rb(t),e!==null)return e;e=null}else if(r===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Ih=e,null}function mb(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(TT()){case L_:return 1;case sb:return 4;case Ph:case kT:return 16;case ab:return 536870912;default:return 16}default:return 16}}var fs=null,j_=null,gh=null;function gb(){if(gh)return gh;var e,t=j_,r=t.length,o,a="value"in fs?fs.value:fs.textContent,l=a.length;for(e=0;e<r&&t[e]===a[e];e++);var p=r-e;for(o=1;o<=p&&t[r-o]===a[l-o];o++);return gh=a.slice(e,1<o?1-o:void 0)}function _h(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 th(){return!0}function _v(){return!1}function xi(e){function t(r,o,a,l,p){this._reactName=r,this._targetInst=a,this.type=o,this.nativeEvent=l,this.target=p,this.currentTarget=null;for(var _ in e)e.hasOwnProperty(_)&&(r=e[_],this[_]=r?r(l):l[_]);return this.isDefaultPrevented=(l.defaultPrevented!=null?l.defaultPrevented:l.returnValue===!1)?th:_v,this.isPropagationStopped=_v,this}return ln(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var r=this.nativeEvent;r&&(r.preventDefault?r.preventDefault():typeof r.returnValue!="unknown"&&(r.returnValue=!1),this.isDefaultPrevented=th)},stopPropagation:function(){var r=this.nativeEvent;r&&(r.stopPropagation?r.stopPropagation():typeof r.cancelBubble!="unknown"&&(r.cancelBubble=!0),this.isPropagationStopped=th)},persist:function(){},isPersistent:th}),t}var su={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},U_=xi(su),Zp=ln({},su,{view:0,detail:0}),RT=xi(Zp),ag,lg,hp,tm=ln({},Zp,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:V_,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!==hp&&(hp&&e.type==="mousemove"?(ag=e.screenX-hp.screenX,lg=e.screenY-hp.screenY):lg=ag=0,hp=e),ag)},movementY:function(e){return"movementY"in e?e.movementY:lg}}),wv=xi(tm),BT=ln({},tm,{dataTransfer:0}),NT=xi(BT),jT=ln({},Zp,{relatedTarget:0}),ug=xi(jT),UT=ln({},su,{animationName:0,elapsedTime:0,pseudoElement:0}),VT=xi(UT),WT=ln({},su,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),GT=xi(WT),HT=ln({},su,{data:0}),yv=xi(HT),qT={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},KT={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"},XT={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function QT(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=XT[e])?!!t[e]:!1}function V_(){return QT}var YT=ln({},Zp,{key:function(e){if(e.key){var t=qT[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=_h(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?KT[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:V_,charCode:function(e){return e.type==="keypress"?_h(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?_h(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),ZT=xi(YT),JT=ln({},tm,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),vv=xi(JT),ek=ln({},Zp,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:V_}),tk=xi(ek),rk=ln({},su,{propertyName:0,elapsedTime:0,pseudoElement:0}),nk=xi(rk),ik=ln({},tm,{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}),ok=xi(ik),sk=[9,13,27,32],W_=Io&&"CompositionEvent"in window,kp=null;Io&&"documentMode"in document&&(kp=document.documentMode);var ak=Io&&"TextEvent"in window&&!kp,_b=Io&&(!W_||kp&&8<kp&&11>=kp),bv=" ",xv=!1;function wb(e,t){switch(e){case"keyup":return sk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function yb(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Dl=!1;function lk(e,t){switch(e){case"compositionend":return yb(t);case"keypress":return t.which!==32?null:(xv=!0,bv);case"textInput":return e=t.data,e===bv&&xv?null:e;default:return null}}function uk(e,t){if(Dl)return e==="compositionend"||!W_&&wb(e,t)?(e=gb(),gh=j_=fs=null,Dl=!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 _b&&t.locale!=="ko"?null:t.data;default:return null}}var ck={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 Mv(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!ck[e.type]:t==="textarea"}function vb(e,t,r,o){Y1(o),t=Fh(t,"onChange"),0<t.length&&(r=new U_("onChange","change",null,r,o),e.push({event:r,listeners:t}))}var Sp=null,Rp=null;function dk(e){Ab(e,0)}function rm(e){var t=Bl(e);if(W1(t))return e}function pk(e,t){if(e==="change")return t}var bb=!1;if(Io){var cg;if(Io){var dg="oninput"in document;if(!dg){var Tv=document.createElement("div");Tv.setAttribute("oninput","return;"),dg=typeof Tv.oninput=="function"}cg=dg}else cg=!1;bb=cg&&(!document.documentMode||9<document.documentMode)}function kv(){Sp&&(Sp.detachEvent("onpropertychange",xb),Rp=Sp=null)}function xb(e){if(e.propertyName==="value"&&rm(Rp)){var t=[];vb(t,Rp,e,D_(e)),tb(dk,t)}}function fk(e,t,r){e==="focusin"?(kv(),Sp=t,Rp=r,Sp.attachEvent("onpropertychange",xb)):e==="focusout"&&kv()}function hk(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return rm(Rp)}function mk(e,t){if(e==="click")return rm(t)}function gk(e,t){if(e==="input"||e==="change")return rm(t)}function _k(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zi=typeof Object.is=="function"?Object.is:_k;function Bp(e,t){if(Zi(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(o=0;o<r.length;o++){var a=r[o];if(!Cg.call(t,a)||!Zi(e[a],t[a]))return!1}return!0}function Sv(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Ev(e,t){var r=Sv(e);e=0;for(var o;r;){if(r.nodeType===3){if(o=e+r.textContent.length,e<=t&&o>=t)return{node:r,offset:t-e};e=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Sv(r)}}function Mb(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Mb(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Tb(){for(var e=window,t=Sh();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=Sh(e.document)}return t}function G_(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 wk(e){var t=Tb(),r=e.focusedElem,o=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&Mb(r.ownerDocument.documentElement,r)){if(o!==null&&G_(r)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=r.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=Ev(r,l);var p=Ev(r,o);a&&p&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==p.node||e.focusOffset!==p.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),l>o?(e.addRange(t),e.extend(p.node,p.offset)):(t.setEnd(p.node,p.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r<t.length;r++)e=t[r],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var yk=Io&&"documentMode"in document&&11>=document.documentMode,Ll=null,qg=null,Ep=null,Kg=!1;function Cv(e,t,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Kg||Ll==null||Ll!==Sh(o)||(o=Ll,"selectionStart"in o&&G_(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}),Ep&&Bp(Ep,o)||(Ep=o,o=Fh(qg,"onSelect"),0<o.length&&(t=new U_("onSelect","select",null,t,r),e.push({event:t,listeners:o}),t.target=Ll)))}function rh(e,t){var r={};return r[e.toLowerCase()]=t.toLowerCase(),r["Webkit"+e]="webkit"+t,r["Moz"+e]="moz"+t,r}var Rl={animationend:rh("Animation","AnimationEnd"),animationiteration:rh("Animation","AnimationIteration"),animationstart:rh("Animation","AnimationStart"),transitionend:rh("Transition","TransitionEnd")},pg={},kb={};Io&&(kb=document.createElement("div").style,"AnimationEvent"in window||(delete Rl.animationend.animation,delete Rl.animationiteration.animation,delete Rl.animationstart.animation),"TransitionEvent"in window||delete Rl.transitionend.transition);function nm(e){if(pg[e])return pg[e];if(!Rl[e])return e;var t=Rl[e],r;for(r in t)if(t.hasOwnProperty(r)&&r in kb)return pg[e]=t[r];return e}var Sb=nm("animationend"),Eb=nm("animationiteration"),Cb=nm("animationstart"),Pb=nm("transitionend"),$b=new Map,Pv="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 ks(e,t){$b.set(e,t),fa(t,[e])}for(var fg=0;fg<Pv.length;fg++){var hg=Pv[fg],vk=hg.toLowerCase(),bk=hg[0].toUpperCase()+hg.slice(1);ks(vk,"on"+bk)}ks(Sb,"onAnimationEnd");ks(Eb,"onAnimationIteration");ks(Cb,"onAnimationStart");ks("dblclick","onDoubleClick");ks("focusin","onFocus");ks("focusout","onBlur");ks(Pb,"onTransitionEnd");Zl("onMouseEnter",["mouseout","mouseover"]);Zl("onMouseLeave",["mouseout","mouseover"]);Zl("onPointerEnter",["pointerout","pointerover"]);Zl("onPointerLeave",["pointerout","pointerover"]);fa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));fa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));fa("onBeforeInput",["compositionend","keypress","textInput","paste"]);fa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));fa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));fa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var bp="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(" "),xk=new Set("cancel close invalid load scroll toggle".split(" ").concat(bp));function $v(e,t,r){var o=e.type||"unknown-event";e.currentTarget=r,vT(o,t,void 0,e),e.currentTarget=null}function Ab(e,t){t=(t&4)!==0;for(var r=0;r<e.length;r++){var o=e[r],a=o.event;o=o.listeners;e:{var l=void 0;if(t)for(var p=o.length-1;0<=p;p--){var _=o[p],h=_.instance,g=_.currentTarget;if(_=_.listener,h!==l&&a.isPropagationStopped())break e;$v(a,_,g),l=h}else for(p=0;p<o.length;p++){if(_=o[p],h=_.instance,g=_.currentTarget,_=_.listener,h!==l&&a.isPropagationStopped())break e;$v(a,_,g),l=h}}}if(Ch)throw e=Vg,Ch=!1,Vg=null,e}function Jr(e,t){var r=t[Jg];r===void 0&&(r=t[Jg]=new Set);var o=e+"__bubble";r.has(o)||(Ib(t,e,2,!1),r.add(o))}function mg(e,t,r){var o=0;t&&(o|=4),Ib(r,e,o,t)}var nh="_reactListening"+Math.random().toString(36).slice(2);function Np(e){if(!e[nh]){e[nh]=!0,B1.forEach(function(r){r!=="selectionchange"&&(xk.has(r)||mg(r,!1,e),mg(r,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[nh]||(t[nh]=!0,mg("selectionchange",!1,t))}}function Ib(e,t,r,o){switch(mb(t)){case 1:var a=DT;break;case 4:a=LT;break;default:a=N_}r=a.bind(null,t,r,e),a=void 0,!Ug||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(a=!0),o?a!==void 0?e.addEventListener(t,r,{capture:!0,passive:a}):e.addEventListener(t,r,!0):a!==void 0?e.addEventListener(t,r,{passive:a}):e.addEventListener(t,r,!1)}function gg(e,t,r,o,a){var l=o;if(!(t&1)&&!(t&2)&&o!==null)e:for(;;){if(o===null)return;var p=o.tag;if(p===3||p===4){var _=o.stateNode.containerInfo;if(_===a||_.nodeType===8&&_.parentNode===a)break;if(p===4)for(p=o.return;p!==null;){var h=p.tag;if((h===3||h===4)&&(h=p.stateNode.containerInfo,h===a||h.nodeType===8&&h.parentNode===a))return;p=p.return}for(;_!==null;){if(p=na(_),p===null)return;if(h=p.tag,h===5||h===6){o=l=p;continue e}_=_.parentNode}}o=o.return}tb(function(){var g=l,M=D_(r),y=[];e:{var E=$b.get(e);if(E!==void 0){var T=U_,O=e;switch(e){case"keypress":if(_h(r)===0)break e;case"keydown":case"keyup":T=ZT;break;case"focusin":O="focus",T=ug;break;case"focusout":O="blur",T=ug;break;case"beforeblur":case"afterblur":T=ug;break;case"click":if(r.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":T=wv;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":T=NT;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":T=tk;break;case Sb:case Eb:case Cb:T=VT;break;case Pb:T=nk;break;case"scroll":T=RT;break;case"wheel":T=ok;break;case"copy":case"cut":case"paste":T=GT;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":T=vv}var S=(t&4)!==0,C=!S&&e==="scroll",w=S?E!==null?E+"Capture":null:E;S=[];for(var b=g,I;b!==null;){I=b;var U=I.stateNode;if(I.tag===5&&U!==null&&(I=U,w!==null&&(U=Op(b,w),U!=null&&S.push(jp(b,U,I)))),C)break;b=b.return}0<S.length&&(E=new T(E,O,null,r,M),y.push({event:E,listeners:S}))}}if(!(t&7)){e:{if(E=e==="mouseover"||e==="pointerover",T=e==="mouseout"||e==="pointerout",E&&r!==Ng&&(O=r.relatedTarget||r.fromElement)&&(na(O)||O[Fo]))break e;if((T||E)&&(E=M.window===M?M:(E=M.ownerDocument)?E.defaultView||E.parentWindow:window,T?(O=r.relatedTarget||r.toElement,T=g,O=O?na(O):null,O!==null&&(C=ha(O),O!==C||O.tag!==5&&O.tag!==6)&&(O=null)):(T=null,O=g),T!==O)){if(S=wv,U="onMouseLeave",w="onMouseEnter",b="mouse",(e==="pointerout"||e==="pointerover")&&(S=vv,U="onPointerLeave",w="onPointerEnter",b="pointer"),C=T==null?E:Bl(T),I=O==null?E:Bl(O),E=new S(U,b+"leave",T,r,M),E.target=C,E.relatedTarget=I,U=null,na(M)===g&&(S=new S(w,b+"enter",O,r,M),S.target=I,S.relatedTarget=C,U=S),C=U,T&&O)t:{for(S=T,w=O,b=0,I=S;I;I=Fl(I))b++;for(I=0,U=w;U;U=Fl(U))I++;for(;0<b-I;)S=Fl(S),b--;for(;0<I-b;)w=Fl(w),I--;for(;b--;){if(S===w||w!==null&&S===w.alternate)break t;S=Fl(S),w=Fl(w)}S=null}else S=null;T!==null&&Av(y,E,T,S,!1),O!==null&&C!==null&&Av(y,C,O,S,!0)}}e:{if(E=g?Bl(g):window,T=E.nodeName&&E.nodeName.toLowerCase(),T==="select"||T==="input"&&E.type==="file")var z=pk;else if(Mv(E))if(bb)z=gk;else{z=hk;var B=fk}else(T=E.nodeName)&&T.toLowerCase()==="input"&&(E.type==="checkbox"||E.type==="radio")&&(z=mk);if(z&&(z=z(e,g))){vb(y,z,r,M);break e}B&&B(e,E,g),e==="focusout"&&(B=E._wrapperState)&&B.controlled&&E.type==="number"&&zg(E,"number",E.value)}switch(B=g?Bl(g):window,e){case"focusin":(Mv(B)||B.contentEditable==="true")&&(Ll=B,qg=g,Ep=null);break;case"focusout":Ep=qg=Ll=null;break;case"mousedown":Kg=!0;break;case"contextmenu":case"mouseup":case"dragend":Kg=!1,Cv(y,r,M);break;case"selectionchange":if(yk)break;case"keydown":case"keyup":Cv(y,r,M)}var j;if(W_)e:{switch(e){case"compositionstart":var N="onCompositionStart";break e;case"compositionend":N="onCompositionEnd";break e;case"compositionupdate":N="onCompositionUpdate";break e}N=void 0}else Dl?wb(e,r)&&(N="onCompositionEnd"):e==="keydown"&&r.keyCode===229&&(N="onCompositionStart");N&&(_b&&r.locale!=="ko"&&(Dl||N!=="onCompositionStart"?N==="onCompositionEnd"&&Dl&&(j=gb()):(fs=M,j_="value"in fs?fs.value:fs.textContent,Dl=!0)),B=Fh(g,N),0<B.length&&(N=new yv(N,e,null,r,M),y.push({event:N,listeners:B}),j?N.data=j:(j=yb(r),j!==null&&(N.data=j)))),(j=ak?lk(e,r):uk(e,r))&&(g=Fh(g,"onBeforeInput"),0<g.length&&(M=new yv("onBeforeInput","beforeinput",null,r,M),y.push({event:M,listeners:g}),M.data=j))}Ab(y,t)})}function jp(e,t,r){return{instance:e,listener:t,currentTarget:r}}function Fh(e,t){for(var r=t+"Capture",o=[];e!==null;){var a=e,l=a.stateNode;a.tag===5&&l!==null&&(a=l,l=Op(e,r),l!=null&&o.unshift(jp(e,l,a)),l=Op(e,t),l!=null&&o.push(jp(e,l,a))),e=e.return}return o}function Fl(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function Av(e,t,r,o,a){for(var l=t._reactName,p=[];r!==null&&r!==o;){var _=r,h=_.alternate,g=_.stateNode;if(h!==null&&h===o)break;_.tag===5&&g!==null&&(_=g,a?(h=Op(r,l),h!=null&&p.unshift(jp(r,h,_))):a||(h=Op(r,l),h!=null&&p.push(jp(r,h,_)))),r=r.return}p.length!==0&&e.push({event:t,listeners:p})}var Mk=/\r\n?/g,Tk=/\u0000|\uFFFD/g;function Iv(e){return(typeof e=="string"?e:""+e).replace(Mk,` `).replace(Tk,"")}function ih(e,t,r){if(t=Iv(t),Iv(e)!==t&&r)throw Error(xt(425))}function Oh(){}var Xg=null,Qg=null;function Yg(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 Zg=typeof setTimeout=="function"?setTimeout:void 0,kk=typeof clearTimeout=="function"?clearTimeout:void 0,Fv=typeof Promise=="function"?Promise:void 0,Sk=typeof queueMicrotask=="function"?queueMicrotask:typeof Fv<"u"?function(e){return Fv.resolve(null).then(e).catch(Ek)}:Zg;function Ek(e){setTimeout(function(){throw e})}function _g(e,t){var r=t,o=0;do{var a=r.nextSibling;if(e.removeChild(r),a&&a.nodeType===8)if(r=a.data,r==="/$"){if(o===0){e.removeChild(a),Lp(t);return}o--}else r!=="$"&&r!=="$?"&&r!=="$!"||o++;r=a}while(r);Lp(t)}function ws(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 Ov(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var au=Math.random().toString(36).slice(2),uo="__reactFiber$"+au,Up="__reactProps$"+au,Fo="__reactContainer$"+au,Jg="__reactEvents$"+au,Ck="__reactListeners$"+au,Pk="__reactHandles$"+au;function na(e){var t=e[uo];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Fo]||r[uo]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=Ov(e);e!==null;){if(r=e[uo])return r;e=Ov(e)}return t}e=r,r=e.parentNode}return null}function Jp(e){return e=e[uo]||e[Fo],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Bl(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(xt(33))}function im(e){return e[Up]||null}var e_=[],Nl=-1;function Ss(e){return{current:e}}function tn(e){0>Nl||(e.current=e_[Nl],e_[Nl]=null,Nl--)}function Qr(e,t){Nl++,e_[Nl]=e.current,e.current=t}var Ts={},qn=Ss(Ts),ui=Ss(!1),la=Ts;function Jl(e,t){var r=e.type.contextTypes;if(!r)return Ts;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},l;for(l in r)a[l]=t[l];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function ci(e){return e=e.childContextTypes,e!=null}function zh(){tn(ui),tn(qn)}function zv(e,t,r){if(qn.current!==Ts)throw Error(xt(168));Qr(qn,t),Qr(ui,r)}function Fb(e,t,r){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return r;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(xt(108,fT(e)||"Unknown",a));return ln({},r,o)}function Dh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ts,la=qn.current,Qr(qn,e),Qr(ui,ui.current),!0}function Dv(e,t,r){var o=e.stateNode;if(!o)throw Error(xt(169));r?(e=Fb(e,t,la),o.__reactInternalMemoizedMergedChildContext=e,tn(ui),tn(qn),Qr(qn,e)):tn(ui),Qr(ui,r)}var Eo=null,om=!1,wg=!1;function Ob(e){Eo===null?Eo=[e]:Eo.push(e)}function $k(e){om=!0,Ob(e)}function Es(){if(!wg&&Eo!==null){wg=!0;var e=0,t=Ur;try{var r=Eo;for(Ur=1;e<r.length;e++){var o=r[e];do o=o(!0);while(o!==null)}Eo=null,om=!1}catch(a){throw Eo!==null&&(Eo=Eo.slice(e+1)),ob(L_,Es),a}finally{Ur=t,wg=!1}}return null}var jl=[],Ul=0,Lh=null,Rh=0,Fi=[],Oi=0,ua=null,Po=1,$o="";function ea(e,t){jl[Ul++]=Rh,jl[Ul++]=Lh,Lh=e,Rh=t}function zb(e,t,r){Fi[Oi++]=Po,Fi[Oi++]=$o,Fi[Oi++]=ua,ua=e;var o=Po;e=$o;var a=32-Qi(o)-1;o&=~(1<<a),r+=1;var l=32-Qi(t)+a;if(30<l){var p=a-a%5;l=(o&(1<<p)-1).toString(32),o>>=p,a-=p,Po=1<<32-Qi(t)+a|r<<a|o,$o=l+e}else Po=1<<l|r<<a|o,$o=e}function H_(e){e.return!==null&&(ea(e,1),zb(e,1,0))}function q_(e){for(;e===Lh;)Lh=jl[--Ul],jl[Ul]=null,Rh=jl[--Ul],jl[Ul]=null;for(;e===ua;)ua=Fi[--Oi],Fi[Oi]=null,$o=Fi[--Oi],Fi[Oi]=null,Po=Fi[--Oi],Fi[Oi]=null}var yi=null,wi=null,nn=!1,Xi=null;function Db(e,t){var r=zi(5,null,null,0);r.elementType="DELETED",r.stateNode=t,r.return=e,t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)}function Lv(e,t){switch(e.tag){case 5:var r=e.type;return t=t.nodeType!==1||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,yi=e,wi=ws(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,yi=e,wi=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(r=ua!==null?{id:Po,overflow:$o}:null,e.memoizedState={dehydrated:t,treeContext:r,retryLane:1073741824},r=zi(18,null,null,0),r.stateNode=t,r.return=e,e.child=r,yi=e,wi=null,!0):!1;default:return!1}}function t_(e){return(e.mode&1)!==0&&(e.flags&128)===0}function r_(e){if(nn){var t=wi;if(t){var r=t;if(!Lv(e,t)){if(t_(e))throw Error(xt(418));t=ws(r.nextSibling);var o=yi;t&&Lv(e,t)?Db(o,r):(e.flags=e.flags&-4097|2,nn=!1,yi=e)}}else{if(t_(e))throw Error(xt(418));e.flags=e.flags&-4097|2,nn=!1,yi=e}}}function Rv(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;yi=e}function oh(e){if(e!==yi)return!1;if(!nn)return Rv(e),nn=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!Yg(e.type,e.memoizedProps)),t&&(t=wi)){if(t_(e))throw Lb(),Error(xt(418));for(;t;)Db(e,t),t=ws(t.nextSibling)}if(Rv(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(xt(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="/$"){if(t===0){wi=ws(e.nextSibling);break e}t--}else r!=="$"&&r!=="$!"&&r!=="$?"||t++}e=e.nextSibling}wi=null}}else wi=yi?ws(e.stateNode.nextSibling):null;return!0}function Lb(){for(var e=wi;e;)e=ws(e.nextSibling)}function eu(){wi=yi=null,nn=!1}function K_(e){Xi===null?Xi=[e]:Xi.push(e)}var Ak=Do.ReactCurrentBatchConfig;function mp(e,t,r){if(e=r.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(r._owner){if(r=r._owner,r){if(r.tag!==1)throw Error(xt(309));var o=r.stateNode}if(!o)throw Error(xt(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(p){var _=a.refs;p===null?delete _[l]:_[l]=p},t._stringRef=l,t)}if(typeof e!="string")throw Error(xt(284));if(!r._owner)throw Error(xt(290,e))}return e}function sh(e,t){throw e=Object.prototype.toString.call(t),Error(xt(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Bv(e){var t=e._init;return t(e._payload)}function Rb(e){function t(w,b){if(e){var I=w.deletions;I===null?(w.deletions=[b],w.flags|=16):I.push(b)}}function r(w,b){if(!e)return null;for(;b!==null;)t(w,b),b=b.sibling;return null}function o(w,b){for(w=new Map;b!==null;)b.key!==null?w.set(b.key,b):w.set(b.index,b),b=b.sibling;return w}function a(w,b){return w=xs(w,b),w.index=0,w.sibling=null,w}function l(w,b,I){return w.index=I,e?(I=w.alternate,I!==null?(I=I.index,I<b?(w.flags|=2,b):I):(w.flags|=2,b)):(w.flags|=1048576,b)}function p(w){return e&&w.alternate===null&&(w.flags|=2),w}function _(w,b,I,U){return b===null||b.tag!==6?(b=kg(I,w.mode,U),b.return=w,b):(b=a(b,I),b.return=w,b)}function h(w,b,I,U){var z=I.type;return z===zl?M(w,b,I.props.children,U,I.key):b!==null&&(b.elementType===z||typeof z=="object"&&z!==null&&z.$$typeof===us&&Bv(z)===b.type)?(U=a(b,I.props),U.ref=mp(w,b,I),U.return=w,U):(U=Th(I.type,I.key,I.props,null,w.mode,U),U.ref=mp(w,b,I),U.return=w,U)}function g(w,b,I,U){return b===null||b.tag!==4||b.stateNode.containerInfo!==I.containerInfo||b.stateNode.implementation!==I.implementation?(b=Sg(I,w.mode,U),b.return=w,b):(b=a(b,I.children||[]),b.return=w,b)}function M(w,b,I,U,z){return b===null||b.tag!==7?(b=aa(I,w.mode,U,z),b.return=w,b):(b=a(b,I),b.return=w,b)}function y(w,b,I){if(typeof b=="string"&&b!==""||typeof b=="number")return b=kg(""+b,w.mode,I),b.return=w,b;if(typeof b=="object"&&b!==null){switch(b.$$typeof){case Xf:return I=Th(b.type,b.key,b.props,null,w.mode,I),I.ref=mp(w,null,b),I.return=w,I;case Ol:return b=Sg(b,w.mode,I),b.return=w,b;case us:var U=b._init;return y(w,U(b._payload),I)}if(yp(b)||cp(b))return b=aa(b,w.mode,I,null),b.return=w,b;sh(w,b)}return null}function E(w,b,I,U){var z=b!==null?b.key:null;if(typeof I=="string"&&I!==""||typeof I=="number")return z!==null?null:_(w,b,""+I,U);if(typeof I=="object"&&I!==null){switch(I.$$typeof){case Xf:return I.key===z?h(w,b,I,U):null;case Ol:return I.key===z?g(w,b,I,U):null;case us:return z=I._init,E(w,b,z(I._payload),U)}if(yp(I)||cp(I))return z!==null?null:M(w,b,I,U,null);sh(w,I)}return null}function T(w,b,I,U,z){if(typeof U=="string"&&U!==""||typeof U=="number")return w=w.get(I)||null,_(b,w,""+U,z);if(typeof U=="object"&&U!==null){switch(U.$$typeof){case Xf:return w=w.get(U.key===null?I:U.key)||null,h(b,w,U,z);case Ol:return w=w.get(U.key===null?I:U.key)||null,g(b,w,U,z);case us:var B=U._init;return T(w,b,I,B(U._payload),z)}if(yp(U)||cp(U))return w=w.get(I)||null,M(b,w,U,z,null);sh(b,U)}return null}function O(w,b,I,U){for(var z=null,B=null,j=b,N=b=0,ae=null;j!==null&&N<I.length;N++){j.index>N?(ae=j,j=null):ae=j.sibling;var ce=E(w,j,I[N],U);if(ce===null){j===null&&(j=ae);break}e&&j&&ce.alternate===null&&t(w,j),b=l(ce,b,N),B===null?z=ce:B.sibling=ce,B=ce,j=ae}if(N===I.length)return r(w,j),nn&&ea(w,N),z;if(j===null){for(;N<I.length;N++)j=y(w,I[N],U),j!==null&&(b=l(j,b,N),B===null?z=j:B.sibling=j,B=j);return nn&&ea(w,N),z}for(j=o(w,j);N<I.length;N++)ae=T(j,w,N,I[N],U),ae!==null&&(e&&ae.alternate!==null&&j.delete(ae.key===null?N:ae.key),b=l(ae,b,N),B===null?z=ae:B.sibling=ae,B=ae);return e&&j.forEach(function(xe){return t(w,xe)}),nn&&ea(w,N),z}function S(w,b,I,U){var z=cp(I);if(typeof z!="function")throw Error(xt(150));if(I=z.call(I),I==null)throw Error(xt(151));for(var B=z=null,j=b,N=b=0,ae=null,ce=I.next();j!==null&&!ce.done;N++,ce=I.next()){j.index>N?(ae=j,j=null):ae=j.sibling;var xe=E(w,j,ce.value,U);if(xe===null){j===null&&(j=ae);break}e&&j&&xe.alternate===null&&t(w,j),b=l(xe,b,N),B===null?z=xe:B.sibling=xe,B=xe,j=ae}if(ce.done)return r(w,j),nn&&ea(w,N),z;if(j===null){for(;!ce.done;N++,ce=I.next())ce=y(w,ce.value,U),ce!==null&&(b=l(ce,b,N),B===null?z=ce:B.sibling=ce,B=ce);return nn&&ea(w,N),z}for(j=o(w,j);!ce.done;N++,ce=I.next())ce=T(j,w,N,ce.value,U),ce!==null&&(e&&ce.alternate!==null&&j.delete(ce.key===null?N:ce.key),b=l(ce,b,N),B===null?z=ce:B.sibling=ce,B=ce);return e&&j.forEach(function(Y){return t(w,Y)}),nn&&ea(w,N),z}function C(w,b,I,U){if(typeof I=="object"&&I!==null&&I.type===zl&&I.key===null&&(I=I.props.children),typeof I=="object"&&I!==null){switch(I.$$typeof){case Xf:e:{for(var z=I.key,B=b;B!==null;){if(B.key===z){if(z=I.type,z===zl){if(B.tag===7){r(w,B.sibling),b=a(B,I.props.children),b.return=w,w=b;break e}}else if(B.elementType===z||typeof z=="object"&&z!==null&&z.$$typeof===us&&Bv(z)===B.type){r(w,B.sibling),b=a(B,I.props),b.ref=mp(w,B,I),b.return=w,w=b;break e}r(w,B);break}else t(w,B);B=B.sibling}I.type===zl?(b=aa(I.props.children,w.mode,U,I.key),b.return=w,w=b):(U=Th(I.type,I.key,I.props,null,w.mode,U),U.ref=mp(w,b,I),U.return=w,w=U)}return p(w);case Ol:e:{for(B=I.key;b!==null;){if(b.key===B)if(b.tag===4&&b.stateNode.containerInfo===I.containerInfo&&b.stateNode.implementation===I.implementation){r(w,b.sibling),b=a(b,I.children||[]),b.return=w,w=b;break e}else{r(w,b);break}else t(w,b);b=b.sibling}b=Sg(I,w.mode,U),b.return=w,w=b}return p(w);case us:return B=I._init,C(w,b,B(I._payload),U)}if(yp(I))return O(w,b,I,U);if(cp(I))return S(w,b,I,U);sh(w,I)}return typeof I=="string"&&I!==""||typeof I=="number"?(I=""+I,b!==null&&b.tag===6?(r(w,b.sibling),b=a(b,I),b.return=w,w=b):(r(w,b),b=kg(I,w.mode,U),b.return=w,w=b),p(w)):r(w,b)}return C}var tu=Rb(!0),Bb=Rb(!1),Bh=Ss(null),Nh=null,Vl=null,X_=null;function Q_(){X_=Vl=Nh=null}function Y_(e){var t=Bh.current;tn(Bh),e._currentValue=t}function n_(e,t,r){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===r)break;e=e.return}}function Ql(e,t){Nh=e,X_=Vl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(li=!0),e.firstContext=null)}function Li(e){var t=e._currentValue;if(X_!==e)if(e={context:e,memoizedValue:t,next:null},Vl===null){if(Nh===null)throw Error(xt(308));Vl=e,Nh.dependencies={lanes:0,firstContext:e}}else Vl=Vl.next=e;return t}var ia=null;function Z_(e){ia===null?ia=[e]:ia.push(e)}function Nb(e,t,r,o){var a=t.interleaved;return a===null?(r.next=r,Z_(t)):(r.next=a.next,a.next=r),t.interleaved=r,Oo(e,o)}function Oo(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var cs=!1;function J_(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function jb(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 Ao(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ys(e,t,r){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,zr&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Oo(e,r)}return a=o.interleaved,a===null?(t.next=t,Z_(o)):(t.next=a.next,a.next=t),o.interleaved=t,Oo(e,r)}function wh(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,r|=o,t.lanes=r,R_(e,r)}}function Nv(e,t){var r=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var a=null,l=null;if(r=r.firstBaseUpdate,r!==null){do{var p={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};l===null?a=l=p:l=l.next=p,r=r.next}while(r!==null);l===null?a=l=t:l=l.next=t}else a=l=t;r={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:l,shared:o.shared,effects:o.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function jh(e,t,r,o){var a=e.updateQueue;cs=!1;var l=a.firstBaseUpdate,p=a.lastBaseUpdate,_=a.shared.pending;if(_!==null){a.shared.pending=null;var h=_,g=h.next;h.next=null,p===null?l=g:p.next=g,p=h;var M=e.alternate;M!==null&&(M=M.updateQueue,_=M.lastBaseUpdate,_!==p&&(_===null?M.firstBaseUpdate=g:_.next=g,M.lastBaseUpdate=h))}if(l!==null){var y=a.baseState;p=0,M=g=h=null,_=l;do{var E=_.lane,T=_.eventTime;if((o&E)===E){M!==null&&(M=M.next={eventTime:T,lane:0,tag:_.tag,payload:_.payload,callback:_.callback,next:null});e:{var O=e,S=_;switch(E=t,T=r,S.tag){case 1:if(O=S.payload,typeof O=="function"){y=O.call(T,y,E);break e}y=O;break e;case 3:O.flags=O.flags&-65537|128;case 0:if(O=S.payload,E=typeof O=="function"?O.call(T,y,E):O,E==null)break e;y=ln({},y,E);break e;case 2:cs=!0}}_.callback!==null&&_.lane!==0&&(e.flags|=64,E=a.effects,E===null?a.effects=[_]:E.push(_))}else T={eventTime:T,lane:E,tag:_.tag,payload:_.payload,callback:_.callback,next:null},M===null?(g=M=T,h=y):M=M.next=T,p|=E;if(_=_.next,_===null){if(_=a.shared.pending,_===null)break;E=_,_=E.next,E.next=null,a.lastBaseUpdate=E,a.shared.pending=null}}while(!0);if(M===null&&(h=y),a.baseState=h,a.firstBaseUpdate=g,a.lastBaseUpdate=M,t=a.shared.interleaved,t!==null){a=t;do p|=a.lane,a=a.next;while(a!==t)}else l===null&&(a.shared.lanes=0);da|=p,e.lanes=p,e.memoizedState=y}}function jv(e,t,r){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=r,typeof a!="function")throw Error(xt(191,a));a.call(o)}}}var ef={},po=Ss(ef),Vp=Ss(ef),Wp=Ss(ef);function oa(e){if(e===ef)throw Error(xt(174));return e}function e0(e,t){switch(Qr(Wp,t),Qr(Vp,e),Qr(po,ef),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Lg(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Lg(t,e)}tn(po),Qr(po,t)}function ru(){tn(po),tn(Vp),tn(Wp)}function Ub(e){oa(Wp.current);var t=oa(po.current),r=Lg(t,e.type);t!==r&&(Qr(Vp,e),Qr(po,r))}function t0(e){Vp.current===e&&(tn(po),tn(Vp))}var sn=Ss(0);function Uh(e){for(var t=e;t!==null;){if(t.tag===13){var r=t.memoizedState;if(r!==null&&(r=r.dehydrated,r===null||r.data==="$?"||r.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 yg=[];function r0(){for(var e=0;e<yg.length;e++)yg[e]._workInProgressVersionPrimary=null;yg.length=0}var yh=Do.ReactCurrentDispatcher,vg=Do.ReactCurrentBatchConfig,ca=0,an=null,Sn=null,In=null,Vh=!1,Cp=!1,Gp=0,Ik=0;function Wn(){throw Error(xt(321))}function n0(e,t){if(t===null)return!1;for(var r=0;r<t.length&&r<e.length;r++)if(!Zi(e[r],t[r]))return!1;return!0}function i0(e,t,r,o,a,l){if(ca=l,an=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,yh.current=e===null||e.memoizedState===null?Dk:Lk,e=r(o,a),Cp){l=0;do{if(Cp=!1,Gp=0,25<=l)throw Error(xt(301));l+=1,In=Sn=null,t.updateQueue=null,yh.current=Rk,e=r(o,a)}while(Cp)}if(yh.current=Wh,t=Sn!==null&&Sn.next!==null,ca=0,In=Sn=an=null,Vh=!1,t)throw Error(xt(300));return e}function o0(){var e=Gp!==0;return Gp=0,e}function lo(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return In===null?an.memoizedState=In=e:In=In.next=e,In}function Ri(){if(Sn===null){var e=an.alternate;e=e!==null?e.memoizedState:null}else e=Sn.next;var t=In===null?an.memoizedState:In.next;if(t!==null)In=t,Sn=e;else{if(e===null)throw Error(xt(310));Sn=e,e={memoizedState:Sn.memoizedState,baseState:Sn.baseState,baseQueue:Sn.baseQueue,queue:Sn.queue,next:null},In===null?an.memoizedState=In=e:In=In.next=e}return In}function Hp(e,t){return typeof t=="function"?t(e):t}function bg(e){var t=Ri(),r=t.queue;if(r===null)throw Error(xt(311));r.lastRenderedReducer=e;var o=Sn,a=o.baseQueue,l=r.pending;if(l!==null){if(a!==null){var p=a.next;a.next=l.next,l.next=p}o.baseQueue=a=l,r.pending=null}if(a!==null){l=a.next,o=o.baseState;var _=p=null,h=null,g=l;do{var M=g.lane;if((ca&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 y={lane:M,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null};h===null?(_=h=y,p=o):h=h.next=y,an.lanes|=M,da|=M}g=g.next}while(g!==null&&g!==l);h===null?p=o:h.next=_,Zi(o,t.memoizedState)||(li=!0),t.memoizedState=o,t.baseState=p,t.baseQueue=h,r.lastRenderedState=o}if(e=r.interleaved,e!==null){a=e;do l=a.lane,an.lanes|=l,da|=l,a=a.next;while(a!==e)}else a===null&&(r.lanes=0);return[t.memoizedState,r.dispatch]}function xg(e){var t=Ri(),r=t.queue;if(r===null)throw Error(xt(311));r.lastRenderedReducer=e;var o=r.dispatch,a=r.pending,l=t.memoizedState;if(a!==null){r.pending=null;var p=a=a.next;do l=e(l,p.action),p=p.next;while(p!==a);Zi(l,t.memoizedState)||(li=!0),t.memoizedState=l,t.baseQueue===null&&(t.baseState=l),r.lastRenderedState=l}return[l,o]}function Vb(){}function Wb(e,t){var r=an,o=Ri(),a=t(),l=!Zi(o.memoizedState,a);if(l&&(o.memoizedState=a,li=!0),o=o.queue,s0(qb.bind(null,r,o,e),[e]),o.getSnapshot!==t||l||In!==null&&In.memoizedState.tag&1){if(r.flags|=2048,qp(9,Hb.bind(null,r,o,a,t),void 0,null),Fn===null)throw Error(xt(349));ca&30||Gb(r,t,a)}return a}function Gb(e,t,r){e.flags|=16384,e={getSnapshot:t,value:r},t=an.updateQueue,t===null?(t={lastEffect:null,stores:null},an.updateQueue=t,t.stores=[e]):(r=t.stores,r===null?t.stores=[e]:r.push(e))}function Hb(e,t,r,o){t.value=r,t.getSnapshot=o,Kb(t)&&Xb(e)}function qb(e,t,r){return r(function(){Kb(t)&&Xb(e)})}function Kb(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!Zi(e,r)}catch{return!0}}function Xb(e){var t=Oo(e,1);t!==null&&Yi(t,e,1,-1)}function Uv(e){var t=lo();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Hp,lastRenderedState:e},t.queue=e,e=e.dispatch=zk.bind(null,an,e),[t.memoizedState,e]}function qp(e,t,r,o){return e={tag:e,create:t,destroy:r,deps:o,next:null},t=an.updateQueue,t===null?(t={lastEffect:null,stores:null},an.updateQueue=t,t.lastEffect=e.next=e):(r=t.lastEffect,r===null?t.lastEffect=e.next=e:(o=r.next,r.next=e,e.next=o,t.lastEffect=e)),e}function Qb(){return Ri().memoizedState}function vh(e,t,r,o){var a=lo();an.flags|=e,a.memoizedState=qp(1|t,r,void 0,o===void 0?null:o)}function sm(e,t,r,o){var a=Ri();o=o===void 0?null:o;var l=void 0;if(Sn!==null){var p=Sn.memoizedState;if(l=p.destroy,o!==null&&n0(o,p.deps)){a.memoizedState=qp(t,r,l,o);return}}an.flags|=e,a.memoizedState=qp(1|t,r,l,o)}function Vv(e,t){return vh(8390656,8,e,t)}function s0(e,t){return sm(2048,8,e,t)}function Yb(e,t){return sm(4,2,e,t)}function Zb(e,t){return sm(4,4,e,t)}function Jb(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 e2(e,t,r){return r=r!=null?r.concat([e]):null,sm(4,4,Jb.bind(null,t,e),r)}function a0(){}function t2(e,t){var r=Ri();t=t===void 0?null:t;var o=r.memoizedState;return o!==null&&t!==null&&n0(t,o[1])?o[0]:(r.memoizedState=[e,t],e)}function r2(e,t){var r=Ri();t=t===void 0?null:t;var o=r.memoizedState;return o!==null&&t!==null&&n0(t,o[1])?o[0]:(e=e(),r.memoizedState=[e,t],e)}function n2(e,t,r){return ca&21?(Zi(r,t)||(r=lb(),an.lanes|=r,da|=r,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,li=!0),e.memoizedState=r)}function Fk(e,t){var r=Ur;Ur=r!==0&&4>r?r:4,e(!0);var o=vg.transition;vg.transition={};try{e(!1),t()}finally{Ur=r,vg.transition=o}}function i2(){return Ri().memoizedState}function Ok(e,t,r){var o=bs(e);if(r={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null},o2(e))s2(t,r);else if(r=Nb(e,t,r,o),r!==null){var a=ti();Yi(r,e,o,a),a2(r,t,o)}}function zk(e,t,r){var o=bs(e),a={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null};if(o2(e))s2(t,a);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var p=t.lastRenderedState,_=l(p,r);if(a.hasEagerState=!0,a.eagerState=_,Zi(_,p)){var h=t.interleaved;h===null?(a.next=a,Z_(t)):(a.next=h.next,h.next=a),t.interleaved=a;return}}catch{}finally{}r=Nb(e,t,a,o),r!==null&&(a=ti(),Yi(r,e,o,a),a2(r,t,o))}}function o2(e){var t=e.alternate;return e===an||t!==null&&t===an}function s2(e,t){Cp=Vh=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function a2(e,t,r){if(r&4194240){var o=t.lanes;o&=e.pendingLanes,r|=o,t.lanes=r,R_(e,r)}}var Wh={readContext:Li,useCallback:Wn,useContext:Wn,useEffect:Wn,useImperativeHandle:Wn,useInsertionEffect:Wn,useLayoutEffect:Wn,useMemo:Wn,useReducer:Wn,useRef:Wn,useState:Wn,useDebugValue:Wn,useDeferredValue:Wn,useTransition:Wn,useMutableSource:Wn,useSyncExternalStore:Wn,useId:Wn,unstable_isNewReconciler:!1},Dk={readContext:Li,useCallback:function(e,t){return lo().memoizedState=[e,t===void 0?null:t],e},useContext:Li,useEffect:Vv,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,vh(4194308,4,Jb.bind(null,t,e),r)},useLayoutEffect:function(e,t){return vh(4194308,4,e,t)},useInsertionEffect:function(e,t){return vh(4,2,e,t)},useMemo:function(e,t){var r=lo();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var o=lo();return t=r!==void 0?r(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=Ok.bind(null,an,e),[o.memoizedState,e]},useRef:function(e){var t=lo();return e={current:e},t.memoizedState=e},useState:Uv,useDebugValue:a0,useDeferredValue:function(e){return lo().memoizedState=e},useTransition:function(){var e=Uv(!1),t=e[0];return e=Fk.bind(null,e[1]),lo().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var o=an,a=lo();if(nn){if(r===void 0)throw Error(xt(407));r=r()}else{if(r=t(),Fn===null)throw Error(xt(349));ca&30||Gb(o,t,r)}a.memoizedState=r;var l={value:r,getSnapshot:t};return a.queue=l,Vv(qb.bind(null,o,l,e),[e]),o.flags|=2048,qp(9,Hb.bind(null,o,l,r,t),void 0,null),r},useId:function(){var e=lo(),t=Fn.identifierPrefix;if(nn){var r=$o,o=Po;r=(o&~(1<<32-Qi(o)-1)).toString(32)+r,t=":"+t+"R"+r,r=Gp++,0<r&&(t+="H"+r.toString(32)),t+=":"}else r=Ik++,t=":"+t+"r"+r.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},Lk={readContext:Li,useCallback:t2,useContext:Li,useEffect:s0,useImperativeHandle:e2,useInsertionEffect:Yb,useLayoutEffect:Zb,useMemo:r2,useReducer:bg,useRef:Qb,useState:function(){return bg(Hp)},useDebugValue:a0,useDeferredValue:function(e){var t=Ri();return n2(t,Sn.memoizedState,e)},useTransition:function(){var e=bg(Hp)[0],t=Ri().memoizedState;return[e,t]},useMutableSource:Vb,useSyncExternalStore:Wb,useId:i2,unstable_isNewReconciler:!1},Rk={readContext:Li,useCallback:t2,useContext:Li,useEffect:s0,useImperativeHandle:e2,useInsertionEffect:Yb,useLayoutEffect:Zb,useMemo:r2,useReducer:xg,useRef:Qb,useState:function(){return xg(Hp)},useDebugValue:a0,useDeferredValue:function(e){var t=Ri();return Sn===null?t.memoizedState=e:n2(t,Sn.memoizedState,e)},useTransition:function(){var e=xg(Hp)[0],t=Ri().memoizedState;return[e,t]},useMutableSource:Vb,useSyncExternalStore:Wb,useId:i2,unstable_isNewReconciler:!1};function qi(e,t){if(e&&e.defaultProps){t=ln({},t),e=e.defaultProps;for(var r in e)t[r]===void 0&&(t[r]=e[r]);return t}return t}function i_(e,t,r,o){t=e.memoizedState,r=r(o,t),r=r==null?t:ln({},t,r),e.memoizedState=r,e.lanes===0&&(e.updateQueue.baseState=r)}var am={isMounted:function(e){return(e=e._reactInternals)?ha(e)===e:!1},enqueueSetState:function(e,t,r){e=e._reactInternals;var o=ti(),a=bs(e),l=Ao(o,a);l.payload=t,r!=null&&(l.callback=r),t=ys(e,l,a),t!==null&&(Yi(t,e,a,o),wh(t,e,a))},enqueueReplaceState:function(e,t,r){e=e._reactInternals;var o=ti(),a=bs(e),l=Ao(o,a);l.tag=1,l.payload=t,r!=null&&(l.callback=r),t=ys(e,l,a),t!==null&&(Yi(t,e,a,o),wh(t,e,a))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var r=ti(),o=bs(e),a=Ao(r,o);a.tag=2,t!=null&&(a.callback=t),t=ys(e,a,o),t!==null&&(Yi(t,e,o,r),wh(t,e,o))}};function Wv(e,t,r,o,a,l,p){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,l,p):t.prototype&&t.prototype.isPureReactComponent?!Bp(r,o)||!Bp(a,l):!0}function l2(e,t,r){var o=!1,a=Ts,l=t.contextType;return typeof l=="object"&&l!==null?l=Li(l):(a=ci(t)?la:qn.current,o=t.contextTypes,l=(o=o!=null)?Jl(e,a):Ts),t=new t(r,l),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=am,e.stateNode=t,t._reactInternals=e,o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=a,e.__reactInternalMemoizedMaskedChildContext=l),t}function Gv(e,t,r,o){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(r,o),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(r,o),t.state!==e&&am.enqueueReplaceState(t,t.state,null)}function o_(e,t,r,o){var a=e.stateNode;a.props=r,a.state=e.memoizedState,a.refs={},J_(e);var l=t.contextType;typeof l=="object"&&l!==null?a.context=Li(l):(l=ci(t)?la:qn.current,a.context=Jl(e,l)),a.state=e.memoizedState,l=t.getDerivedStateFromProps,typeof l=="function"&&(i_(e,t,l,r),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&&am.enqueueReplaceState(a,a.state,null),jh(e,r,a,o),a.state=e.memoizedState),typeof a.componentDidMount=="function"&&(e.flags|=4194308)}function nu(e,t){try{var r="",o=t;do r+=pT(o),o=o.return;while(o);var a=r}catch(l){a=` Error generating stack: `+l.message+` `+l.stack}return{value:e,source:t,stack:a,digest:null}}function Mg(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function s_(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var Bk=typeof WeakMap=="function"?WeakMap:Map;function u2(e,t,r){r=Ao(-1,r),r.tag=3,r.payload={element:null};var o=t.value;return r.callback=function(){Hh||(Hh=!0,g_=o),s_(e,t)},r}function c2(e,t,r){r=Ao(-1,r),r.tag=3;var o=e.type.getDerivedStateFromError;if(typeof o=="function"){var a=t.value;r.payload=function(){return o(a)},r.callback=function(){s_(e,t)}}var l=e.stateNode;return l!==null&&typeof l.componentDidCatch=="function"&&(r.callback=function(){s_(e,t),typeof o!="function"&&(vs===null?vs=new Set([this]):vs.add(this));var p=t.stack;this.componentDidCatch(t.value,{componentStack:p!==null?p:""})}),r}function Hv(e,t,r){var o=e.pingCache;if(o===null){o=e.pingCache=new Bk;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(r)||(a.add(r),e=Jk.bind(null,e,t,r),t.then(e,e))}function qv(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 Kv(e,t,r,o,a){return e.mode&1?(e.flags|=65536,e.lanes=a,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Ao(-1,1),t.tag=2,ys(r,t,1))),r.lanes|=1),e)}var Nk=Do.ReactCurrentOwner,li=!1;function ei(e,t,r,o){t.child=e===null?Bb(t,null,r,o):tu(t,e.child,r,o)}function Xv(e,t,r,o,a){r=r.render;var l=t.ref;return Ql(t,a),o=i0(e,t,r,o,l,a),r=o0(),e!==null&&!li?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,zo(e,t,a)):(nn&&r&&H_(t),t.flags|=1,ei(e,t,o,a),t.child)}function Qv(e,t,r,o,a){if(e===null){var l=r.type;return typeof l=="function"&&!m0(l)&&l.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=l,d2(e,t,l,o,a)):(e=Th(r.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 p=l.memoizedProps;if(r=r.compare,r=r!==null?r:Bp,r(p,o)&&e.ref===t.ref)return zo(e,t,a)}return t.flags|=1,e=xs(l,o),e.ref=t.ref,e.return=t,t.child=e}function d2(e,t,r,o,a){if(e!==null){var l=e.memoizedProps;if(Bp(l,o)&&e.ref===t.ref)if(li=!1,t.pendingProps=o=l,(e.lanes&a)!==0)e.flags&131072&&(li=!0);else return t.lanes=e.lanes,zo(e,t,a)}return a_(e,t,r,o,a)}function p2(e,t,r){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},Qr(Gl,_i),_i|=r;else{if(!(r&1073741824))return e=l!==null?l.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Qr(Gl,_i),_i|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},o=l!==null?l.baseLanes:r,Qr(Gl,_i),_i|=o}else l!==null?(o=l.baseLanes|r,t.memoizedState=null):o=r,Qr(Gl,_i),_i|=o;return ei(e,t,a,r),t.child}function f2(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function a_(e,t,r,o,a){var l=ci(r)?la:qn.current;return l=Jl(t,l),Ql(t,a),r=i0(e,t,r,o,l,a),o=o0(),e!==null&&!li?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,zo(e,t,a)):(nn&&o&&H_(t),t.flags|=1,ei(e,t,r,a),t.child)}function Yv(e,t,r,o,a){if(ci(r)){var l=!0;Dh(t)}else l=!1;if(Ql(t,a),t.stateNode===null)bh(e,t),l2(t,r,o),o_(t,r,o,a),o=!0;else if(e===null){var p=t.stateNode,_=t.memoizedProps;p.props=_;var h=p.context,g=r.contextType;typeof g=="object"&&g!==null?g=Li(g):(g=ci(r)?la:qn.current,g=Jl(t,g));var M=r.getDerivedStateFromProps,y=typeof M=="function"||typeof p.getSnapshotBeforeUpdate=="function";y||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(_!==o||h!==g)&&Gv(t,p,o,g),cs=!1;var E=t.memoizedState;p.state=E,jh(t,o,p,a),h=t.memoizedState,_!==o||E!==h||ui.current||cs?(typeof M=="function"&&(i_(t,r,M,o),h=t.memoizedState),(_=cs||Wv(t,r,_,o,E,h,g))?(y||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount()),typeof p.componentDidMount=="function"&&(t.flags|=4194308)):(typeof p.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=h),p.props=o,p.state=h,p.context=g,o=_):(typeof p.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{p=t.stateNode,jb(e,t),_=t.memoizedProps,g=t.type===t.elementType?_:qi(t.type,_),p.props=g,y=t.pendingProps,E=p.context,h=r.contextType,typeof h=="object"&&h!==null?h=Li(h):(h=ci(r)?la:qn.current,h=Jl(t,h));var T=r.getDerivedStateFromProps;(M=typeof T=="function"||typeof p.getSnapshotBeforeUpdate=="function")||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(_!==y||E!==h)&&Gv(t,p,o,h),cs=!1,E=t.memoizedState,p.state=E,jh(t,o,p,a);var O=t.memoizedState;_!==y||E!==O||ui.current||cs?(typeof T=="function"&&(i_(t,r,T,o),O=t.memoizedState),(g=cs||Wv(t,r,g,o,E,O,h)||!1)?(M||typeof p.UNSAFE_componentWillUpdate!="function"&&typeof p.componentWillUpdate!="function"||(typeof p.componentWillUpdate=="function"&&p.componentWillUpdate(o,O,h),typeof p.UNSAFE_componentWillUpdate=="function"&&p.UNSAFE_componentWillUpdate(o,O,h)),typeof p.componentDidUpdate=="function"&&(t.flags|=4),typeof p.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof p.componentDidUpdate!="function"||_===e.memoizedProps&&E===e.memoizedState||(t.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||_===e.memoizedProps&&E===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=O),p.props=o,p.state=O,p.context=h,o=g):(typeof p.componentDidUpdate!="function"||_===e.memoizedProps&&E===e.memoizedState||(t.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||_===e.memoizedProps&&E===e.memoizedState||(t.flags|=1024),o=!1)}return l_(e,t,r,o,l,a)}function l_(e,t,r,o,a,l){f2(e,t);var p=(t.flags&128)!==0;if(!o&&!p)return a&&Dv(t,r,!1),zo(e,t,l);o=t.stateNode,Nk.current=t;var _=p&&typeof r.getDerivedStateFromError!="function"?null:o.render();return t.flags|=1,e!==null&&p?(t.child=tu(t,e.child,null,l),t.child=tu(t,null,_,l)):ei(e,t,_,l),t.memoizedState=o.state,a&&Dv(t,r,!0),t.child}function h2(e){var t=e.stateNode;t.pendingContext?zv(e,t.pendingContext,t.pendingContext!==t.context):t.context&&zv(e,t.context,!1),e0(e,t.containerInfo)}function Zv(e,t,r,o,a){return eu(),K_(a),t.flags|=256,ei(e,t,r,o),t.child}var u_={dehydrated:null,treeContext:null,retryLane:0};function c_(e){return{baseLanes:e,cachePool:null,transitions:null}}function m2(e,t,r){var o=t.pendingProps,a=sn.current,l=!1,p=(t.flags&128)!==0,_;if((_=p)||(_=e!==null&&e.memoizedState===null?!1:(a&2)!==0),_?(l=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(a|=1),Qr(sn,a&1),e===null)return r_(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):(p=o.children,e=o.fallback,l?(o=t.mode,l=t.child,p={mode:"hidden",children:p},!(o&1)&&l!==null?(l.childLanes=0,l.pendingProps=p):l=cm(p,o,0,null),e=aa(e,o,r,null),l.return=t,e.return=t,l.sibling=e,t.child=l,t.child.memoizedState=c_(r),t.memoizedState=u_,e):l0(t,p));if(a=e.memoizedState,a!==null&&(_=a.dehydrated,_!==null))return jk(e,t,p,o,_,a,r);if(l){l=o.fallback,p=t.mode,a=e.child,_=a.sibling;var h={mode:"hidden",children:o.children};return!(p&1)&&t.child!==a?(o=t.child,o.childLanes=0,o.pendingProps=h,t.deletions=null):(o=xs(a,h),o.subtreeFlags=a.subtreeFlags&14680064),_!==null?l=xs(_,l):(l=aa(l,p,r,null),l.flags|=2),l.return=t,o.return=t,o.sibling=l,t.child=o,o=l,l=t.child,p=e.child.memoizedState,p=p===null?c_(r):{baseLanes:p.baseLanes|r,cachePool:null,transitions:p.transitions},l.memoizedState=p,l.childLanes=e.childLanes&~r,t.memoizedState=u_,o}return l=e.child,e=l.sibling,o=xs(l,{mode:"visible",children:o.children}),!(t.mode&1)&&(o.lanes=r),o.return=t,o.sibling=null,e!==null&&(r=t.deletions,r===null?(t.deletions=[e],t.flags|=16):r.push(e)),t.child=o,t.memoizedState=null,o}function l0(e,t){return t=cm({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function ah(e,t,r,o){return o!==null&&K_(o),tu(t,e.child,null,r),e=l0(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function jk(e,t,r,o,a,l,p){if(r)return t.flags&256?(t.flags&=-257,o=Mg(Error(xt(422))),ah(e,t,p,o)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(l=o.fallback,a=t.mode,o=cm({mode:"visible",children:o.children},a,0,null),l=aa(l,a,p,null),l.flags|=2,o.return=t,l.return=t,o.sibling=l,t.child=o,t.mode&1&&tu(t,e.child,null,p),t.child.memoizedState=c_(p),t.memoizedState=u_,l);if(!(t.mode&1))return ah(e,t,p,null);if(a.data==="$!"){if(o=a.nextSibling&&a.nextSibling.dataset,o)var _=o.dgst;return o=_,l=Error(xt(419)),o=Mg(l,o,void 0),ah(e,t,p,o)}if(_=(p&e.childLanes)!==0,li||_){if(o=Fn,o!==null){switch(p&-p){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|p)?0:a,a!==0&&a!==l.retryLane&&(l.retryLane=a,Oo(e,a),Yi(o,e,a,-1))}return h0(),o=Mg(Error(xt(421))),ah(e,t,p,o)}return a.data==="$?"?(t.flags|=128,t.child=e.child,t=eS.bind(null,e),a._reactRetry=t,null):(e=l.treeContext,wi=ws(a.nextSibling),yi=t,nn=!0,Xi=null,e!==null&&(Fi[Oi++]=Po,Fi[Oi++]=$o,Fi[Oi++]=ua,Po=e.id,$o=e.overflow,ua=t),t=l0(t,o.children),t.flags|=4096,t)}function Jv(e,t,r){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),n_(e.return,t,r)}function Tg(e,t,r,o,a){var l=e.memoizedState;l===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:r,tailMode:a}:(l.isBackwards=t,l.rendering=null,l.renderingStartTime=0,l.last=o,l.tail=r,l.tailMode=a)}function g2(e,t,r){var o=t.pendingProps,a=o.revealOrder,l=o.tail;if(ei(e,t,o.children,r),o=sn.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&&Jv(e,r,t);else if(e.tag===19)Jv(e,r,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(Qr(sn,o),!(t.mode&1))t.memoizedState=null;else switch(a){case"forwards":for(r=t.child,a=null;r!==null;)e=r.alternate,e!==null&&Uh(e)===null&&(a=r),r=r.sibling;r=a,r===null?(a=t.child,t.child=null):(a=r.sibling,r.sibling=null),Tg(t,!1,a,r,l);break;case"backwards":for(r=null,a=t.child,t.child=null;a!==null;){if(e=a.alternate,e!==null&&Uh(e)===null){t.child=a;break}e=a.sibling,a.sibling=r,r=a,a=e}Tg(t,!0,r,null,l);break;case"together":Tg(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function bh(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function zo(e,t,r){if(e!==null&&(t.dependencies=e.dependencies),da|=t.lanes,!(r&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(xt(153));if(t.child!==null){for(e=t.child,r=xs(e,e.pendingProps),t.child=r,r.return=t;e.sibling!==null;)e=e.sibling,r=r.sibling=xs(e,e.pendingProps),r.return=t;r.sibling=null}return t.child}function Uk(e,t,r){switch(t.tag){case 3:h2(t),eu();break;case 5:Ub(t);break;case 1:ci(t.type)&&Dh(t);break;case 4:e0(t,t.stateNode.containerInfo);break;case 10:var o=t.type._context,a=t.memoizedProps.value;Qr(Bh,o._currentValue),o._currentValue=a;break;case 13:if(o=t.memoizedState,o!==null)return o.dehydrated!==null?(Qr(sn,sn.current&1),t.flags|=128,null):r&t.child.childLanes?m2(e,t,r):(Qr(sn,sn.current&1),e=zo(e,t,r),e!==null?e.sibling:null);Qr(sn,sn.current&1);break;case 19:if(o=(r&t.childLanes)!==0,e.flags&128){if(o)return g2(e,t,r);t.flags|=128}if(a=t.memoizedState,a!==null&&(a.rendering=null,a.tail=null,a.lastEffect=null),Qr(sn,sn.current),o)break;return null;case 22:case 23:return t.lanes=0,p2(e,t,r)}return zo(e,t,r)}var _2,d_,w2,y2;_2=function(e,t){for(var r=t.child;r!==null;){if(r.tag===5||r.tag===6)e.appendChild(r.stateNode);else if(r.tag!==4&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===t)break;for(;r.sibling===null;){if(r.return===null||r.return===t)return;r=r.return}r.sibling.return=r.return,r=r.sibling}};d_=function(){};w2=function(e,t,r,o){var a=e.memoizedProps;if(a!==o){e=t.stateNode,oa(po.current);var l=null;switch(r){case"input":a=Fg(e,a),o=Fg(e,o),l=[];break;case"select":a=ln({},a,{value:void 0}),o=ln({},o,{value:void 0}),l=[];break;case"textarea":a=Dg(e,a),o=Dg(e,o),l=[];break;default:typeof a.onClick!="function"&&typeof o.onClick=="function"&&(e.onclick=Oh)}Rg(r,o);var p;r=null;for(g in a)if(!o.hasOwnProperty(g)&&a.hasOwnProperty(g)&&a[g]!=null)if(g==="style"){var _=a[g];for(p in _)_.hasOwnProperty(p)&&(r||(r={}),r[p]="")}else g!=="dangerouslySetInnerHTML"&&g!=="children"&&g!=="suppressContentEditableWarning"&&g!=="suppressHydrationWarning"&&g!=="autoFocus"&&(Ip.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(p in _)!_.hasOwnProperty(p)||h&&h.hasOwnProperty(p)||(r||(r={}),r[p]="");for(p in h)h.hasOwnProperty(p)&&_[p]!==h[p]&&(r||(r={}),r[p]=h[p])}else r||(l||(l=[]),l.push(g,r)),r=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"&&(Ip.hasOwnProperty(g)?(h!=null&&g==="onScroll"&&Jr("scroll",e),l||_===h||(l=[])):(l=l||[]).push(g,h))}r&&(l=l||[]).push("style",r);var g=l;(t.updateQueue=g)&&(t.flags|=4)}};y2=function(e,t,r,o){r!==o&&(t.flags|=4)};function gp(e,t){if(!nn)switch(e.tailMode){case"hidden":t=e.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?e.tail=null:r.sibling=null;break;case"collapsed":r=e.tail;for(var o=null;r!==null;)r.alternate!==null&&(o=r),r=r.sibling;o===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function Gn(e){var t=e.alternate!==null&&e.alternate.child===e.child,r=0,o=0;if(t)for(var a=e.child;a!==null;)r|=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;)r|=a.lanes|a.childLanes,o|=a.subtreeFlags,o|=a.flags,a.return=e,a=a.sibling;return e.subtreeFlags|=o,e.childLanes=r,t}function Vk(e,t,r){var o=t.pendingProps;switch(q_(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Gn(t),null;case 1:return ci(t.type)&&zh(),Gn(t),null;case 3:return o=t.stateNode,ru(),tn(ui),tn(qn),r0(),o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(e===null||e.child===null)&&(oh(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Xi!==null&&(y_(Xi),Xi=null))),d_(e,t),Gn(t),null;case 5:t0(t);var a=oa(Wp.current);if(r=t.type,e!==null&&t.stateNode!=null)w2(e,t,r,o,a),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!o){if(t.stateNode===null)throw Error(xt(166));return Gn(t),null}if(e=oa(po.current),oh(t)){o=t.stateNode,r=t.type;var l=t.memoizedProps;switch(o[uo]=t,o[Up]=l,e=(t.mode&1)!==0,r){case"dialog":Jr("cancel",o),Jr("close",o);break;case"iframe":case"object":case"embed":Jr("load",o);break;case"video":case"audio":for(a=0;a<bp.length;a++)Jr(bp[a],o);break;case"source":Jr("error",o);break;case"img":case"image":case"link":Jr("error",o),Jr("load",o);break;case"details":Jr("toggle",o);break;case"input":lv(o,l),Jr("invalid",o);break;case"select":o._wrapperState={wasMultiple:!!l.multiple},Jr("invalid",o);break;case"textarea":cv(o,l),Jr("invalid",o)}Rg(r,l),a=null;for(var p in l)if(l.hasOwnProperty(p)){var _=l[p];p==="children"?typeof _=="string"?o.textContent!==_&&(l.suppressHydrationWarning!==!0&&ih(o.textContent,_,e),a=["children",_]):typeof _=="number"&&o.textContent!==""+_&&(l.suppressHydrationWarning!==!0&&ih(o.textContent,_,e),a=["children",""+_]):Ip.hasOwnProperty(p)&&_!=null&&p==="onScroll"&&Jr("scroll",o)}switch(r){case"input":Qf(o),uv(o,l,!0);break;case"textarea":Qf(o),dv(o);break;case"select":case"option":break;default:typeof l.onClick=="function"&&(o.onclick=Oh)}o=a,t.updateQueue=o,o!==null&&(t.flags|=4)}else{p=a.nodeType===9?a:a.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=q1(r)),e==="http://www.w3.org/1999/xhtml"?r==="script"?(e=p.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=p.createElement(r,{is:o.is}):(e=p.createElement(r),r==="select"&&(p=e,o.multiple?p.multiple=!0:o.size&&(p.size=o.size))):e=p.createElementNS(e,r),e[uo]=t,e[Up]=o,_2(e,t,!1,!1),t.stateNode=e;e:{switch(p=Bg(r,o),r){case"dialog":Jr("cancel",e),Jr("close",e),a=o;break;case"iframe":case"object":case"embed":Jr("load",e),a=o;break;case"video":case"audio":for(a=0;a<bp.length;a++)Jr(bp[a],e);a=o;break;case"source":Jr("error",e),a=o;break;case"img":case"image":case"link":Jr("error",e),Jr("load",e),a=o;break;case"details":Jr("toggle",e),a=o;break;case"input":lv(e,o),a=Fg(e,o),Jr("invalid",e);break;case"option":a=o;break;case"select":e._wrapperState={wasMultiple:!!o.multiple},a=ln({},o,{value:void 0}),Jr("invalid",e);break;case"textarea":cv(e,o),a=Dg(e,o),Jr("invalid",e);break;default:a=o}Rg(r,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&&K1(e,h)):l==="children"?typeof h=="string"?(r!=="textarea"||h!=="")&&Fp(e,h):typeof h=="number"&&Fp(e,""+h):l!=="suppressContentEditableWarning"&&l!=="suppressHydrationWarning"&&l!=="autoFocus"&&(Ip.hasOwnProperty(l)?h!=null&&l==="onScroll"&&Jr("scroll",e):h!=null&&I_(e,l,h,p))}switch(r){case"input":Qf(e),uv(e,o,!1);break;case"textarea":Qf(e),dv(e);break;case"option":o.value!=null&&e.setAttribute("value",""+Ms(o.value));break;case"select":e.multiple=!!o.multiple,l=o.value,l!=null?Hl(e,!!o.multiple,l,!1):o.defaultValue!=null&&Hl(e,!!o.multiple,o.defaultValue,!0);break;default:typeof a.onClick=="function"&&(e.onclick=Oh)}switch(r){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 Gn(t),null;case 6:if(e&&t.stateNode!=null)y2(e,t,e.memoizedProps,o);else{if(typeof o!="string"&&t.stateNode===null)throw Error(xt(166));if(r=oa(Wp.current),oa(po.current),oh(t)){if(o=t.stateNode,r=t.memoizedProps,o[uo]=t,(l=o.nodeValue!==r)&&(e=yi,e!==null))switch(e.tag){case 3:ih(o.nodeValue,r,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&ih(o.nodeValue,r,(e.mode&1)!==0)}l&&(t.flags|=4)}else o=(r.nodeType===9?r:r.ownerDocument).createTextNode(o),o[uo]=t,t.stateNode=o}return Gn(t),null;case 13:if(tn(sn),o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(nn&&wi!==null&&t.mode&1&&!(t.flags&128))Lb(),eu(),t.flags|=98560,l=!1;else if(l=oh(t),o!==null&&o.dehydrated!==null){if(e===null){if(!l)throw Error(xt(318));if(l=t.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(xt(317));l[uo]=t}else eu(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Gn(t),l=!1}else Xi!==null&&(y_(Xi),Xi=null),l=!0;if(!l)return t.flags&65536?t:null}return t.flags&128?(t.lanes=r,t):(o=o!==null,o!==(e!==null&&e.memoizedState!==null)&&o&&(t.child.flags|=8192,t.mode&1&&(e===null||sn.current&1?En===0&&(En=3):h0())),t.updateQueue!==null&&(t.flags|=4),Gn(t),null);case 4:return ru(),d_(e,t),e===null&&Np(t.stateNode.containerInfo),Gn(t),null;case 10:return Y_(t.type._context),Gn(t),null;case 17:return ci(t.type)&&zh(),Gn(t),null;case 19:if(tn(sn),l=t.memoizedState,l===null)return Gn(t),null;if(o=(t.flags&128)!==0,p=l.rendering,p===null)if(o)gp(l,!1);else{if(En!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(p=Uh(e),p!==null){for(t.flags|=128,gp(l,!1),o=p.updateQueue,o!==null&&(t.updateQueue=o,t.flags|=4),t.subtreeFlags=0,o=r,r=t.child;r!==null;)l=r,e=o,l.flags&=14680066,p=l.alternate,p===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=p.childLanes,l.lanes=p.lanes,l.child=p.child,l.subtreeFlags=0,l.deletions=null,l.memoizedProps=p.memoizedProps,l.memoizedState=p.memoizedState,l.updateQueue=p.updateQueue,l.type=p.type,e=p.dependencies,l.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),r=r.sibling;return Qr(sn,sn.current&1|2),t.child}e=e.sibling}l.tail!==null&&mn()>iu&&(t.flags|=128,o=!0,gp(l,!1),t.lanes=4194304)}else{if(!o)if(e=Uh(p),e!==null){if(t.flags|=128,o=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),gp(l,!0),l.tail===null&&l.tailMode==="hidden"&&!p.alternate&&!nn)return Gn(t),null}else 2*mn()-l.renderingStartTime>iu&&r!==1073741824&&(t.flags|=128,o=!0,gp(l,!1),t.lanes=4194304);l.isBackwards?(p.sibling=t.child,t.child=p):(r=l.last,r!==null?r.sibling=p:t.child=p,l.last=p)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=mn(),t.sibling=null,r=sn.current,Qr(sn,o?r&1|2:r&1),t):(Gn(t),null);case 22:case 23:return f0(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?_i&1073741824&&(Gn(t),t.subtreeFlags&6&&(t.flags|=8192)):Gn(t),null;case 24:return null;case 25:return null}throw Error(xt(156,t.tag))}function Wk(e,t){switch(q_(t),t.tag){case 1:return ci(t.type)&&zh(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ru(),tn(ui),tn(qn),r0(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return t0(t),null;case 13:if(tn(sn),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(xt(340));eu()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return tn(sn),null;case 4:return ru(),null;case 10:return Y_(t.type._context),null;case 22:case 23:return f0(),null;case 24:return null;default:return null}}var lh=!1,Hn=!1,Gk=typeof WeakSet=="function"?WeakSet:Set,jt=null;function Wl(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(o){fn(e,t,o)}else r.current=null}function p_(e,t,r){try{r()}catch(o){fn(e,t,o)}}var e1=!1;function Hk(e,t){if(Xg=Ah,e=Tb(),G_(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var a=o.anchorOffset,l=o.focusNode;o=o.focusOffset;try{r.nodeType,l.nodeType}catch{r=null;break e}var p=0,_=-1,h=-1,g=0,M=0,y=e,E=null;t:for(;;){for(var T;y!==r||a!==0&&y.nodeType!==3||(_=p+a),y!==l||o!==0&&y.nodeType!==3||(h=p+o),y.nodeType===3&&(p+=y.nodeValue.length),(T=y.firstChild)!==null;)E=y,y=T;for(;;){if(y===e)break t;if(E===r&&++g===a&&(_=p),E===l&&++M===o&&(h=p),(T=y.nextSibling)!==null)break;y=E,E=y.parentNode}y=T}r=_===-1||h===-1?null:{start:_,end:h}}else r=null}r=r||{start:0,end:0}}else r=null;for(Qg={focusedElem:e,selectionRange:r},Ah=!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 O=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(O!==null){var S=O.memoizedProps,C=O.memoizedState,w=t.stateNode,b=w.getSnapshotBeforeUpdate(t.elementType===t.type?S:qi(t.type,S),C);w.__reactInternalSnapshotBeforeUpdate=b}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(xt(163))}}catch(U){fn(t,t.return,U)}if(e=t.sibling,e!==null){e.return=t.return,jt=e;break}jt=t.return}return O=e1,e1=!1,O}function Pp(e,t,r){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&&p_(t,r,l)}a=a.next}while(a!==o)}}function lm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var o=r.create;r.destroy=o()}r=r.next}while(r!==t)}}function f_(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function v2(e){var t=e.alternate;t!==null&&(e.alternate=null,v2(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[uo],delete t[Up],delete t[Jg],delete t[Ck],delete t[Pk])),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 b2(e){return e.tag===5||e.tag===3||e.tag===4}function t1(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||b2(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 h_(e,t,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Oh));else if(o!==4&&(e=e.child,e!==null))for(h_(e,t,r),e=e.sibling;e!==null;)h_(e,t,r),e=e.sibling}function m_(e,t,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(m_(e,t,r),e=e.sibling;e!==null;)m_(e,t,r),e=e.sibling}var Rn=null,Ki=!1;function ls(e,t,r){for(r=r.child;r!==null;)x2(e,t,r),r=r.sibling}function x2(e,t,r){if(co&&typeof co.onCommitFiberUnmount=="function")try{co.onCommitFiberUnmount(em,r)}catch{}switch(r.tag){case 5:Hn||Wl(r,t);case 6:var o=Rn,a=Ki;Rn=null,ls(e,t,r),Rn=o,Ki=a,Rn!==null&&(Ki?(e=Rn,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Rn.removeChild(r.stateNode));break;case 18:Rn!==null&&(Ki?(e=Rn,r=r.stateNode,e.nodeType===8?_g(e.parentNode,r):e.nodeType===1&&_g(e,r),Lp(e)):_g(Rn,r.stateNode));break;case 4:o=Rn,a=Ki,Rn=r.stateNode.containerInfo,Ki=!0,ls(e,t,r),Rn=o,Ki=a;break;case 0:case 11:case 14:case 15:if(!Hn&&(o=r.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var l=a,p=l.destroy;l=l.tag,p!==void 0&&(l&2||l&4)&&p_(r,t,p),a=a.next}while(a!==o)}ls(e,t,r);break;case 1:if(!Hn&&(Wl(r,t),o=r.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=r.memoizedProps,o.state=r.memoizedState,o.componentWillUnmount()}catch(_){fn(r,t,_)}ls(e,t,r);break;case 21:ls(e,t,r);break;case 22:r.mode&1?(Hn=(o=Hn)||r.memoizedState!==null,ls(e,t,r),Hn=o):ls(e,t,r);break;default:ls(e,t,r)}}function r1(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new Gk),t.forEach(function(o){var a=tS.bind(null,e,o);r.has(o)||(r.add(o),o.then(a,a))})}}function Hi(e,t){var r=t.deletions;if(r!==null)for(var o=0;o<r.length;o++){var a=r[o];try{var l=e,p=t,_=p;e:for(;_!==null;){switch(_.tag){case 5:Rn=_.stateNode,Ki=!1;break e;case 3:Rn=_.stateNode.containerInfo,Ki=!0;break e;case 4:Rn=_.stateNode.containerInfo,Ki=!0;break e}_=_.return}if(Rn===null)throw Error(xt(160));x2(l,p,a),Rn=null,Ki=!1;var h=a.alternate;h!==null&&(h.return=null),a.return=null}catch(g){fn(a,t,g)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)M2(t,e),t=t.sibling}function M2(e,t){var r=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Hi(t,e),so(e),o&4){try{Pp(3,e,e.return),lm(3,e)}catch(S){fn(e,e.return,S)}try{Pp(5,e,e.return)}catch(S){fn(e,e.return,S)}}break;case 1:Hi(t,e),so(e),o&512&&r!==null&&Wl(r,r.return);break;case 5:if(Hi(t,e),so(e),o&512&&r!==null&&Wl(r,r.return),e.flags&32){var a=e.stateNode;try{Fp(a,"")}catch(S){fn(e,e.return,S)}}if(o&4&&(a=e.stateNode,a!=null)){var l=e.memoizedProps,p=r!==null?r.memoizedProps:l,_=e.type,h=e.updateQueue;if(e.updateQueue=null,h!==null)try{_==="input"&&l.type==="radio"&&l.name!=null&&G1(a,l),Bg(_,p);var g=Bg(_,l);for(p=0;p<h.length;p+=2){var M=h[p],y=h[p+1];M==="style"?Q1(a,y):M==="dangerouslySetInnerHTML"?K1(a,y):M==="children"?Fp(a,y):I_(a,M,y,g)}switch(_){case"input":Og(a,l);break;case"textarea":H1(a,l);break;case"select":var E=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!l.multiple;var T=l.value;T!=null?Hl(a,!!l.multiple,T,!1):E!==!!l.multiple&&(l.defaultValue!=null?Hl(a,!!l.multiple,l.defaultValue,!0):Hl(a,!!l.multiple,l.multiple?[]:"",!1))}a[Up]=l}catch(S){fn(e,e.return,S)}}break;case 6:if(Hi(t,e),so(e),o&4){if(e.stateNode===null)throw Error(xt(162));a=e.stateNode,l=e.memoizedProps;try{a.nodeValue=l}catch(S){fn(e,e.return,S)}}break;case 3:if(Hi(t,e),so(e),o&4&&r!==null&&r.memoizedState.isDehydrated)try{Lp(t.containerInfo)}catch(S){fn(e,e.return,S)}break;case 4:Hi(t,e),so(e);break;case 13:Hi(t,e),so(e),a=e.child,a.flags&8192&&(l=a.memoizedState!==null,a.stateNode.isHidden=l,!l||a.alternate!==null&&a.alternate.memoizedState!==null||(d0=mn())),o&4&&r1(e);break;case 22:if(M=r!==null&&r.memoizedState!==null,e.mode&1?(Hn=(g=Hn)||M,Hi(t,e),Hn=g):Hi(t,e),so(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(y=jt=M;jt!==null;){switch(E=jt,T=E.child,E.tag){case 0:case 11:case 14:case 15:Pp(4,E,E.return);break;case 1:Wl(E,E.return);var O=E.stateNode;if(typeof O.componentWillUnmount=="function"){o=E,r=E.return;try{t=o,O.props=t.memoizedProps,O.state=t.memoizedState,O.componentWillUnmount()}catch(S){fn(o,r,S)}}break;case 5:Wl(E,E.return);break;case 22:if(E.memoizedState!==null){i1(y);continue}}T!==null?(T.return=E,jt=T):i1(y)}M=M.sibling}e:for(M=null,y=e;;){if(y.tag===5){if(M===null){M=y;try{a=y.stateNode,g?(l=a.style,typeof l.setProperty=="function"?l.setProperty("display","none","important"):l.display="none"):(_=y.stateNode,h=y.memoizedProps.style,p=h!=null&&h.hasOwnProperty("display")?h.display:null,_.style.display=X1("display",p))}catch(S){fn(e,e.return,S)}}}else if(y.tag===6){if(M===null)try{y.stateNode.nodeValue=g?"":y.memoizedProps}catch(S){fn(e,e.return,S)}}else if((y.tag!==22&&y.tag!==23||y.memoizedState===null||y===e)&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===e)break e;for(;y.sibling===null;){if(y.return===null||y.return===e)break e;M===y&&(M=null),y=y.return}M===y&&(M=null),y.sibling.return=y.return,y=y.sibling}}break;case 19:Hi(t,e),so(e),o&4&&r1(e);break;case 21:break;default:Hi(t,e),so(e)}}function so(e){var t=e.flags;if(t&2){try{e:{for(var r=e.return;r!==null;){if(b2(r)){var o=r;break e}r=r.return}throw Error(xt(160))}switch(o.tag){case 5:var a=o.stateNode;o.flags&32&&(Fp(a,""),o.flags&=-33);var l=t1(e);m_(e,l,a);break;case 3:case 4:var p=o.stateNode.containerInfo,_=t1(e);h_(e,_,p);break;default:throw Error(xt(161))}}catch(h){fn(e,e.return,h)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function qk(e,t,r){jt=e,T2(e)}function T2(e,t,r){for(var o=(e.mode&1)!==0;jt!==null;){var a=jt,l=a.child;if(a.tag===22&&o){var p=a.memoizedState!==null||lh;if(!p){var _=a.alternate,h=_!==null&&_.memoizedState!==null||Hn;_=lh;var g=Hn;if(lh=p,(Hn=h)&&!g)for(jt=a;jt!==null;)p=jt,h=p.child,p.tag===22&&p.memoizedState!==null?o1(a):h!==null?(h.return=p,jt=h):o1(a);for(;l!==null;)jt=l,T2(l),l=l.sibling;jt=a,lh=_,Hn=g}n1(e)}else a.subtreeFlags&8772&&l!==null?(l.return=a,jt=l):n1(e)}}function n1(e){for(;jt!==null;){var t=jt;if(t.flags&8772){var r=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:Hn||lm(5,t);break;case 1:var o=t.stateNode;if(t.flags&4&&!Hn)if(r===null)o.componentDidMount();else{var a=t.elementType===t.type?r.memoizedProps:qi(t.type,r.memoizedProps);o.componentDidUpdate(a,r.memoizedState,o.__reactInternalSnapshotBeforeUpdate)}var l=t.updateQueue;l!==null&&jv(t,l,o);break;case 3:var p=t.updateQueue;if(p!==null){if(r=null,t.child!==null)switch(t.child.tag){case 5:r=t.child.stateNode;break;case 1:r=t.child.stateNode}jv(t,p,r)}break;case 5:var _=t.stateNode;if(r===null&&t.flags&4){r=_;var h=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":h.autoFocus&&r.focus();break;case"img":h.src&&(r.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 y=M.dehydrated;y!==null&&Lp(y)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(xt(163))}Hn||t.flags&512&&f_(t)}catch(E){fn(t,t.return,E)}}if(t===e){jt=null;break}if(r=t.sibling,r!==null){r.return=t.return,jt=r;break}jt=t.return}}function i1(e){for(;jt!==null;){var t=jt;if(t===e){jt=null;break}var r=t.sibling;if(r!==null){r.return=t.return,jt=r;break}jt=t.return}}function o1(e){for(;jt!==null;){var t=jt;try{switch(t.tag){case 0:case 11:case 15:var r=t.return;try{lm(4,t)}catch(h){fn(t,r,h)}break;case 1:var o=t.stateNode;if(typeof o.componentDidMount=="function"){var a=t.return;try{o.componentDidMount()}catch(h){fn(t,a,h)}}var l=t.return;try{f_(t)}catch(h){fn(t,l,h)}break;case 5:var p=t.return;try{f_(t)}catch(h){fn(t,p,h)}}}catch(h){fn(t,t.return,h)}if(t===e){jt=null;break}var _=t.sibling;if(_!==null){_.return=t.return,jt=_;break}jt=t.return}}var Kk=Math.ceil,Gh=Do.ReactCurrentDispatcher,u0=Do.ReactCurrentOwner,Di=Do.ReactCurrentBatchConfig,zr=0,Fn=null,_n=null,Bn=0,_i=0,Gl=Ss(0),En=0,Kp=null,da=0,um=0,c0=0,$p=null,ai=null,d0=0,iu=1/0,So=null,Hh=!1,g_=null,vs=null,uh=!1,hs=null,qh=0,Ap=0,__=null,xh=-1,Mh=0;function ti(){return zr&6?mn():xh!==-1?xh:xh=mn()}function bs(e){return e.mode&1?zr&2&&Bn!==0?Bn&-Bn:Ak.transition!==null?(Mh===0&&(Mh=lb()),Mh):(e=Ur,e!==0||(e=window.event,e=e===void 0?16:mb(e.type)),e):1}function Yi(e,t,r,o){if(50<Ap)throw Ap=0,__=null,Error(xt(185));Yp(e,r,o),(!(zr&2)||e!==Fn)&&(e===Fn&&(!(zr&2)&&(um|=r),En===4&&ps(e,Bn)),di(e,o),r===1&&zr===0&&!(t.mode&1)&&(iu=mn()+500,om&&Es()))}function di(e,t){var r=e.callbackNode;AT(e,t);var o=$h(e,e===Fn?Bn:0);if(o===0)r!==null&&hv(r),e.callbackNode=null,e.callbackPriority=0;else if(t=o&-o,e.callbackPriority!==t){if(r!=null&&hv(r),t===1)e.tag===0?$k(s1.bind(null,e)):Ob(s1.bind(null,e)),Sk(function(){!(zr&6)&&Es()}),r=null;else{switch(ub(o)){case 1:r=L_;break;case 4:r=sb;break;case 16:r=Ph;break;case 536870912:r=ab;break;default:r=Ph}r=I2(r,k2.bind(null,e))}e.callbackPriority=t,e.callbackNode=r}}function k2(e,t){if(xh=-1,Mh=0,zr&6)throw Error(xt(327));var r=e.callbackNode;if(Yl()&&e.callbackNode!==r)return null;var o=$h(e,e===Fn?Bn:0);if(o===0)return null;if(o&30||o&e.expiredLanes||t)t=Kh(e,o);else{t=o;var a=zr;zr|=2;var l=E2();(Fn!==e||Bn!==t)&&(So=null,iu=mn()+500,sa(e,t));do try{Yk();break}catch(_){S2(e,_)}while(!0);Q_(),Gh.current=l,zr=a,_n!==null?t=0:(Fn=null,Bn=0,t=En)}if(t!==0){if(t===2&&(a=Wg(e),a!==0&&(o=a,t=w_(e,a))),t===1)throw r=Kp,sa(e,0),ps(e,o),di(e,mn()),r;if(t===6)ps(e,o);else{if(a=e.current.alternate,!(o&30)&&!Xk(a)&&(t=Kh(e,o),t===2&&(l=Wg(e),l!==0&&(o=l,t=w_(e,l))),t===1))throw r=Kp,sa(e,0),ps(e,o),di(e,mn()),r;switch(e.finishedWork=a,e.finishedLanes=o,t){case 0:case 1:throw Error(xt(345));case 2:ta(e,ai,So);break;case 3:if(ps(e,o),(o&130023424)===o&&(t=d0+500-mn(),10<t)){if($h(e,0)!==0)break;if(a=e.suspendedLanes,(a&o)!==o){ti(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=Zg(ta.bind(null,e,ai,So),t);break}ta(e,ai,So);break;case 4:if(ps(e,o),(o&4194240)===o)break;for(t=e.eventTimes,a=-1;0<o;){var p=31-Qi(o);l=1<<p,p=t[p],p>a&&(a=p),o&=~l}if(o=a,o=mn()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*Kk(o/1960))-o,10<o){e.timeoutHandle=Zg(ta.bind(null,e,ai,So),o);break}ta(e,ai,So);break;case 5:ta(e,ai,So);break;default:throw Error(xt(329))}}}return di(e,mn()),e.callbackNode===r?k2.bind(null,e):null}function w_(e,t){var r=$p;return e.current.memoizedState.isDehydrated&&(sa(e,t).flags|=256),e=Kh(e,t),e!==2&&(t=ai,ai=r,t!==null&&y_(t)),e}function y_(e){ai===null?ai=e:ai.push.apply(ai,e)}function Xk(e){for(var t=e;;){if(t.flags&16384){var r=t.updateQueue;if(r!==null&&(r=r.stores,r!==null))for(var o=0;o<r.length;o++){var a=r[o],l=a.getSnapshot;a=a.value;try{if(!Zi(l(),a))return!1}catch{return!1}}}if(r=t.child,t.subtreeFlags&16384&&r!==null)r.return=t,t=r;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 ps(e,t){for(t&=~c0,t&=~um,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var r=31-Qi(t),o=1<<r;e[r]=-1,t&=~o}}function s1(e){if(zr&6)throw Error(xt(327));Yl();var t=$h(e,0);if(!(t&1))return di(e,mn()),null;var r=Kh(e,t);if(e.tag!==0&&r===2){var o=Wg(e);o!==0&&(t=o,r=w_(e,o))}if(r===1)throw r=Kp,sa(e,0),ps(e,t),di(e,mn()),r;if(r===6)throw Error(xt(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,ta(e,ai,So),di(e,mn()),null}function p0(e,t){var r=zr;zr|=1;try{return e(t)}finally{zr=r,zr===0&&(iu=mn()+500,om&&Es())}}function pa(e){hs!==null&&hs.tag===0&&!(zr&6)&&Yl();var t=zr;zr|=1;var r=Di.transition,o=Ur;try{if(Di.transition=null,Ur=1,e)return e()}finally{Ur=o,Di.transition=r,zr=t,!(zr&6)&&Es()}}function f0(){_i=Gl.current,tn(Gl)}function sa(e,t){e.finishedWork=null,e.finishedLanes=0;var r=e.timeoutHandle;if(r!==-1&&(e.timeoutHandle=-1,kk(r)),_n!==null)for(r=_n.return;r!==null;){var o=r;switch(q_(o),o.tag){case 1:o=o.type.childContextTypes,o!=null&&zh();break;case 3:ru(),tn(ui),tn(qn),r0();break;case 5:t0(o);break;case 4:ru();break;case 13:tn(sn);break;case 19:tn(sn);break;case 10:Y_(o.type._context);break;case 22:case 23:f0()}r=r.return}if(Fn=e,_n=e=xs(e.current,null),Bn=_i=t,En=0,Kp=null,c0=um=da=0,ai=$p=null,ia!==null){for(t=0;t<ia.length;t++)if(r=ia[t],o=r.interleaved,o!==null){r.interleaved=null;var a=o.next,l=r.pending;if(l!==null){var p=l.next;l.next=a,o.next=p}r.pending=o}ia=null}return e}function S2(e,t){do{var r=_n;try{if(Q_(),yh.current=Wh,Vh){for(var o=an.memoizedState;o!==null;){var a=o.queue;a!==null&&(a.pending=null),o=o.next}Vh=!1}if(ca=0,In=Sn=an=null,Cp=!1,Gp=0,u0.current=null,r===null||r.return===null){En=1,Kp=t,_n=null;break}e:{var l=e,p=r.return,_=r,h=t;if(t=Bn,_.flags|=32768,h!==null&&typeof h=="object"&&typeof h.then=="function"){var g=h,M=_,y=M.tag;if(!(M.mode&1)&&(y===0||y===11||y===15)){var E=M.alternate;E?(M.updateQueue=E.updateQueue,M.memoizedState=E.memoizedState,M.lanes=E.lanes):(M.updateQueue=null,M.memoizedState=null)}var T=qv(p);if(T!==null){T.flags&=-257,Kv(T,p,_,l,t),T.mode&1&&Hv(l,g,t),t=T,h=g;var O=t.updateQueue;if(O===null){var S=new Set;S.add(h),t.updateQueue=S}else O.add(h);break e}else{if(!(t&1)){Hv(l,g,t),h0();break e}h=Error(xt(426))}}else if(nn&&_.mode&1){var C=qv(p);if(C!==null){!(C.flags&65536)&&(C.flags|=256),Kv(C,p,_,l,t),K_(nu(h,_));break e}}l=h=nu(h,_),En!==4&&(En=2),$p===null?$p=[l]:$p.push(l),l=p;do{switch(l.tag){case 3:l.flags|=65536,t&=-t,l.lanes|=t;var w=u2(l,h,t);Nv(l,w);break e;case 1:_=h;var b=l.type,I=l.stateNode;if(!(l.flags&128)&&(typeof b.getDerivedStateFromError=="function"||I!==null&&typeof I.componentDidCatch=="function"&&(vs===null||!vs.has(I)))){l.flags|=65536,t&=-t,l.lanes|=t;var U=c2(l,_,t);Nv(l,U);break e}}l=l.return}while(l!==null)}P2(r)}catch(z){t=z,_n===r&&r!==null&&(_n=r=r.return);continue}break}while(!0)}function E2(){var e=Gh.current;return Gh.current=Wh,e===null?Wh:e}function h0(){(En===0||En===3||En===2)&&(En=4),Fn===null||!(da&268435455)&&!(um&268435455)||ps(Fn,Bn)}function Kh(e,t){var r=zr;zr|=2;var o=E2();(Fn!==e||Bn!==t)&&(So=null,sa(e,t));do try{Qk();break}catch(a){S2(e,a)}while(!0);if(Q_(),zr=r,Gh.current=o,_n!==null)throw Error(xt(261));return Fn=null,Bn=0,En}function Qk(){for(;_n!==null;)C2(_n)}function Yk(){for(;_n!==null&&!xT();)C2(_n)}function C2(e){var t=A2(e.alternate,e,_i);e.memoizedProps=e.pendingProps,t===null?P2(e):_n=t,u0.current=null}function P2(e){var t=e;do{var r=t.alternate;if(e=t.return,t.flags&32768){if(r=Wk(r,t),r!==null){r.flags&=32767,_n=r;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{En=6,_n=null;return}}else if(r=Vk(r,t,_i),r!==null){_n=r;return}if(t=t.sibling,t!==null){_n=t;return}_n=t=e}while(t!==null);En===0&&(En=5)}function ta(e,t,r){var o=Ur,a=Di.transition;try{Di.transition=null,Ur=1,Zk(e,t,r,o)}finally{Di.transition=a,Ur=o}return null}function Zk(e,t,r,o){do Yl();while(hs!==null);if(zr&6)throw Error(xt(327));r=e.finishedWork;var a=e.finishedLanes;if(r===null)return null;if(e.finishedWork=null,e.finishedLanes=0,r===e.current)throw Error(xt(177));e.callbackNode=null,e.callbackPriority=0;var l=r.lanes|r.childLanes;if(IT(e,l),e===Fn&&(_n=Fn=null,Bn=0),!(r.subtreeFlags&2064)&&!(r.flags&2064)||uh||(uh=!0,I2(Ph,function(){return Yl(),null})),l=(r.flags&15990)!==0,r.subtreeFlags&15990||l){l=Di.transition,Di.transition=null;var p=Ur;Ur=1;var _=zr;zr|=4,u0.current=null,Hk(e,r),M2(r,e),wk(Qg),Ah=!!Xg,Qg=Xg=null,e.current=r,qk(r),MT(),zr=_,Ur=p,Di.transition=l}else e.current=r;if(uh&&(uh=!1,hs=e,qh=a),l=e.pendingLanes,l===0&&(vs=null),ST(r.stateNode),di(e,mn()),t!==null)for(o=e.onRecoverableError,r=0;r<t.length;r++)a=t[r],o(a.value,{componentStack:a.stack,digest:a.digest});if(Hh)throw Hh=!1,e=g_,g_=null,e;return qh&1&&e.tag!==0&&Yl(),l=e.pendingLanes,l&1?e===__?Ap++:(Ap=0,__=e):Ap=0,Es(),null}function Yl(){if(hs!==null){var e=ub(qh),t=Di.transition,r=Ur;try{if(Di.transition=null,Ur=16>e?16:e,hs===null)var o=!1;else{if(e=hs,hs=null,qh=0,zr&6)throw Error(xt(331));var a=zr;for(zr|=4,jt=e.current;jt!==null;){var l=jt,p=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:Pp(8,M,l)}var y=M.child;if(y!==null)y.return=M,jt=y;else for(;jt!==null;){M=jt;var E=M.sibling,T=M.return;if(v2(M),M===g){jt=null;break}if(E!==null){E.return=T,jt=E;break}jt=T}}}var O=l.alternate;if(O!==null){var S=O.child;if(S!==null){O.child=null;do{var C=S.sibling;S.sibling=null,S=C}while(S!==null)}}jt=l}}if(l.subtreeFlags&2064&&p!==null)p.return=l,jt=p;else e:for(;jt!==null;){if(l=jt,l.flags&2048)switch(l.tag){case 0:case 11:case 15:Pp(9,l,l.return)}var w=l.sibling;if(w!==null){w.return=l.return,jt=w;break e}jt=l.return}}var b=e.current;for(jt=b;jt!==null;){p=jt;var I=p.child;if(p.subtreeFlags&2064&&I!==null)I.return=p,jt=I;else e:for(p=b;jt!==null;){if(_=jt,_.flags&2048)try{switch(_.tag){case 0:case 11:case 15:lm(9,_)}}catch(z){fn(_,_.return,z)}if(_===p){jt=null;break e}var U=_.sibling;if(U!==null){U.return=_.return,jt=U;break e}jt=_.return}}if(zr=a,Es(),co&&typeof co.onPostCommitFiberRoot=="function")try{co.onPostCommitFiberRoot(em,e)}catch{}o=!0}return o}finally{Ur=r,Di.transition=t}}return!1}function a1(e,t,r){t=nu(r,t),t=u2(e,t,1),e=ys(e,t,1),t=ti(),e!==null&&(Yp(e,1,t),di(e,t))}function fn(e,t,r){if(e.tag===3)a1(e,e,r);else for(;t!==null;){if(t.tag===3){a1(t,e,r);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(vs===null||!vs.has(o))){e=nu(r,e),e=c2(t,e,1),t=ys(t,e,1),e=ti(),t!==null&&(Yp(t,1,e),di(t,e));break}}t=t.return}}function Jk(e,t,r){var o=e.pingCache;o!==null&&o.delete(t),t=ti(),e.pingedLanes|=e.suspendedLanes&r,Fn===e&&(Bn&r)===r&&(En===4||En===3&&(Bn&130023424)===Bn&&500>mn()-d0?sa(e,0):c0|=r),di(e,t)}function $2(e,t){t===0&&(e.mode&1?(t=Jf,Jf<<=1,!(Jf&130023424)&&(Jf=4194304)):t=1);var r=ti();e=Oo(e,t),e!==null&&(Yp(e,t,r),di(e,r))}function eS(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),$2(e,r)}function tS(e,t){var r=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(r=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(xt(314))}o!==null&&o.delete(t),$2(e,r)}var A2;A2=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||ui.current)li=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return li=!1,Uk(e,t,r);li=!!(e.flags&131072)}else li=!1,nn&&t.flags&1048576&&zb(t,Rh,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;bh(e,t),e=t.pendingProps;var a=Jl(t,qn.current);Ql(t,r),a=i0(null,t,o,e,a,r);var l=o0();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,ci(o)?(l=!0,Dh(t)):l=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,J_(t),a.updater=am,t.stateNode=a,a._reactInternals=t,o_(t,o,e,r),t=l_(null,t,o,!0,l,r)):(t.tag=0,nn&&l&&H_(t),ei(null,t,a,r),t=t.child),t;case 16:o=t.elementType;e:{switch(bh(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=nS(o),e=qi(o,e),a){case 0:t=a_(null,t,o,e,r);break e;case 1:t=Yv(null,t,o,e,r);break e;case 11:t=Xv(null,t,o,e,r);break e;case 14:t=Qv(null,t,o,qi(o.type,e),r);break e}throw Error(xt(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),a_(e,t,o,a,r);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),Yv(e,t,o,a,r);case 3:e:{if(h2(t),e===null)throw Error(xt(387));o=t.pendingProps,l=t.memoizedState,a=l.element,jb(e,t),jh(t,o,null,r);var p=t.memoizedState;if(o=p.element,l.isDehydrated)if(l={element:o,isDehydrated:!1,cache:p.cache,pendingSuspenseBoundaries:p.pendingSuspenseBoundaries,transitions:p.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){a=nu(Error(xt(423)),t),t=Zv(e,t,o,r,a);break e}else if(o!==a){a=nu(Error(xt(424)),t),t=Zv(e,t,o,r,a);break e}else for(wi=ws(t.stateNode.containerInfo.firstChild),yi=t,nn=!0,Xi=null,r=Bb(t,null,o,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(eu(),o===a){t=zo(e,t,r);break e}ei(e,t,o,r)}t=t.child}return t;case 5:return Ub(t),e===null&&r_(t),o=t.type,a=t.pendingProps,l=e!==null?e.memoizedProps:null,p=a.children,Yg(o,a)?p=null:l!==null&&Yg(o,l)&&(t.flags|=32),f2(e,t),ei(e,t,p,r),t.child;case 6:return e===null&&r_(t),null;case 13:return m2(e,t,r);case 4:return e0(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=tu(t,null,o,r):ei(e,t,o,r),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),Xv(e,t,o,a,r);case 7:return ei(e,t,t.pendingProps,r),t.child;case 8:return ei(e,t,t.pendingProps.children,r),t.child;case 12:return ei(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,l=t.memoizedProps,p=a.value,Qr(Bh,o._currentValue),o._currentValue=p,l!==null)if(Zi(l.value,p)){if(l.children===a.children&&!ui.current){t=zo(e,t,r);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var _=l.dependencies;if(_!==null){p=l.child;for(var h=_.firstContext;h!==null;){if(h.context===o){if(l.tag===1){h=Ao(-1,r&-r),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|=r,h=l.alternate,h!==null&&(h.lanes|=r),n_(l.return,r,t),_.lanes|=r;break}h=h.next}}else if(l.tag===10)p=l.type===t.type?null:l.child;else if(l.tag===18){if(p=l.return,p===null)throw Error(xt(341));p.lanes|=r,_=p.alternate,_!==null&&(_.lanes|=r),n_(p,r,t),p=l.sibling}else p=l.child;if(p!==null)p.return=l;else for(p=l;p!==null;){if(p===t){p=null;break}if(l=p.sibling,l!==null){l.return=p.return,p=l;break}p=p.return}l=p}ei(e,t,a.children,r),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,Ql(t,r),a=Li(a),o=o(a),t.flags|=1,ei(e,t,o,r),t.child;case 14:return o=t.type,a=qi(o,t.pendingProps),a=qi(o.type,a),Qv(e,t,o,a,r);case 15:return d2(e,t,t.type,t.pendingProps,r);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),bh(e,t),t.tag=1,ci(o)?(e=!0,Dh(t)):e=!1,Ql(t,r),l2(t,o,a),o_(t,o,a,r),l_(null,t,o,!0,e,r);case 19:return g2(e,t,r);case 22:return p2(e,t,r)}throw Error(xt(156,t.tag))};function I2(e,t){return ob(e,t)}function rS(e,t,r,o){this.tag=e,this.key=r,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 zi(e,t,r,o){return new rS(e,t,r,o)}function m0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function nS(e){if(typeof e=="function")return m0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===O_)return 11;if(e===z_)return 14}return 2}function xs(e,t){var r=e.alternate;return r===null?(r=zi(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Th(e,t,r,o,a,l){var p=2;if(o=e,typeof e=="function")m0(e)&&(p=1);else if(typeof e=="string")p=5;else e:switch(e){case zl:return aa(r.children,a,l,t);case F_:p=8,a|=8;break;case Pg:return e=zi(12,r,t,a|2),e.elementType=Pg,e.lanes=l,e;case $g:return e=zi(13,r,t,a),e.elementType=$g,e.lanes=l,e;case Ag:return e=zi(19,r,t,a),e.elementType=Ag,e.lanes=l,e;case U1:return cm(r,a,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case N1:p=10;break e;case j1:p=9;break e;case O_:p=11;break e;case z_:p=14;break e;case us:p=16,o=null;break e}throw Error(xt(130,e==null?e:typeof e,""))}return t=zi(p,r,t,a),t.elementType=e,t.type=o,t.lanes=l,t}function aa(e,t,r,o){return e=zi(7,e,o,t),e.lanes=r,e}function cm(e,t,r,o){return e=zi(22,e,o,t),e.elementType=U1,e.lanes=r,e.stateNode={isHidden:!1},e}function kg(e,t,r){return e=zi(6,e,null,t),e.lanes=r,e}function Sg(e,t,r){return t=zi(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function iS(e,t,r,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=sg(0),this.expirationTimes=sg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=sg(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function g0(e,t,r,o,a,l,p,_,h){return e=new iS(e,t,r,_,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=zi(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:o,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},J_(l),e}function oS(e,t,r){var o=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Ol,key:o==null?null:""+o,children:e,containerInfo:t,implementation:r}}function F2(e){if(!e)return Ts;e=e._reactInternals;e:{if(ha(e)!==e||e.tag!==1)throw Error(xt(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(ci(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(xt(171))}if(e.tag===1){var r=e.type;if(ci(r))return Fb(e,r,t)}return t}function O2(e,t,r,o,a,l,p,_,h){return e=g0(r,o,!0,e,a,l,p,_,h),e.context=F2(null),r=e.current,o=ti(),a=bs(r),l=Ao(o,a),l.callback=t??null,ys(r,l,a),e.current.lanes=a,Yp(e,a,o),di(e,o),e}function dm(e,t,r,o){var a=t.current,l=ti(),p=bs(a);return r=F2(r),t.context===null?t.context=r:t.pendingContext=r,t=Ao(l,p),t.payload={element:e},o=o===void 0?null:o,o!==null&&(t.callback=o),e=ys(a,t,p),e!==null&&(Yi(e,a,p,l),wh(e,a,p)),p}function Xh(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 l1(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var r=e.retryLane;e.retryLane=r!==0&&r<t?r:t}}function _0(e,t){l1(e,t),(e=e.alternate)&&l1(e,t)}function sS(){return null}var z2=typeof reportError=="function"?reportError:function(e){console.error(e)};function w0(e){this._internalRoot=e}pm.prototype.render=w0.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(xt(409));dm(e,t,null,null)};pm.prototype.unmount=w0.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;pa(function(){dm(null,e,null,null)}),t[Fo]=null}};function pm(e){this._internalRoot=e}pm.prototype.unstable_scheduleHydration=function(e){if(e){var t=pb();e={blockedOn:null,target:e,priority:t};for(var r=0;r<ds.length&&t!==0&&t<ds[r].priority;r++);ds.splice(r,0,e),r===0&&hb(e)}};function y0(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function fm(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function u1(){}function aS(e,t,r,o,a){if(a){if(typeof o=="function"){var l=o;o=function(){var g=Xh(p);l.call(g)}}var p=O2(t,o,e,0,null,!1,!1,"",u1);return e._reactRootContainer=p,e[Fo]=p.current,Np(e.nodeType===8?e.parentNode:e),pa(),p}for(;a=e.lastChild;)e.removeChild(a);if(typeof o=="function"){var _=o;o=function(){var g=Xh(h);_.call(g)}}var h=g0(e,0,!1,null,null,!1,!1,"",u1);return e._reactRootContainer=h,e[Fo]=h.current,Np(e.nodeType===8?e.parentNode:e),pa(function(){dm(t,h,r,o)}),h}function hm(e,t,r,o,a){var l=r._reactRootContainer;if(l){var p=l;if(typeof a=="function"){var _=a;a=function(){var h=Xh(p);_.call(h)}}dm(t,p,e,a)}else p=aS(r,t,e,a,o);return Xh(p)}cb=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var r=vp(t.pendingLanes);r!==0&&(R_(t,r|1),di(t,mn()),!(zr&6)&&(iu=mn()+500,Es()))}break;case 13:pa(function(){var o=Oo(e,1);if(o!==null){var a=ti();Yi(o,e,1,a)}}),_0(e,1)}};B_=function(e){if(e.tag===13){var t=Oo(e,134217728);if(t!==null){var r=ti();Yi(t,e,134217728,r)}_0(e,134217728)}};db=function(e){if(e.tag===13){var t=bs(e),r=Oo(e,t);if(r!==null){var o=ti();Yi(r,e,t,o)}_0(e,t)}};pb=function(){return Ur};fb=function(e,t){var r=Ur;try{return Ur=e,t()}finally{Ur=r}};jg=function(e,t,r){switch(t){case"input":if(Og(e,r),t=r.name,r.type==="radio"&&t!=null){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<r.length;t++){var o=r[t];if(o!==e&&o.form===e.form){var a=im(o);if(!a)throw Error(xt(90));W1(o),Og(o,a)}}}break;case"textarea":H1(e,r);break;case"select":t=r.value,t!=null&&Hl(e,!!r.multiple,t,!1)}};J1=p0;eb=pa;var lS={usingClientEntryPoint:!1,Events:[Jp,Bl,im,Y1,Z1,p0]},_p={findFiberByHostInstance:na,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},uS={bundleType:_p.bundleType,version:_p.version,rendererPackageName:_p.rendererPackageName,rendererConfig:_p.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Do.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=nb(e),e===null?null:e.stateNode},findFiberByHostInstance:_p.findFiberByHostInstance||sS,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 ch=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!ch.isDisabled&&ch.supportsFiber)try{em=ch.inject(uS),co=ch}catch{}}bi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=lS;bi.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!y0(t))throw Error(xt(200));return oS(e,t,null,r)};bi.createRoot=function(e,t){if(!y0(e))throw Error(xt(299));var r=!1,o="",a=z2;return t!=null&&(t.unstable_strictMode===!0&&(r=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onRecoverableError!==void 0&&(a=t.onRecoverableError)),t=g0(e,1,!1,null,null,r,!1,o,a),e[Fo]=t.current,Np(e.nodeType===8?e.parentNode:e),new w0(t)};bi.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(xt(188)):(e=Object.keys(e).join(","),Error(xt(268,e)));return e=nb(t),e=e===null?null:e.stateNode,e};bi.flushSync=function(e){return pa(e)};bi.hydrate=function(e,t,r){if(!fm(t))throw Error(xt(200));return hm(null,e,t,!0,r)};bi.hydrateRoot=function(e,t,r){if(!y0(e))throw Error(xt(405));var o=r!=null&&r.hydratedSources||null,a=!1,l="",p=z2;if(r!=null&&(r.unstable_strictMode===!0&&(a=!0),r.identifierPrefix!==void 0&&(l=r.identifierPrefix),r.onRecoverableError!==void 0&&(p=r.onRecoverableError)),t=O2(t,null,e,1,r??null,a,!1,l,p),e[Fo]=t.current,Np(e),o)for(e=0;e<o.length;e++)r=o[e],a=r._getVersion,a=a(r._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[r,a]:t.mutableSourceEagerHydrationData.push(r,a);return new pm(t)};bi.render=function(e,t,r){if(!fm(t))throw Error(xt(200));return hm(null,e,t,!1,r)};bi.unmountComponentAtNode=function(e){if(!fm(e))throw Error(xt(40));return e._reactRootContainer?(pa(function(){hm(null,null,e,!1,function(){e._reactRootContainer=null,e[Fo]=null})}),!0):!1};bi.unstable_batchedUpdates=p0;bi.unstable_renderSubtreeIntoContainer=function(e,t,r,o){if(!fm(r))throw Error(xt(200));if(e==null||e._reactInternals===void 0)throw Error(xt(38));return hm(e,t,r,!1,o)};bi.version="18.3.1-next-f1338f8080-20240426";function D2(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(D2)}catch(e){console.error(e)}}D2(),D1.exports=bi;var cS=D1.exports,L2,c1=cS;L2=c1.createRoot,c1.hydrateRoot;var R2={exports:{}},dS="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",pS=dS,fS=pS;function B2(){}function N2(){}N2.resetWarningCache=B2;var hS=function(){function e(o,a,l,p,_,h){if(h!==fS){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 r={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:N2,resetWarningCache:B2};return r.PropTypes=r,r};R2.exports=hS();var mS=R2.exports;const qr=k_(mS);function lu(e,t,r,o){function a(l){return l instanceof r?l:new r(function(p){p(l)})}return new(r||(r=Promise))(function(l,p){function _(M){try{g(o.next(M))}catch(y){p(y)}}function h(M){try{g(o.throw(M))}catch(y){p(y)}}function g(M){M.done?l(M.value):a(M.value).then(_,h)}g((o=o.apply(e,t||[])).next())})}function uu(e,t){var r={label:0,sent:function(){if(l[0]&1)throw l[1];return l[1]},trys:[],ops:[]},o,a,l,p=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return p.next=_(0),p.throw=_(1),p.return=_(2),typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function _(g){return function(M){return h([g,M])}}function h(g){if(o)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(r=0)),r;)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 r.label++,{value:g[1],done:!1};case 5:r.label++,a=g[1],g=[0];continue;case 7:g=r.ops.pop(),r.trys.pop();continue;default:if(l=r.trys,!(l=l.length>0&&l[l.length-1])&&(g[0]===6||g[0]===2)){r=0;continue}if(g[0]===3&&(!l||g[1]>l[0]&&g[1]<l[3])){r.label=g[1];break}if(g[0]===6&&r.label<l[1]){r.label=l[1],l=g;break}if(l&&r.label<l[2]){r.label=l[2],r.ops.push(g);break}l[2]&&r.ops.pop(),r.trys.pop();continue}g=t.call(e,r)}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 d1(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),a,l=[],p;try{for(;(t===void 0||t-- >0)&&!(a=o.next()).done;)l.push(a.value)}catch(_){p={error:_}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(p)throw p.error}}return l}function p1(e,t,r){if(r||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 gS=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 tf(e,t){var r=_S(e);if(typeof r.path!="string"){var o=e.webkitRelativePath;Object.defineProperty(r,"path",{value:typeof t=="string"?t:typeof o=="string"&&o.length>0?o:e.name,writable:!1,configurable:!1,enumerable:!0})}return r}function _S(e){var t=e.name,r=t&&t.lastIndexOf(".")!==-1;if(r&&!e.type){var o=t.split(".").pop().toLowerCase(),a=gS.get(o);a&&Object.defineProperty(e,"type",{value:a,writable:!1,configurable:!1,enumerable:!0})}return e}var wS=[".DS_Store","Thumbs.db"];function yS(e){return lu(this,void 0,void 0,function(){return uu(this,function(t){return Qh(e)&&vS(e.dataTransfer)?[2,TS(e.dataTransfer,e.type)]:bS(e)?[2,xS(e)]:Array.isArray(e)&&e.every(function(r){return"getFile"in r&&typeof r.getFile=="function"})?[2,MS(e)]:[2,[]]})})}function vS(e){return Qh(e)}function bS(e){return Qh(e)&&Qh(e.target)}function Qh(e){return typeof e=="object"&&e!==null}function xS(e){return v_(e.target.files).map(function(t){return tf(t)})}function MS(e){return lu(this,void 0,void 0,function(){var t;return uu(this,function(r){switch(r.label){case 0:return[4,Promise.all(e.map(function(o){return o.getFile()}))];case 1:return t=r.sent(),[2,t.map(function(o){return tf(o)})]}})})}function TS(e,t){return lu(this,void 0,void 0,function(){var r,o;return uu(this,function(a){switch(a.label){case 0:return e.items?(r=v_(e.items).filter(function(l){return l.kind==="file"}),t!=="drop"?[2,r]:[4,Promise.all(r.map(kS))]):[3,2];case 1:return o=a.sent(),[2,f1(j2(o))];case 2:return[2,f1(v_(e.files).map(function(l){return tf(l)}))]}})})}function f1(e){return e.filter(function(t){return wS.indexOf(t.name)===-1})}function v_(e){if(e===null)return[];for(var t=[],r=0;r<e.length;r++){var o=e[r];t.push(o)}return t}function kS(e){if(typeof e.webkitGetAsEntry!="function")return h1(e);var t=e.webkitGetAsEntry();return t&&t.isDirectory?U2(t):h1(e)}function j2(e){return e.reduce(function(t,r){return p1(p1([],d1(t),!1),d1(Array.isArray(r)?j2(r):[r]),!1)},[])}function h1(e){var t=e.getAsFile();if(!t)return Promise.reject("".concat(e," is not a File"));var r=tf(t);return Promise.resolve(r)}function SS(e){return lu(this,void 0,void 0,function(){return uu(this,function(t){return[2,e.isDirectory?U2(e):ES(e)]})})}function U2(e){var t=e.createReader();return new Promise(function(r,o){var a=[];function l(){var p=this;t.readEntries(function(_){return lu(p,void 0,void 0,function(){var h,g,M;return uu(this,function(y){switch(y.label){case 0:if(_.length)return[3,5];y.label=1;case 1:return y.trys.push([1,3,,4]),[4,Promise.all(a)];case 2:return h=y.sent(),r(h),[3,4];case 3:return g=y.sent(),o(g),[3,4];case 4:return[3,6];case 5:M=Promise.all(_.map(SS)),a.push(M),l(),y.label=6;case 6:return[2]}})})},function(_){o(_)})}l()})}function ES(e){return lu(this,void 0,void 0,function(){return uu(this,function(t){return[2,new Promise(function(r,o){e.file(function(a){var l=tf(a,e.fullPath);r(l)},function(a){o(a)})})]})})}var CS=function(e,t){if(e&&t){var r=Array.isArray(t)?t:t.split(","),o=e.name||"",a=(e.type||"").toLowerCase(),l=a.replace(/\/.*$/,"");return r.some(function(p){var _=p.trim().toLowerCase();return _.charAt(0)==="."?o.toLowerCase().endsWith(_):_.endsWith("/*")?l===_.replace(/\/.*$/,""):a===_})}return!0};function m1(e){return AS(e)||$S(e)||W2(e)||PS()}function PS(){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 $S(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function AS(e){if(Array.isArray(e))return b_(e)}function g1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,o)}return r}function _1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?g1(Object(r),!0).forEach(function(o){V2(e,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):g1(Object(r)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(r,o))})}return e}function V2(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Xp(e,t){return OS(e)||FS(e,t)||W2(e,t)||IS()}function IS(){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 W2(e,t){if(e){if(typeof e=="string")return b_(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return b_(e,t)}}function b_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,o=new Array(t);r<t;r++)o[r]=e[r];return o}function FS(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var o=[],a=!0,l=!1,p,_;try{for(r=r.call(e);!(a=(p=r.next()).done)&&(o.push(p.value),!(t&&o.length===t));a=!0);}catch(h){l=!0,_=h}finally{try{!a&&r.return!=null&&r.return()}finally{if(l)throw _}}return o}}function OS(e){if(Array.isArray(e))return e}var zS="file-invalid-type",DS="file-too-large",LS="file-too-small",RS="too-many-files",BS=function(t){t=Array.isArray(t)&&t.length===1?t[0]:t;var r=Array.isArray(t)?"one of ".concat(t.join(", ")):t;return{code:zS,message:"File type must be ".concat(r)}},w1=function(t){return{code:DS,message:"File is larger than ".concat(t," ").concat(t===1?"byte":"bytes")}},y1=function(t){return{code:LS,message:"File is smaller than ".concat(t," ").concat(t===1?"byte":"bytes")}},NS={code:RS,message:"Too many files"};function G2(e,t){var r=e.type==="application/x-moz-file"||CS(e,t);return[r,r?null:BS(t)]}function H2(e,t,r){if(ra(e.size))if(ra(t)&&ra(r)){if(e.size>r)return[!1,w1(r)];if(e.size<t)return[!1,y1(t)]}else{if(ra(t)&&e.size<t)return[!1,y1(t)];if(ra(r)&&e.size>r)return[!1,w1(r)]}return[!0,null]}function ra(e){return e!=null}function jS(e){var t=e.files,r=e.accept,o=e.minSize,a=e.maxSize,l=e.multiple,p=e.maxFiles,_=e.validator;return!l&&t.length>1||l&&p>=1&&t.length>p?!1:t.every(function(h){var g=G2(h,r),M=Xp(g,1),y=M[0],E=H2(h,o,a),T=Xp(E,1),O=T[0],S=_?_(h):null;return y&&O&&!S})}function Yh(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function dh(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 v1(e){e.preventDefault()}function US(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function VS(e){return e.indexOf("Edge/")!==-1}function WS(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return US(e)||VS(e)}function ao(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(o){for(var a=arguments.length,l=new Array(a>1?a-1:0),p=1;p<a;p++)l[p-1]=arguments[p];return t.some(function(_){return!Yh(o)&&_&&_.apply(void 0,[o].concat(l)),Yh(o)})}}function GS(){return"showOpenFilePicker"in window}function HS(e){if(ra(e)){var t=Object.entries(e).filter(function(r){var o=Xp(r,2),a=o[0],l=o[1],p=!0;return q2(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.')),p=!1),(!Array.isArray(l)||!l.every(K2))&&(console.warn('Skipped "'.concat(a,'" because an invalid file extension was provided.')),p=!1),p}).reduce(function(r,o){var a=Xp(o,2),l=a[0],p=a[1];return _1(_1({},r),{},V2({},l,p))},{});return[{description:"Files",accept:t}]}return e}function qS(e){if(ra(e))return Object.entries(e).reduce(function(t,r){var o=Xp(r,2),a=o[0],l=o[1];return[].concat(m1(t),[a],m1(l))},[]).filter(function(t){return q2(t)||K2(t)}).join(",")}function KS(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function XS(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function q2(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||/\w+\/[-+.\w]+/g.test(e)}function K2(e){return/^.*\.[\w]+$/.test(e)}var QS=["children"],YS=["open"],ZS=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],JS=["refKey","onChange","onClick"];function eE(e){return nE(e)||rE(e)||X2(e)||tE()}function tE(){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 rE(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function nE(e){if(Array.isArray(e))return x_(e)}function Eg(e,t){return sE(e)||oE(e,t)||X2(e,t)||iE()}function iE(){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 X2(e,t){if(e){if(typeof e=="string")return x_(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return x_(e,t)}}function x_(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,o=new Array(t);r<t;r++)o[r]=e[r];return o}function oE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var o=[],a=!0,l=!1,p,_;try{for(r=r.call(e);!(a=(p=r.next()).done)&&(o.push(p.value),!(t&&o.length===t));a=!0);}catch(h){l=!0,_=h}finally{try{!a&&r.return!=null&&r.return()}finally{if(l)throw _}}return o}}function sE(e){if(Array.isArray(e))return e}function b1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,o)}return r}function on(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?b1(Object(r),!0).forEach(function(o){M_(e,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):b1(Object(r)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(r,o))})}return e}function M_(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Zh(e,t){if(e==null)return{};var r=aE(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)&&(r[o]=e[o])}return r}function aE(e,t){if(e==null)return{};var r={},o=Object.keys(e),a,l;for(l=0;l<o.length;l++)a=o[l],!(t.indexOf(a)>=0)&&(r[a]=e[a]);return r}var v0=fr.forwardRef(function(e,t){var r=e.children,o=Zh(e,QS),a=Y2(o),l=a.open,p=Zh(a,YS);return fr.useImperativeHandle(t,function(){return{open:l}},[l]),JM.createElement(fr.Fragment,null,r(on(on({},p),{},{open:l})))});v0.displayName="Dropzone";var Q2={disabled:!1,getFilesFromEvent:yS,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};v0.defaultProps=Q2;v0.propTypes={children:qr.func,accept:qr.objectOf(qr.arrayOf(qr.string)),multiple:qr.bool,preventDropOnDocument:qr.bool,noClick:qr.bool,noKeyboard:qr.bool,noDrag:qr.bool,noDragEventsBubbling:qr.bool,minSize:qr.number,maxSize:qr.number,maxFiles:qr.number,disabled:qr.bool,getFilesFromEvent:qr.func,onFileDialogCancel:qr.func,onFileDialogOpen:qr.func,useFsAccessApi:qr.bool,autoFocus:qr.bool,onDragEnter:qr.func,onDragLeave:qr.func,onDragOver:qr.func,onDrop:qr.func,onDropAccepted:qr.func,onDropRejected:qr.func,onError:qr.func,validator:qr.func};var T_={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function Y2(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=on(on({},Q2),e),r=t.accept,o=t.disabled,a=t.getFilesFromEvent,l=t.maxSize,p=t.minSize,_=t.multiple,h=t.maxFiles,g=t.onDragEnter,M=t.onDragLeave,y=t.onDragOver,E=t.onDrop,T=t.onDropAccepted,O=t.onDropRejected,S=t.onFileDialogCancel,C=t.onFileDialogOpen,w=t.useFsAccessApi,b=t.autoFocus,I=t.preventDropOnDocument,U=t.noClick,z=t.noKeyboard,B=t.noDrag,j=t.noDragEventsBubbling,N=t.onError,ae=t.validator,ce=fr.useMemo(function(){return qS(r)},[r]),xe=fr.useMemo(function(){return HS(r)},[r]),Y=fr.useMemo(function(){return typeof C=="function"?C:x1},[C]),_e=fr.useMemo(function(){return typeof S=="function"?S:x1},[S]),L=fr.useRef(null),Se=fr.useRef(null),Xe=fr.useReducer(lE,T_),me=Eg(Xe,2),X=me[0],ie=me[1],Me=X.isFocused,Q=X.isFileDialogActive,ge=fr.useRef(typeof window<"u"&&window.isSecureContext&&w&&GS()),Ke=function(){!ge.current&&Q&&setTimeout(function(){if(Se.current){var ke=Se.current.files;ke.length||(ie({type:"closeDialog"}),_e())}},300)};fr.useEffect(function(){return window.addEventListener("focus",Ke,!1),function(){window.removeEventListener("focus",Ke,!1)}},[Se,Q,_e,ge]);var Le=fr.useRef([]),Be=function(ke){L.current&&L.current.contains(ke.target)||(ke.preventDefault(),Le.current=[])};fr.useEffect(function(){return I&&(document.addEventListener("dragover",v1,!1),document.addEventListener("drop",Be,!1)),function(){I&&(document.removeEventListener("dragover",v1),document.removeEventListener("drop",Be))}},[L,I]),fr.useEffect(function(){return!o&&b&&L.current&&L.current.focus(),function(){}},[L,b,o]);var We=fr.useCallback(function(le){N?N(le):console.error(le)},[N]),st=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le),Le.current=[].concat(eE(Le.current),[le.target]),dh(le)&&Promise.resolve(a(le)).then(function(ke){if(!(Yh(le)&&!j)){var Ne=ke.length,dt=Ne>0&&jS({files:ke,accept:ce,minSize:p,maxSize:l,multiple:_,maxFiles:h,validator:ae}),Je=Ne>0&&!dt;ie({isDragAccept:dt,isDragReject:Je,isDragActive:!0,type:"setDraggedFiles"}),g&&g(le)}}).catch(function(ke){return We(ke)})},[a,g,We,j,ce,p,l,_,h,ae]),pt=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le);var ke=dh(le);if(ke&&le.dataTransfer)try{le.dataTransfer.dropEffect="copy"}catch{}return ke&&y&&y(le),!1},[y,j]),Ge=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le);var ke=Le.current.filter(function(dt){return L.current&&L.current.contains(dt)}),Ne=ke.indexOf(le.target);Ne!==-1&&ke.splice(Ne,1),Le.current=ke,!(ke.length>0)&&(ie({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),dh(le)&&M&&M(le))},[L,M,j]),Te=fr.useCallback(function(le,ke){var Ne=[],dt=[];le.forEach(function(Je){var Ve=G2(Je,ce),Z=Eg(Ve,2),ve=Z[0],Re=Z[1],qe=H2(Je,p,l),Qe=Eg(qe,2),tt=Qe[0],ft=Qe[1],ht=ae?ae(Je):null;if(ve&&tt&&!ht)Ne.push(Je);else{var Tt=[Re,ft];ht&&(Tt=Tt.concat(ht)),dt.push({file:Je,errors:Tt.filter(function(bt){return bt})})}}),(!_&&Ne.length>1||_&&h>=1&&Ne.length>h)&&(Ne.forEach(function(Je){dt.push({file:Je,errors:[NS]})}),Ne.splice(0)),ie({acceptedFiles:Ne,fileRejections:dt,type:"setFiles"}),E&&E(Ne,dt,ke),dt.length>0&&O&&O(dt,ke),Ne.length>0&&T&&T(Ne,ke)},[ie,_,ce,p,l,h,E,T,O,ae]),je=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le),Le.current=[],dh(le)&&Promise.resolve(a(le)).then(function(ke){Yh(le)&&!j||Te(ke,le)}).catch(function(ke){return We(ke)}),ie({type:"reset"})},[a,Te,We,j]),Ye=fr.useCallback(function(){if(ge.current){ie({type:"openDialog"}),Y();var le={multiple:_,types:xe};window.showOpenFilePicker(le).then(function(ke){return a(ke)}).then(function(ke){Te(ke,null),ie({type:"closeDialog"})}).catch(function(ke){KS(ke)?(_e(ke),ie({type:"closeDialog"})):XS(ke)?(ge.current=!1,Se.current?(Se.current.value=null,Se.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}Se.current&&(ie({type:"openDialog"}),Y(),Se.current.value=null,Se.current.click())},[ie,Y,_e,w,Te,We,xe,_]),et=fr.useCallback(function(le){!L.current||!L.current.isEqualNode(le.target)||(le.key===" "||le.key==="Enter"||le.keyCode===32||le.keyCode===13)&&(le.preventDefault(),Ye())},[L,Ye]),A=fr.useCallback(function(){ie({type:"focus"})},[]),$e=fr.useCallback(function(){ie({type:"blur"})},[]),Pe=fr.useCallback(function(){U||(WS()?setTimeout(Ye,0):Ye())},[U,Ye]),se=function(ke){return o?null:ke},re=function(ke){return z?null:se(ke)},ye=function(ke){return B?null:se(ke)},R=function(ke){j&&ke.stopPropagation()},ee=fr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,dt=le.role,Je=le.onKeyDown,Ve=le.onFocus,Z=le.onBlur,ve=le.onClick,Re=le.onDragEnter,qe=le.onDragOver,Qe=le.onDragLeave,tt=le.onDrop,ft=Zh(le,ZS);return on(on(M_({onKeyDown:re(ao(Je,et)),onFocus:re(ao(Ve,A)),onBlur:re(ao(Z,$e)),onClick:se(ao(ve,Pe)),onDragEnter:ye(ao(Re,st)),onDragOver:ye(ao(qe,pt)),onDragLeave:ye(ao(Qe,Ge)),onDrop:ye(ao(tt,je)),role:typeof dt=="string"&&dt!==""?dt:"presentation"},Ne,L),!o&&!z?{tabIndex:0}:{}),ft)}},[L,et,A,$e,Pe,st,pt,Ge,je,z,B,o]),D=fr.useCallback(function(le){le.stopPropagation()},[]),ue=fr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,dt=le.onChange,Je=le.onClick,Ve=Zh(le,JS),Z=M_({accept:ce,multiple:_,type:"file",style:{display:"none"},onChange:se(ao(dt,je)),onClick:se(ao(Je,D)),tabIndex:-1},Ne,Se);return on(on({},Z),Ve)}},[Se,r,_,je,o]);return on(on({},X),{},{isFocused:Me&&!o,getRootProps:ee,getInputProps:ue,rootRef:L,inputRef:Se,open:se(Ye)})}function lE(e,t){switch(t.type){case"focus":return on(on({},e),{},{isFocused:!0});case"blur":return on(on({},e),{},{isFocused:!1});case"openDialog":return on(on({},T_),{},{isFileDialogActive:!0});case"closeDialog":return on(on({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return on(on({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return on(on({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return on({},T_);default:return e}}function x1(){}var ko={},uE={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(e,t,r)=>{e.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,t,r)=>{r.r(t),r.d(t,{Environment:()=>$e,Interpreter:()=>Pe,Template:()=>ye,parse:()=>Me,tokenize:()=>y});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(R,ee){this.value=R,this.type=ee}};function p(R){return/\w/.test(R)}function _(R){return/[0-9]/.test(R)}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(R,ee={}){return R.endsWith(` `)&&(R=R.slice(0,-1)),R=R.replace(/{#.*?#}/gs,"{##}"),ee.lstrip_blocks&&(R=R.replace(/^[ \t]*({[#%])/gm,"$1")),ee.trim_blocks&&(R=R.replace(/([#%]})\n/g,"$1")),R.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function y(R,ee={}){var Ne,dt,Je;const D=[],ue=M(R,ee);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=D.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){D.push(new l(ve,o.Text));continue}}ke(ve=>/\s/.test(ve));const Z=ue[le];if(Z==="-"||Z==="+"){const ve=(dt=D.at(-1))==null?void 0:dt.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(_);D.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){D.push(new l(ve,Re)),le+=ve.length;continue e}if(Z==="'"||Z==='"'){++le;const ve=ke(Re=>Re!==Z);D.push(new l(ve,o.StringLiteral)),++le;continue}if(_(Z)){const ve=ke(_);D.push(new l(ve,o.NumericLiteral));continue}if(p(Z)){const ve=ke(p),Re=Object.hasOwn(a,ve)?a[ve]:o.Identifier;Re===o.In&&((Je=D.at(-1))==null?void 0:Je.type)===o.Not?(D.pop(),D.push(new l("not in",o.NotIn))):D.push(new l(ve,Re));continue}throw new SyntaxError(`Unexpected character: ${Z}`)}return D}var E=class{constructor(){He(this,"type","Statement")}},T=class extends E{constructor(ee){super();He(this,"type","Program");this.body=ee}},O=class extends E{constructor(ee,D,ue){super();He(this,"type","If");this.test=ee,this.body=D,this.alternate=ue}},S=class extends E{constructor(ee,D,ue,le){super();He(this,"type","For");this.loopvar=ee,this.iterable=D,this.body=ue,this.defaultBlock=le}},C=class extends E{constructor(ee,D){super();He(this,"type","Set");this.assignee=ee,this.value=D}},w=class extends E{constructor(ee,D,ue){super();He(this,"type","Macro");this.name=ee,this.args=D,this.body=ue}},b=class extends E{constructor(){super(...arguments);He(this,"type","Expression")}},I=class extends b{constructor(ee,D,ue){super();He(this,"type","MemberExpression");this.object=ee,this.property=D,this.computed=ue}},U=class extends b{constructor(ee,D){super();He(this,"type","CallExpression");this.callee=ee,this.args=D}},z=class extends b{constructor(ee){super();He(this,"type","Identifier");this.value=ee}},B=class extends b{constructor(ee){super();He(this,"type","Literal");this.value=ee}},j=class extends B{constructor(){super(...arguments);He(this,"type","NumericLiteral")}},N=class extends B{constructor(){super(...arguments);He(this,"type","StringLiteral")}},ae=class extends B{constructor(){super(...arguments);He(this,"type","BooleanLiteral")}},ce=class extends B{constructor(){super(...arguments);He(this,"type","ArrayLiteral")}},xe=class extends B{constructor(){super(...arguments);He(this,"type","TupleLiteral")}},Y=class extends B{constructor(){super(...arguments);He(this,"type","ObjectLiteral")}},_e=class extends b{constructor(ee,D,ue){super();He(this,"type","BinaryExpression");this.operator=ee,this.left=D,this.right=ue}},L=class extends b{constructor(ee,D){super();He(this,"type","FilterExpression");this.operand=ee,this.filter=D}},Se=class extends b{constructor(ee,D){super();He(this,"type","SelectExpression");this.iterable=ee,this.test=D}},Xe=class extends b{constructor(ee,D,ue){super();He(this,"type","TestExpression");this.operand=ee,this.negate=D,this.test=ue}},me=class extends b{constructor(ee,D){super();He(this,"type","UnaryExpression");this.operator=ee,this.argument=D}},X=class extends b{constructor(ee=void 0,D=void 0,ue=void 0){super();He(this,"type","SliceExpression");this.start=ee,this.stop=D,this.step=ue}},ie=class extends b{constructor(ee,D){super();He(this,"type","KeywordArgumentExpression");this.key=ee,this.value=D}};function Me(R){const ee=new T([]);let D=0;function ue(mt,$t){const Bt=R[D++];if(!Bt||Bt.type!==mt)throw new Error(`Parser Error: ${$t}. ${Bt.type} !== ${mt}.`);return Bt}function le(){switch(R[D].type){case o.Text:return dt();case o.OpenStatement:return Je();case o.OpenExpression:return Ve();default:throw new SyntaxError(`Unexpected token type: ${R[D].type}`)}}function ke(...mt){return D+mt.length<=R.length&&mt.some(($t,Bt)=>$t!==R[D+Bt].type)}function Ne(...mt){return D+mt.length<=R.length&&mt.every(($t,Bt)=>$t===R[D+Bt].type)}function dt(){return new N(ue(o.Text,"Expected text token").value)}function Je(){ue(o.OpenStatement,"Expected opening statement token");let mt;switch(R[D].type){case o.Set:++D,mt=Z(),ue(o.CloseStatement,"Expected closing statement token");break;case o.If:++D,mt=ve(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndIf,"Expected endif token"),ue(o.CloseStatement,"Expected %} token");break;case o.Macro:++D,mt=Re(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndMacro,"Expected endmacro token"),ue(o.CloseStatement,"Expected %} token");break;case o.For:++D,mt=Qe(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndFor,"Expected endfor token"),ue(o.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${R[D].type}`)}return mt}function Ve(){ue(o.OpenExpression,"Expected opening expression token");const mt=tt();return ue(o.CloseExpression,"Expected closing expression token"),mt}function Z(){const mt=tt();if(Ne(o.Equals)){++D;const $t=Z();return new C(mt,$t)}return mt}function ve(){var un,Bi,Mi,Gr,wn,Kr,pi,Dr;const mt=tt();ue(o.CloseStatement,"Expected closing statement token");const $t=[],Bt=[];for(;!(((un=R[D])==null?void 0:un.type)===o.OpenStatement&&(((Bi=R[D+1])==null?void 0:Bi.type)===o.ElseIf||((Mi=R[D+1])==null?void 0:Mi.type)===o.Else||((Gr=R[D+1])==null?void 0:Gr.type)===o.EndIf));)$t.push(le());if(((wn=R[D])==null?void 0:wn.type)===o.OpenStatement&&((Kr=R[D+1])==null?void 0:Kr.type)!==o.EndIf)if(++D,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");!(((pi=R[D])==null?void 0:pi.type)===o.OpenStatement&&((Dr=R[D+1])==null?void 0:Dr.type)===o.EndIf);)Bt.push(le());return new O(mt,$t,Bt)}function Re(){const mt=$r();if(mt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const $t=Ut();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndMacro);)Bt.push(le());return new w(mt,$t,Bt)}function qe(mt=!1){const $t=mt?$r:tt,Bt=[$t()],un=Ne(o.Comma);for(;un&&(++D,Bt.push($t()),!!Ne(o.Comma)););return un?new xe(Bt):Bt[0]}function Qe(){const mt=qe(!0);if(!(mt instanceof z||mt instanceof xe))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${mt.type} instead`);ue(o.In,"Expected `in` keyword following loop variable");const $t=tt();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndFor)&&ke(o.OpenStatement,o.Else);)Bt.push(le());const un=[];if(Ne(o.OpenStatement,o.Else))for(++D,++D,ue(o.CloseStatement,"Expected closing statement token");ke(o.OpenStatement,o.EndFor);)un.push(le());return new S(mt,$t,Bt,un)}function tt(){return ft()}function ft(){const mt=ht();if(Ne(o.If)){++D;const $t=ht();if(Ne(o.Else)){++D;const Bt=ht();return new O($t,[mt],[Bt])}else return new Se(mt,$t)}return mt}function ht(){let mt=Tt();for(;Ne(o.Or);){const $t=R[D];++D;const Bt=Tt();mt=new _e($t,mt,Bt)}return mt}function Tt(){let mt=bt();for(;Ne(o.And);){const $t=R[D];++D;const Bt=bt();mt=new _e($t,mt,Bt)}return mt}function bt(){let mt;for(;Ne(o.Not);){const $t=R[D];++D;const Bt=bt();mt=new me($t,Bt)}return mt??Et()}function Et(){let mt=Lt();for(;Ne(o.ComparisonBinaryOperator)||Ne(o.In)||Ne(o.NotIn);){const $t=R[D];++D;const Bt=Lt();mt=new _e($t,mt,Bt)}return mt}function Lt(){let mt=Ht();for(;Ne(o.AdditiveBinaryOperator);){const $t=R[D];++D;const Bt=Ht();mt=new _e($t,mt,Bt)}return mt}function at(){const mt=rr();return Ne(o.OpenParen)?Ot(mt):mt}function Ot(mt){let $t=new U(mt,Ut());return Ne(o.OpenParen)&&($t=Ot($t)),$t}function Ut(){ue(o.OpenParen,"Expected opening parenthesis for arguments list");const mt=Xt();return ue(o.CloseParen,"Expected closing parenthesis for arguments list"),mt}function Xt(){const mt=[];for(;!Ne(o.CloseParen);){let $t=tt();if(Ne(o.Equals)){if(++D,!($t instanceof z))throw new SyntaxError("Expected identifier for keyword argument");const Bt=tt();$t=new ie($t,Bt)}mt.push($t),Ne(o.Comma)&&++D}return mt}function Yt(){const mt=[];let $t=!1;for(;!Ne(o.CloseSquareBracket);)Ne(o.Colon)?(mt.push(void 0),++D,$t=!0):(mt.push(tt()),Ne(o.Colon)&&(++D,$t=!0));if(mt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($t){if(mt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new X(...mt)}return mt[0]}function rr(){let mt=$r();for(;Ne(o.Dot)||Ne(o.OpenSquareBracket);){const $t=R[D];++D;let Bt;const un=$t.type!==o.Dot;if(un)Bt=Yt(),ue(o.CloseSquareBracket,"Expected closing square bracket");else if(Bt=$r(),Bt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");mt=new I(mt,Bt,un)}return mt}function Ht(){let mt=Pr();for(;Ne(o.MultiplicativeBinaryOperator);){const $t=R[D];++D;const Bt=Pr();mt=new _e($t,mt,Bt)}return mt}function Pr(){let mt=Yr();for(;Ne(o.Is);){++D;const $t=Ne(o.Not);$t&&++D;let Bt=$r();if(Bt instanceof ae&&(Bt=new z(Bt.value.toString())),!(Bt instanceof z))throw new SyntaxError("Expected identifier for the test");mt=new Xe(mt,$t,Bt)}return mt}function Yr(){let mt=at();for(;Ne(o.Pipe);){++D;let $t=$r();if(!($t instanceof z))throw new SyntaxError("Expected identifier for the filter");Ne(o.OpenParen)&&($t=Ot($t)),mt=new L(mt,$t)}return mt}function $r(){const mt=R[D];switch(mt.type){case o.NumericLiteral:return++D,new j(Number(mt.value));case o.StringLiteral:return++D,new N(mt.value);case o.BooleanLiteral:return++D,new ae(mt.value.toLowerCase()==="true");case o.Identifier:return++D,new z(mt.value);case o.OpenParen:{++D;const $t=qe();if(R[D].type!==o.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${R[D].type} instead`);return++D,$t}case o.OpenSquareBracket:{++D;const $t=[];for(;!Ne(o.CloseSquareBracket);)$t.push(tt()),Ne(o.Comma)&&++D;return++D,new ce($t)}case o.OpenCurlyBracket:{++D;const $t=new Map;for(;!Ne(o.CloseCurlyBracket);){const Bt=tt();ue(o.Colon,"Expected colon between key and value in object literal");const un=tt();$t.set(Bt,un),Ne(o.Comma)&&++D}return++D,new Y($t)}default:throw new SyntaxError(`Unexpected token: ${mt.type}`)}}for(;D<R.length;)ee.body.push(le());return ee}function Q(R,ee,D=1){ee===void 0&&(ee=R,R=0);const ue=[];for(let le=R;le<ee;le+=D)ue.push(le);return ue}function ge(R,ee,D,ue=1){const le=Math.sign(ue);le>=0?(ee=(ee??(ee=0))<0?Math.max(R.length+ee,0):Math.min(ee,R.length),D=(D??(D=R.length))<0?Math.max(R.length+D,0):Math.min(D,R.length)):(ee=(ee??(ee=R.length-1))<0?Math.max(R.length+ee,-1):Math.min(ee,R.length-1),D=(D??(D=-1))<-1?Math.max(R.length+D,-1):Math.min(D,R.length-1));const ke=[];for(let Ne=ee;le*Ne<le*D;Ne+=ue)ke.push(R[Ne]);return ke}function Ke(R){return R.replace(/\b\w/g,ee=>ee.toUpperCase())}var Le=class{constructor(R=void 0){He(this,"type","RuntimeValue");He(this,"value");He(this,"builtins",new Map);this.value=R}__bool__(){return new st(!!this.value)}},Be=class extends Le{constructor(){super(...arguments);He(this,"type","NumericValue")}},We=class extends Le{constructor(){super(...arguments);He(this,"type","StringValue");He(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)]]))}},st=class extends Le{constructor(){super(...arguments);He(this,"type","BooleanValue")}},pt=class extends Le{constructor(){super(...arguments);He(this,"type","ObjectValue");He(this,"builtins",new Map([["get",new Ye(([ee,D])=>{if(!(ee instanceof We))throw new Error(`Object key must be a string: got ${ee.type}`);return this.value.get(ee.value)??D??new et})],["items",new Ye(()=>new Te(Array.from(this.value.entries()).map(([ee,D])=>new Te([new We(ee),D]))))]]))}__bool__(){return new st(this.value.size>0)}},Ge=class extends pt{constructor(){super(...arguments);He(this,"type","KeywordArgumentsValue")}},Te=class extends Le{constructor(){super(...arguments);He(this,"type","ArrayValue");He(this,"builtins",new Map([["length",new Be(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},je=class extends Te{constructor(){super(...arguments);He(this,"type","TupleValue")}},Ye=class extends Le{constructor(){super(...arguments);He(this,"type","FunctionValue")}},et=class extends Le{constructor(){super(...arguments);He(this,"type","NullValue")}},A=class extends Le{constructor(){super(...arguments);He(this,"type","UndefinedValue")}},$e=class{constructor(R){He(this,"variables",new Map([["namespace",new Ye(R=>{if(R.length===0)return new pt(new Map);if(R.length!==1||!(R[0]instanceof pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return R[0]})]]));He(this,"tests",new Map([["boolean",R=>R.type==="BooleanValue"],["callable",R=>R instanceof Ye],["odd",R=>{if(R.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${R.type}`);return R.value%2!==0}],["even",R=>{if(R.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${R.type}`);return R.value%2===0}],["false",R=>R.type==="BooleanValue"&&!R.value],["true",R=>R.type==="BooleanValue"&&R.value],["string",R=>R.type==="StringValue"],["number",R=>R.type==="NumericValue"],["integer",R=>R.type==="NumericValue"&&Number.isInteger(R.value)],["iterable",R=>R instanceof Te||R instanceof We],["lower",R=>{const ee=R.value;return R.type==="StringValue"&&ee===ee.toLowerCase()}],["upper",R=>{const ee=R.value;return R.type==="StringValue"&&ee===ee.toUpperCase()}],["none",R=>R.type==="NullValue"],["defined",R=>R.type!=="UndefinedValue"],["undefined",R=>R.type==="UndefinedValue"],["equalto",(R,ee)=>R.value===ee.value],["eq",(R,ee)=>R.value===ee.value]]));this.parent=R}set(R,ee){return this.declareVariable(R,se(ee))}declareVariable(R,ee){if(this.variables.has(R))throw new SyntaxError(`Variable already declared: ${R}`);return this.variables.set(R,ee),ee}setVariable(R,ee){return this.variables.set(R,ee),ee}resolve(R){if(this.variables.has(R))return this;if(this.parent)return this.parent.resolve(R);throw new Error(`Unknown variable: ${R}`)}lookupVariable(R){try{return this.resolve(R).variables.get(R)??new A}catch{return new A}}},Pe=class{constructor(R){He(this,"global");this.global=R??new $e}run(R){return this.evaluate(R,this.global)}evaluateBinaryExpression(R,ee){const D=this.evaluate(R.left,ee);switch(R.operator.value){case"and":return D.__bool__().value?this.evaluate(R.right,ee):D;case"or":return D.__bool__().value?D:this.evaluate(R.right,ee)}const ue=this.evaluate(R.right,ee);switch(R.operator.value){case"==":return new st(D.value==ue.value);case"!=":return new st(D.value!=ue.value)}if(D instanceof A||ue instanceof A)throw new Error("Cannot perform operation on undefined values");if(D instanceof et||ue instanceof et)throw new Error("Cannot perform operation on null values");if(D instanceof Be&&ue instanceof Be)switch(R.operator.value){case"+":return new Be(D.value+ue.value);case"-":return new Be(D.value-ue.value);case"*":return new Be(D.value*ue.value);case"/":return new Be(D.value/ue.value);case"%":return new Be(D.value%ue.value);case"<":return new st(D.value<ue.value);case">":return new st(D.value>ue.value);case">=":return new st(D.value>=ue.value);case"<=":return new st(D.value<=ue.value)}else if(D instanceof Te&&ue instanceof Te)switch(R.operator.value){case"+":return new Te(D.value.concat(ue.value))}else if(ue instanceof Te){const le=ue.value.find(ke=>ke.value===D.value)!==void 0;switch(R.operator.value){case"in":return new st(le);case"not in":return new st(!le)}}if(D instanceof We||ue instanceof We)switch(R.operator.value){case"+":return new We(D.value.toString()+ue.value.toString())}if(D instanceof We&&ue instanceof We)switch(R.operator.value){case"in":return new st(ue.value.includes(D.value));case"not in":return new st(!ue.value.includes(D.value))}if(D instanceof We&&ue instanceof pt)switch(R.operator.value){case"in":return new st(ue.value.has(D.value));case"not in":return new st(!ue.value.has(D.value))}throw new SyntaxError(`Unknown operator "${R.operator.value}" between ${D.type} and ${ue.type}`)}evaluateArguments(R,ee){const D=[],ue=new Map;for(const le of R)if(le.type==="KeywordArgumentExpression"){const ke=le;ue.set(ke.key.value,this.evaluate(ke.value,ee))}else{if(ue.size>0)throw new Error("Positional arguments must come before keyword arguments");D.push(this.evaluate(le,ee))}return[D,ue]}evaluateFilterExpression(R,ee){const D=this.evaluate(R.operand,ee);if(R.filter.type==="Identifier"){const ue=R.filter;if(ue.value==="tojson")return new We(re(D));if(D instanceof Te)switch(ue.value){case"list":return D;case"first":return D.value[0];case"last":return D.value[D.value.length-1];case"length":return new Be(D.value.length);case"reverse":return new Te(D.value.reverse());case"sort":return new Te(D.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(D instanceof We)switch(ue.value){case"length":return new Be(D.value.length);case"upper":return new We(D.value.toUpperCase());case"lower":return new We(D.value.toLowerCase());case"title":return new We(Ke(D.value));case"capitalize":return new We(D.value.charAt(0).toUpperCase()+D.value.slice(1));case"trim":return new We(D.value.trim());case"indent":return new We(D.value.split(` `).map((le,ke)=>ke===0||le.length===0?le:" "+le).join(` `));case"string":return D;default:throw new Error(`Unknown StringValue filter: ${ue.value}`)}else if(D instanceof Be)switch(ue.value){case"abs":return new Be(Math.abs(D.value));default:throw new Error(`Unknown NumericValue filter: ${ue.value}`)}else if(D instanceof pt)switch(ue.value){case"items":return new Te(Array.from(D.value.entries()).map(([le,ke])=>new Te([new We(le),ke])));case"length":return new Be(D.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ue.value}`)}throw new Error(`Cannot apply filter "${ue.value}" to type: ${D.type}`)}else if(R.filter.type==="CallExpression"){const ue=R.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,ee),Ne=ke.get("indent")??new et;if(!(Ne instanceof Be||Ne instanceof et))throw new Error("If set, indent must be a number");return new We(re(D,Ne.value))}if(D instanceof Te){switch(le){case"selectattr":{if(D.value.some(Z=>!(Z instanceof pt)))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,dt]=ue.args.map(Z=>this.evaluate(Z,ee));let Je;if(Ne){const Z=ee.tests.get(Ne.value);if(!Z)throw new Error(`Unknown test: ${Ne.value}`);Je=Z}else Je=(...Z)=>Z[0].__bool__().value;const Ve=D.value.filter(Z=>{const ve=Z.value.get(ke.value);return ve?Je(ve,dt):!1});return new Te(Ve)}case"map":{const[,ke]=this.evaluateArguments(ue.args,ee);if(ke.has("attribute")){const Ne=ke.get("attribute");if(!(Ne instanceof We))throw new Error("attribute must be a string");const dt=ke.get("default"),Je=D.value.map(Ve=>{if(!(Ve instanceof pt))throw new Error("items in map must be an object");return Ve.value.get(Ne.value)??dt??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(D instanceof We){switch(le){case"indent":{const[ke,Ne]=this.evaluateArguments(ue.args,ee),dt=ke.at(0)??Ne.get("width")??new Be(4);if(!(dt instanceof Be))throw new Error("width must be a number");const Je=ke.at(1)??Ne.get("first")??new st(!1),Ve=ke.at(2)??Ne.get("blank")??new st(!1),Z=D.value.split(` `),ve=" ".repeat(dt.value),Re=Z.map((qe,Qe)=>!Je.value&&Qe===0||!Ve.value&&qe.length===0?qe:ve+qe);return new We(Re.join(` `))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${D.type}`)}throw new Error(`Unknown filter: ${R.filter.type}`)}evaluateTestExpression(R,ee){const D=this.evaluate(R.operand,ee),ue=ee.tests.get(R.test.value);if(!ue)throw new Error(`Unknown test: ${R.test.value}`);const le=ue(D);return new st(R.negate?!le:le)}evaluateUnaryExpression(R,ee){const D=this.evaluate(R.argument,ee);switch(R.operator.value){case"not":return new st(!D.value);default:throw new SyntaxError(`Unknown operator: ${R.operator.value}`)}}evalProgram(R,ee){return this.evaluateBlock(R.body,ee)}evaluateBlock(R,ee){let D="";for(const ue of R){const le=this.evaluate(ue,ee);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(D+=le.value)}return new We(D)}evaluateIdentifier(R,ee){return ee.lookupVariable(R.value)}evaluateCallExpression(R,ee){const[D,ue]=this.evaluateArguments(R.args,ee);ue.size>0&&D.push(new Ge(ue));const le=this.evaluate(R.callee,ee);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(D,ee)}evaluateSliceExpression(R,ee,D){if(!(R instanceof Te||R instanceof We))throw new Error("Slice object must be an array or string");const ue=this.evaluate(ee.start,D),le=this.evaluate(ee.stop,D),ke=this.evaluate(ee.step,D);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 R instanceof Te?new Te(ge(R.value,ue.value,le.value,ke.value)):new We(ge(Array.from(R.value),ue.value,le.value,ke.value).join(""))}evaluateMemberExpression(R,ee){const D=this.evaluate(R.object,ee);let ue;if(R.computed){if(R.property.type==="SliceExpression")return this.evaluateSliceExpression(D,R.property,ee);ue=this.evaluate(R.property,ee)}else ue=new We(R.property.value);let le;if(D instanceof pt){if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=D.value.get(ue.value)??D.builtins.get(ue.value)}else if(D instanceof Te||D instanceof We)if(ue instanceof Be)le=D.value.at(ue.value),D instanceof We&&(le=new We(D.value.at(ue.value)));else if(ue instanceof We)le=D.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=D.builtins.get(ue.value)}return le instanceof Le?le:new A}evaluateSet(R,ee){const D=this.evaluate(R.value,ee);if(R.assignee.type==="Identifier"){const ue=R.assignee.value;ee.setVariable(ue,D)}else if(R.assignee.type==="MemberExpression"){const ue=R.assignee,le=this.evaluate(ue.object,ee);if(!(le instanceof pt))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,D)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(R.assignee)}`);return new et}evaluateIf(R,ee){const D=this.evaluate(R.test,ee);return this.evaluateBlock(D.__bool__().value?R.body:R.alternate,ee)}evaluateFor(R,ee){const D=new $e(ee);let ue,le;if(R.iterable.type==="SelectExpression"){const Ve=R.iterable;le=this.evaluate(Ve.iterable,D),ue=Ve.test}else le=this.evaluate(R.iterable,D);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 $e(D),ve=le.value[Ve];let Re;if(R.loopvar.type==="Identifier")Re=qe=>qe.setVariable(R.loopvar.value,ve);else if(R.loopvar.type==="TupleLiteral"){const qe=R.loopvar;if(ve.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ve.type}`);const Qe=ve;if(qe.value.length!==Qe.value.length)throw new Error(`Too ${qe.value.length>Qe.value.length?"few":"many"} items to unpack`);Re=tt=>{for(let ft=0;ft<qe.value.length;++ft){if(qe.value[ft].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${qe.value[ft].type}`);tt.setVariable(qe.value[ft].value,Qe.value[ft])}}}else throw new Error(`Invalid loop variable(s): ${R.loopvar.type}`);ue&&(Re(Z),!this.evaluate(ue,Z).__bool__().value)||(ke.push(ve),Ne.push(Re))}let dt="",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 st(Ve===0)],["last",new st(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]]);D.setVariable("loop",new pt(Z)),Ne[Ve](D);const ve=this.evaluateBlock(R.body,D);dt+=ve.value,Je=!1}if(Je){const Ve=this.evaluateBlock(R.defaultBlock,D);dt+=Ve.value}return new We(dt)}evaluateMacro(R,ee){return ee.setVariable(R.name.value,new Ye((D,ue)=>{var Ne;const le=new $e(ue);D=D.slice();let ke;((Ne=D.at(-1))==null?void 0:Ne.type)==="KeywordArgumentsValue"&&(ke=D.pop());for(let dt=0;dt<R.args.length;++dt){const Je=R.args[dt],Ve=D[dt];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(R.body,le)})),new et}evaluate(R,ee){if(R===void 0)return new A;switch(R.type){case"Program":return this.evalProgram(R,ee);case"Set":return this.evaluateSet(R,ee);case"If":return this.evaluateIf(R,ee);case"For":return this.evaluateFor(R,ee);case"Macro":return this.evaluateMacro(R,ee);case"NumericLiteral":return new Be(Number(R.value));case"StringLiteral":return new We(R.value);case"BooleanLiteral":return new st(R.value);case"ArrayLiteral":return new Te(R.value.map(D=>this.evaluate(D,ee)));case"TupleLiteral":return new je(R.value.map(D=>this.evaluate(D,ee)));case"ObjectLiteral":{const D=new Map;for(const[ue,le]of R.value){const ke=this.evaluate(ue,ee);if(!(ke instanceof We))throw new Error(`Object keys must be strings: got ${ke.type}`);D.set(ke.value,this.evaluate(le,ee))}return new pt(D)}case"Identifier":return this.evaluateIdentifier(R,ee);case"CallExpression":return this.evaluateCallExpression(R,ee);case"MemberExpression":return this.evaluateMemberExpression(R,ee);case"UnaryExpression":return this.evaluateUnaryExpression(R,ee);case"BinaryExpression":return this.evaluateBinaryExpression(R,ee);case"FilterExpression":return this.evaluateFilterExpression(R,ee);case"TestExpression":return this.evaluateTestExpression(R,ee);default:throw new SyntaxError(`Unknown node type: ${R.type}`)}}};function se(R){switch(typeof R){case"number":return new Be(R);case"string":return new We(R);case"boolean":return new st(R);case"undefined":return new A;case"object":return R===null?new et:Array.isArray(R)?new Te(R.map(se)):new pt(new Map(Object.entries(R).map(([ee,D])=>[ee,se(D)])));case"function":return new Ye((ee,D)=>{const ue=R(...ee.map(le=>le.value))??null;return se(ue)});default:throw new Error(`Cannot convert to runtime value: ${R}`)}}function re(R,ee,D){const ue=D??0;switch(R.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(R.value);case"ArrayValue":case"ObjectValue":{const le=ee?" ".repeat(ee):"",ke=` `+le.repeat(ue),Ne=ke+le;if(R.type==="ArrayValue"){const dt=R.value.map(Je=>re(Je,ee,ue+1));return ee?`[${Ne}${dt.join(`,${Ne}`)}${ke}]`:`[${dt.join(", ")}]`}else{const dt=Array.from(R.value.entries()).map(([Je,Ve])=>{const Z=`"${Je}": ${re(Ve,ee,ue+1)}`;return ee?`${Ne}${Z}`:Z});return ee?`{${dt.join(",")}${ke}}`:`{${dt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${R.type}`)}}var ye=class{constructor(R){He(this,"parsed");const ee=y(R,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Me(ee)}render(R){const ee=new $e;ee.set("false",!1),ee.set("true",!0),ee.set("raise_exception",le=>{throw new Error(le)}),ee.set("range",Q);for(const[le,ke]of Object.entries(R))ee.set(le,ke);return new Pe(ee).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,t,r)=>{r.r(t),r.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 y=o.get(h);if(y===void 0)o.set(h,{backend:g,priority:M});else{if(y.priority>M)return;if(y.priority===M&&y.backend!==g)throw new Error(`cannot register backend "${h}" using priority ${M}`)}if(M>=0){const E=a.indexOf(h);E!==-1&&a.splice(E,1);for(let T=0;T<a.length;T++)if(o.get(a[T]).priority<=M){a.splice(T,0,h);return}a.push(h)}return}throw new TypeError("not a valid backend")},p=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(y){return M||(g.error=`${y}`,g.aborted=!0),g.error}finally{delete g.initPromise}}},_=async h=>{const g=h.executionProviders||[],M=g.map(C=>typeof C=="string"?C:C.name),y=M.length===0?a:M;let E;const T=[],O=new Set;for(const C of y){const w=await p(C);typeof w=="string"?T.push({name:C,err:w}):(E||(E=w),E===w&&O.add(C))}if(!E)throw new Error(`no available backend found. ERR: ${T.map(C=>`[${C.name}] ${C.err}`).join(", ")}`);for(const{name:C,err:w}of T)M.includes(C)&&console.warn(`removing requested execution provider "${C}" from session options because it is not available: ${w}`);const S=g.filter(C=>O.has(typeof C=="string"?C:C.name));return[E,new Proxy(h,{get:(C,w)=>w==="executionProviders"?S:Reflect.get(C,w)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,t,r)=>{r.r(t),r.d(t,{registerBackend:()=>o.registerBackend});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,t,r)=>{r.r(t),r.d(t,{env:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/version.js");let a="warning";const l={wasm:{},webgl:{},webgpu:{},versions:{common:o.version},set logLevel(p){if(p!==void 0){if(typeof p!="string"||["verbose","info","warning","error","fatal"].indexOf(p)===-1)throw new Error(`Unsupported logging level: ${p}`);a=p}},get logLevel(){return a}};Object.defineProperty(l,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,r)=>{r.r(t),r.d(t,{env:()=>a});var o=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=o.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,t,r)=>{r.r(t),r.d(t,{InferenceSession:()=>l.InferenceSession,TRACE:()=>_.TRACE,TRACE_FUNC_BEGIN:()=>_.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>_.TRACE_FUNC_END,Tensor:()=>p.Tensor,TrainingSession:()=>h.TrainingSession,env:()=>a.env,registerBackend:()=>o.registerBackend});var o=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),a=r("./node_modules/onnxruntime-common/dist/esm/env.js"),l=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),p=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var _=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var h=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,t,r)=>{r.r(t),r.d(t,{InferenceSession:()=>p});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),l=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class p{constructor(h){this.handler=h}async run(h,g,M){(0,l.TRACE_FUNC_BEGIN)();const y={};let E={};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 T=!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.");T=!1;for(const C of g){if(typeof C!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(C)===-1)throw new RangeError(`'fetches' contains invalid output name: ${C}.`);y[C]=null}if(typeof M=="object"&&M!==null)E=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let C=!1;const w=Object.getOwnPropertyNames(g);for(const b of this.outputNames)if(w.indexOf(b)!==-1){const I=g[b];(I===null||I instanceof a.Tensor)&&(C=!0,T=!1,y[b]=I)}if(C){if(typeof M=="object"&&M!==null)E=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else E=g}}else if(typeof g<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const C of this.inputNames)if(typeof h[C]>"u")throw new Error(`input '${C}' is missing in 'feeds'.`);if(T)for(const C of this.outputNames)y[C]=null;const O=await this.handler.run(h,y,E),S={};for(const C in O)if(Object.hasOwnProperty.call(O,C)){const w=O[C];w instanceof a.Tensor?S[C]=w:S[C]=new a.Tensor(w.type,w.data,w.dims)}return(0,l.TRACE_FUNC_END)(),S}async release(){return this.handler.dispose()}static async create(h,g,M,y){(0,l.TRACE_FUNC_BEGIN)();let E,T={};if(typeof h=="string"){if(E=h,typeof g=="object"&&g!==null)T=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(h instanceof Uint8Array){if(E=h,typeof g=="object"&&g!==null)T=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 w=h;let b=0,I=h.byteLength;if(typeof g=="object"&&g!==null)T=g;else if(typeof g=="number"){if(b=g,!Number.isSafeInteger(b))throw new RangeError("'byteOffset' must be an integer.");if(b<0||b>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(I=h.byteLength-b,typeof M=="number"){if(I=M,!Number.isSafeInteger(I))throw new RangeError("'byteLength' must be an integer.");if(I<=0||b+I>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-b}].`);if(typeof y=="object"&&y!==null)T=y;else if(typeof y<"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.");E=new Uint8Array(w,b,I)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[O,S]=await(0,o.resolveBackendAndExecutionProviders)(T),C=await O.createInferenceSessionHandler(E,S);return(0,l.TRACE_FUNC_END)(),new p(C)}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,r)=>{r.r(t),r.d(t,{InferenceSession:()=>a});var o=r("./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,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,t,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,t,r)=>{r.r(t),r.d(t,{tensorToDataURL:()=>o,tensorToImageData:()=>a});const o=(l,p)=>{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;(p==null?void 0:p.tensorLayout)!==void 0&&p.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[3]):(g=l.dims[3],M=l.dims[2]);const y=(p==null?void 0:p.format)!==void 0?p.format:"RGB",E=p==null?void 0:p.norm;let T,O;E===void 0||E.mean===void 0?T=[255,255,255,255]:typeof E.mean=="number"?T=[E.mean,E.mean,E.mean,E.mean]:(T=[E.mean[0],E.mean[1],E.mean[2],0],E.mean[3]!==void 0&&(T[3]=E.mean[3])),E===void 0||E.bias===void 0?O=[0,0,0,0]:typeof E.bias=="number"?O=[E.bias,E.bias,E.bias,E.bias]:(O=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&(O[3]=E.bias[3]));const S=M*g;let C=0,w=S,b=S*2,I=-1;y==="RGBA"?(C=0,w=S,b=S*2,I=S*3):y==="RGB"?(C=0,w=S,b=S*2):y==="RBG"&&(C=0,b=S,w=S*2);for(let U=0;U<M;U++)for(let z=0;z<g;z++){const B=(l.data[C++]-O[0])*T[0],j=(l.data[w++]-O[1])*T[1],N=(l.data[b++]-O[2])*T[2],ae=I===-1?255:(l.data[I++]-O[3])*T[3];h.fillStyle="rgba("+B+","+j+","+N+","+ae+")",h.fillRect(z,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,p)=>{const _=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let h;if(_!=null){let g,M,y;(p==null?void 0:p.tensorLayout)!==void 0&&p.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[1],y=l.dims[3]):(g=l.dims[3],M=l.dims[2],y=l.dims[1]);const E=p!==void 0&&p.format!==void 0?p.format:"RGB",T=p==null?void 0:p.norm;let O,S;T===void 0||T.mean===void 0?O=[255,255,255,255]:typeof T.mean=="number"?O=[T.mean,T.mean,T.mean,T.mean]:(O=[T.mean[0],T.mean[1],T.mean[2],255],T.mean[3]!==void 0&&(O[3]=T.mean[3])),T===void 0||T.bias===void 0?S=[0,0,0,0]:typeof T.bias=="number"?S=[T.bias,T.bias,T.bias,T.bias]:(S=[T.bias[0],T.bias[1],T.bias[2],0],T.bias[3]!==void 0&&(S[3]=T.bias[3]));const C=M*g;if(p!==void 0&&(p.format!==void 0&&y===4&&p.format!=="RGBA"||y===3&&p.format!=="RGB"&&p.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const w=4;let b=0,I=1,U=2,z=3,B=0,j=C,N=C*2,ae=-1;E==="RGBA"?(B=0,j=C,N=C*2,ae=C*3):E==="RGB"?(B=0,j=C,N=C*2):E==="RBG"&&(B=0,N=C,j=C*2),h=_.createImageData(g,M);for(let ce=0;ce<M*g;b+=w,I+=w,U+=w,z+=w,ce++)h.data[b]=(l.data[B++]-S[0])*O[0],h.data[I]=(l.data[j++]-S[1])*O[1],h.data[U]=(l.data[N++]-S[2])*O[2],h.data[z]=ae===-1?255:(l.data[ae++]-S[3])*O[3]}else throw new Error("Can not access image data");return h}},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js":(e,t,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,t,r)=>{r.r(t),r.d(t,{bufferToTensor:()=>a,tensorFromGpuBuffer:()=>_,tensorFromImage:()=>l,tensorFromPinnedBuffer:()=>h,tensorFromTexture:()=>p});var o=r("./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:y,width:E}=M,T=M.norm??{mean:255,bias:0};let O,S;typeof T.mean=="number"?O=[T.mean,T.mean,T.mean,T.mean]:O=[T.mean[0],T.mean[1],T.mean[2],T.mean[3]??255],typeof T.bias=="number"?S=[T.bias,T.bias,T.bias,T.bias]:S=[T.bias[0],T.bias[1],T.bias[2],T.bias[3]??0];const C=M.format!==void 0?M.format:"RGBA",w=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",b=y*E,I=w==="RGBA"?new Float32Array(b*4):new Float32Array(b*3);let U=4,z=0,B=1,j=2,N=3,ae=0,ce=b,xe=b*2,Y=-1;C==="RGB"&&(U=3,z=0,B=1,j=2,N=-1),w==="RGBA"?Y=b*3:w==="RBG"?(ae=0,xe=b,ce=b*2):w==="BGR"&&(xe=0,ce=b,ae=b*2);for(let L=0;L<b;L++,z+=U,j+=U,B+=U,N+=U)I[ae++]=(g[z]+S[0])/O[0],I[ce++]=(g[B]+S[1])/O[1],I[xe++]=(g[j]+S[2])/O[2],Y!==-1&&N!==-1&&(I[Y++]=(g[N]+S[3])/O[3]);return w==="RGBA"?new o.Tensor("float32",I,[1,4,y,E]):new o.Tensor("float32",I,[1,3,y,E])},l=async(g,M)=>{const y=typeof HTMLImageElement<"u"&&g instanceof HTMLImageElement,E=typeof ImageData<"u"&&g instanceof ImageData,T=typeof ImageBitmap<"u"&&g instanceof ImageBitmap,O=typeof g=="string";let S,C=M??{};const w=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},b=I=>I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?I.getContext("2d"):null;if(y){const I=w();I.width=g.width,I.height=g.height;const U=b(I);if(U!=null){let z=g.height,B=g.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(z=M.resizedHeight,B=M.resizedWidth),M!==void 0){if(C=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");C.tensorFormat="RGBA",C.height=z,C.width=B}else C.tensorFormat="RGBA",C.height=z,C.width=B;U.drawImage(g,0,0),S=U.getImageData(0,0,B,z).data}else throw new Error("Can not access image data")}else if(E){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&&(C=M),C.format="RGBA",C.height=I,C.width=U,M!==void 0){const z=w();z.width=U,z.height=I;const B=b(z);if(B!=null)B.putImageData(g,0,0),S=B.getImageData(0,0,U,I).data;else throw new Error("Can not access image data")}else S=g.data}else if(T){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const I=w();I.width=g.width,I.height=g.height;const U=b(I);if(U!=null){const z=g.height,B=g.width;return U.drawImage(g,0,0,B,z),S=U.getImageData(0,0,B,z).data,C.height=z,C.width=B,a(S,C)}else throw new Error("Can not access image data")}else{if(O)return new Promise((I,U)=>{const z=w(),B=b(z);if(!g||!B)return U();const j=new Image;j.crossOrigin="Anonymous",j.src=g,j.onload=()=>{z.width=j.width,z.height=j.height,B.drawImage(j,0,0,z.width,z.height);const N=B.getImageData(0,0,z.width,z.height);C.height=z.height,C.width=z.width,I(a(N.data,C))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(S!==void 0)return a(S,C);throw new Error("Input data provided is not supported - aborted tensor creation")},p=(g,M)=>{const{width:y,height:E,download:T,dispose:O}=M,S=[1,E,y,4];return new o.Tensor({location:"texture",type:"float32",texture:g,dims:S,download:T,dispose:O})},_=(g,M)=>{const{dataType:y,dims:E,download:T,dispose:O}=M;return new o.Tensor({location:"gpu-buffer",type:y??"float32",gpuBuffer:g,dims:E,download:T,dispose:O})},h=(g,M,y)=>new o.Tensor({location:"cpu-pinned",type:g,data:M,dims:y??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,t,r)=>{r.r(t),r.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>a,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>o,checkTypedArray:()=>p});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 p=()=>{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,r)=>{r.r(t),r.d(t,{Tensor:()=>_});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),a=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),l=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),p=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class _{constructor(g,M,y){(0,l.checkTypedArray)();let E,T;if(typeof g=="object"&&"location"in g)switch(this.dataLocation=g.location,E=g.type,T=g.dims,g.location){case"cpu-pinned":{const S=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(E);if(!S)throw new TypeError(`unsupported type "${E}" 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(E!=="float32")throw new TypeError(`unsupported type "${E}" to create tensor from texture`);this.gpuTextureData=g.texture,this.downloader=g.download,this.disposer=g.dispose;break}case"gpu-buffer":{if(E!=="float32"&&E!=="float16"&&E!=="int32"&&E!=="int64"&&E!=="uint32"&&E!=="uint8"&&E!=="bool")throw new TypeError(`unsupported type "${E}" 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,C;if(typeof g=="string")if(E=g,C=y,g==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");S=M}else{const w=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(g);if(w===void 0)throw new TypeError(`Unsupported tensor type: ${g}.`);if(Array.isArray(M)){if(g==="float16"&&w===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");g==="uint64"||g==="int64"?S=w.from(M,BigInt):S=w.from(M)}else if(M instanceof w)S=M;else throw new TypeError(`A ${E} tensor's data must be type of ${w}`)}else if(C=M,Array.isArray(g)){if(g.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const w=typeof g[0];if(w==="string")E="string",S=g;else if(w==="boolean")E="bool",S=Uint8Array.from(g);else throw new TypeError(`Invalid element type of data array: ${w}.`)}else{const w=l.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(g.constructor);if(w===void 0)throw new TypeError(`Unsupported type for tensor data: ${g.constructor}.`);E=w,S=g}if(C===void 0)C=[S.length];else if(!Array.isArray(C))throw new TypeError("A tensor's dims must be a number array");T=C,this.cpuData=S,this.dataLocation="cpu"}const O=(0,p.calculateSize)(T);if(this.cpuData&&O!==this.cpuData.length)throw new Error(`Tensor's size(${O}) does not match data length(${this.cpuData.length}).`);this.type=E,this.dims=T,this.size=O}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,y){return(0,a.tensorFromPinnedBuffer)(g,M,y)}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,p.tensorReshape)(this,g)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,t,r)=>{r.r(t),r.d(t,{calculateSize:()=>a,tensorReshape:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=p=>{let _=1;for(let h=0;h<p.length;h++){const g=p[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=(p,_)=>{switch(p.location){case"cpu":return new o.Tensor(p.type,p.data,_);case"cpu-pinned":return new o.Tensor({location:"cpu-pinned",data:p.data,type:p.type,dims:_});case"texture":return new o.Tensor({location:"texture",texture:p.texture,type:p.type,dims:_});case"gpu-buffer":return new o.Tensor({location:"gpu-buffer",gpuBuffer:p.gpuBuffer,type:p.type,dims:_});default:throw new Error(`tensorReshape: tensor location ${p.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,t,r)=>{r.r(t),r.d(t,{Tensor:()=>a});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=o.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,t,r)=>{r.r(t),r.d(t,{TRACE:()=>a,TRACE_FUNC_BEGIN:()=>p,TRACE_FUNC_END:()=>_});var o=r("./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 E;const M=((E=new Error().stack)==null?void 0:E.split(/\r\n|\r|\n/g))||[];let y=!1;for(let T=0;T<M.length;T++){if(y&&!M[T].includes("TRACE_FUNC")){let O=`FUNC_${h}::${M[T].trim().split(" ")[1]}`;g&&(O+=`::${g}`),a("CPU",O);return}M[T].includes("TRACE_FUNC")&&(y=!0)}},p=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,r)=>{r.r(t),r.d(t,{TrainingSession:()=>p});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=r("./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 p{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||"",y=h.optimizerModel||"",E=g||{},[T,O]=await(0,o.resolveBackendAndExecutionProviders)(E);if(T.createTrainingSessionHandler){const S=await T.createTrainingSessionHandler(h.checkpointState,h.trainModel,M,y,O);return new p(S,!!h.optimizerModel,!!h.evalModel)}else throw new Error(l)}typeNarrowingForRunStep(h,g,M,y,E){const T={};let O={};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 y=="object"){if(y===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(y instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(y)){if(y.length===0)throw new TypeError("'fetches' cannot be an empty array.");S=!1;for(const C of y){if(typeof C!="string")throw new TypeError("'fetches' must be a string array or an object.");if(g.indexOf(C)===-1)throw new RangeError(`'fetches' contains invalid output name: ${C}.`);T[C]=null}if(typeof E=="object"&&E!==null)O=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else{let C=!1;const w=Object.getOwnPropertyNames(y);for(const b of g)if(w.indexOf(b)!==-1){const I=y[b];(I===null||I instanceof a.Tensor)&&(C=!0,S=!1,T[b]=I)}if(C){if(typeof E=="object"&&E!==null)O=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else O=y}}else if(typeof y<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const C of h)if(typeof M[C]>"u")throw new Error(`input '${C}' is missing in 'feeds'.`);if(S)for(const C of g)T[C]=null;return[T,O]}convertHandlerReturnTypeToMapOfTensors(h){const g={};for(const M in h)if(Object.hasOwnProperty.call(h,M)){const y=h[M];y instanceof a.Tensor?g[M]=y:g[M]=new a.Tensor(y.type,y.data,y.dims)}return g}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(h,g,M){const[y,E]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,h,g,M),T=await this.handler.runTrainStep(h,y,E);return this.convertHandlerReturnTypeToMapOfTensors(T)}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[y,E]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,h,g,M),T=await this.handler.runEvalStep(h,y,E);return this.convertHandlerReturnTypeToMapOfTensors(T)}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,r)=>{r.r(t),r.d(t,{TrainingSession:()=>a});var o=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const a=o.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,t,r)=>{r.r(t),r.d(t,{version:()=>o});const o="1.18.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(e,t,r)=>{r.r(t),r.d(t,{InferenceSession:()=>re,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>et,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>dt,default:()=>wx,env:()=>N,registerBackend:()=>O});/*! * ONNX Runtime Web v1.19.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var o=Object.defineProperty,a=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,_=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(i,s)=>(typeof require<"u"?require:i)[s]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),h=(n,i)=>()=>(n&&(i=n(n=0)),i),g=(n,i)=>{for(var s in i)o(n,s,{get:i[s],enumerable:!0})},M=(n,i,s,u)=>{if(i&&typeof i=="object"||typeof i=="function")for(let c of l(i))!p.call(n,c)&&c!==s&&o(n,c,{get:()=>i[c],enumerable:!(u=a(i,c))||u.enumerable});return n},y=n=>M(o({},"__esModule",{value:!0}),n),E,T,O,S,C,w=h(()=>{E=new Map,T=[],O=(n,i,s)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let u=E.get(n);if(u===void 0)E.set(n,{backend:i,priority:s});else{if(u.priority>s)return;if(u.priority===s&&u.backend!==i)throw new Error(`cannot register backend "${n}" using priority ${s}`)}if(s>=0){let c=T.indexOf(n);c!==-1&&T.splice(c,1);for(let f=0;f<T.length;f++)if(E.get(T[f]).priority<=s){T.splice(f,0,n);return}T.push(n)}return}throw new TypeError("not a valid backend")},S=async n=>{let i=E.get(n);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(n)),await i.initPromise,i.initialized=!0,i.backend}catch(u){return s||(i.error=`${u}`,i.aborted=!0),i.error}finally{delete i.initPromise}}},C=async n=>{let i=n.executionProviders||[],s=i.map(k=>typeof k=="string"?k:k.name),u=s.length===0?T:s,c,f=[],d=new Set;for(let k of u){let $=await S(k);typeof $=="string"?f.push({name:k,err:$}):(c||(c=$),c===$&&d.add(k))}if(!c)throw new Error(`no available backend found. ERR: ${f.map(k=>`[${k.name}] ${k.err}`).join(", ")}`);for(let{name:k,err:$}of f)s.includes(k)&&console.warn(`removing requested execution provider "${k}" from session options because it is not available: ${$}`);let x=i.filter(k=>d.has(typeof k=="string"?k:k.name));return[c,new Proxy(n,{get:(k,$)=>$==="executionProviders"?x:Reflect.get(k,$)})]}}),b=h(()=>{w()}),I,U=h(()=>{I="1.19.0"}),z,B,j=h(()=>{U(),z="warning",B={wasm:{},webgl:{},webgpu:{},versions:{common:I},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);z=n}},get logLevel(){return z}},Object.defineProperty(B,"logLevel",{enumerable:!0})}),N,ae=h(()=>{j(),N=B}),ce,xe,Y=h(()=>{ce=(n,i)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=n.dims[3],s.height=n.dims[2];let u=s.getContext("2d");if(u!=null){let c,f;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=n.dims[2],f=n.dims[3]):(c=n.dims[3],f=n.dims[2]);let d=(i==null?void 0:i.format)!==void 0?i.format:"RGB",x=i==null?void 0:i.norm,k,$;x===void 0||x.mean===void 0?k=[255,255,255,255]:typeof x.mean=="number"?k=[x.mean,x.mean,x.mean,x.mean]:(k=[x.mean[0],x.mean[1],x.mean[2],0],x.mean[3]!==void 0&&(k[3]=x.mean[3])),x===void 0||x.bias===void 0?$=[0,0,0,0]:typeof x.bias=="number"?$=[x.bias,x.bias,x.bias,x.bias]:($=[x.bias[0],x.bias[1],x.bias[2],0],x.bias[3]!==void 0&&($[3]=x.bias[3]));let H=f*c,q=0,v=H,oe=H*2,te=-1;d==="RGBA"?(q=0,v=H,oe=H*2,te=H*3):d==="RGB"?(q=0,v=H,oe=H*2):d==="RBG"&&(q=0,oe=H,v=H*2);for(let de=0;de<f;de++)for(let we=0;we<c;we++){let be=(n.data[q++]-$[0])*k[0],he=(n.data[v++]-$[1])*k[1],De=(n.data[oe++]-$[2])*k[2],Ae=te===-1?255:(n.data[te++]-$[3])*k[3];u.fillStyle="rgba("+be+","+he+","+De+","+Ae+")",u.fillRect(we,de,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")},xe=(n,i)=>{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),u;if(s!=null){let c,f,d;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=n.dims[2],f=n.dims[1],d=n.dims[3]):(c=n.dims[3],f=n.dims[2],d=n.dims[1]);let x=i!==void 0&&i.format!==void 0?i.format:"RGB",k=i==null?void 0:i.norm,$,H;k===void 0||k.mean===void 0?$=[255,255,255,255]:typeof k.mean=="number"?$=[k.mean,k.mean,k.mean,k.mean]:($=[k.mean[0],k.mean[1],k.mean[2],255],k.mean[3]!==void 0&&($[3]=k.mean[3])),k===void 0||k.bias===void 0?H=[0,0,0,0]:typeof k.bias=="number"?H=[k.bias,k.bias,k.bias,k.bias]:(H=[k.bias[0],k.bias[1],k.bias[2],0],k.bias[3]!==void 0&&(H[3]=k.bias[3]));let q=f*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,oe=0,te=1,de=2,we=3,be=0,he=q,De=q*2,Ae=-1;x==="RGBA"?(be=0,he=q,De=q*2,Ae=q*3):x==="RGB"?(be=0,he=q,De=q*2):x==="RBG"&&(be=0,De=q,he=q*2),u=s.createImageData(c,f);for(let Ie=0;Ie<f*c;oe+=v,te+=v,de+=v,we+=v,Ie++)u.data[oe]=(n.data[be++]-H[0])*$[0],u.data[te]=(n.data[he++]-H[1])*$[1],u.data[de]=(n.data[De++]-H[2])*$[2],u.data[we]=Ae===-1?255:(n.data[Ae++]-H[3])*$[3]}else throw new Error("Can not access image data");return u}}),_e,L,Se,Xe,me,X=h(()=>{pt(),_e=(n,i)=>{if(n===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},f,d;typeof c.mean=="number"?f=[c.mean,c.mean,c.mean,c.mean]:f=[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 x=i.format!==void 0?i.format:"RGBA",k=i.tensorFormat!==void 0&&i.tensorFormat!==void 0?i.tensorFormat:"RGB",$=s*u,H=k==="RGBA"?new Float32Array($*4):new Float32Array($*3),q=4,v=0,oe=1,te=2,de=3,we=0,be=$,he=$*2,De=-1;x==="RGB"&&(q=3,v=0,oe=1,te=2,de=-1),k==="RGBA"?De=$*3:k==="RBG"?(we=0,he=$,be=$*2):k==="BGR"&&(he=0,be=$,we=$*2);for(let Ae=0;Ae<$;Ae++,v+=q,te+=q,oe+=q,de+=q)H[we++]=(n[v]+d[0])/f[0],H[be++]=(n[oe]+d[1])/f[1],H[he++]=(n[te]+d[2])/f[2],De!==-1&&de!==-1&&(H[De++]=(n[de]+d[3])/f[3]);return k==="RGBA"?new st("float32",H,[1,4,s,u]):new st("float32",H,[1,3,s,u])},L=async(n,i)=>{let s=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,u=typeof ImageData<"u"&&n instanceof ImageData,c=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,f=typeof n=="string",d,x=i??{},k=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},$=H=>H instanceof HTMLCanvasElement||H instanceof OffscreenCanvas?H.getContext("2d"):null;if(s){let H=k();H.width=n.width,H.height=n.height;let q=$(H);if(q!=null){let v=n.height,oe=n.width;if(i!==void 0&&i.resizedHeight!==void 0&&i.resizedWidth!==void 0&&(v=i.resizedHeight,oe=i.resizedWidth),i!==void 0){if(x=i,i.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");x.tensorFormat="RGBA",x.height=v,x.width=oe}else x.tensorFormat="RGBA",x.height=v,x.width=oe;q.drawImage(n,0,0),d=q.getImageData(0,0,oe,v).data}else throw new Error("Can not access image data")}else if(u){let H,q;if(i!==void 0&&i.resizedWidth!==void 0&&i.resizedHeight!==void 0?(H=i.resizedHeight,q=i.resizedWidth):(H=n.height,q=n.width),i!==void 0&&(x=i),x.format="RGBA",x.height=H,x.width=q,i!==void 0){let v=k();v.width=q,v.height=H;let oe=$(v);if(oe!=null)oe.putImageData(n,0,0),d=oe.getImageData(0,0,q,H).data;else throw new Error("Can not access image data")}else d=n.data}else if(c){if(i===void 0)throw new Error("Please provide image config with format for Imagebitmap");let H=k();H.width=n.width,H.height=n.height;let q=$(H);if(q!=null){let v=n.height,oe=n.width;return q.drawImage(n,0,0,oe,v),d=q.getImageData(0,0,oe,v).data,x.height=v,x.width=oe,_e(d,x)}else throw new Error("Can not access image data")}else{if(f)return new Promise((H,q)=>{let v=k(),oe=$(v);if(!n||!oe)return q();let te=new Image;te.crossOrigin="Anonymous",te.src=n,te.onload=()=>{v.width=te.width,v.height=te.height,oe.drawImage(te,0,0,v.width,v.height);let de=oe.getImageData(0,0,v.width,v.height);x.height=v.height,x.width=v.width,H(_e(de.data,x))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return _e(d,x);throw new Error("Input data provided is not supported - aborted tensor creation")},Se=(n,i)=>{let{width:s,height:u,download:c,dispose:f}=i,d=[1,u,s,4];return new st({location:"texture",type:"float32",texture:n,dims:d,download:c,dispose:f})},Xe=(n,i)=>{let{dataType:s,dims:u,download:c,dispose:f}=i;return new st({location:"gpu-buffer",type:s??"float32",gpuBuffer:n,dims:u,download:c,dispose:f})},me=(n,i,s)=>new st({location:"cpu-pinned",type:n,data:i,dims:s??[i.length]})}),ie,Me,Q,ge,Ke=h(()=>{ie=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Me=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Q=!1,ge=()=>{if(!Q){Q=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;n&&(ie.set("int64",BigInt64Array),Me.set(BigInt64Array,"int64")),i&&(ie.set("uint64",BigUint64Array),Me.set(BigUint64Array,"uint64")),s?(ie.set("float16",Float16Array),Me.set(Float16Array,"float16")):ie.set("float16",Uint16Array)}}}),Le,Be,We=h(()=>{pt(),Le=n=>{let i=1;for(let s=0;s<n.length;s++){let u=n[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=(n,i)=>{switch(n.location){case"cpu":return new st(n.type,n.data,i);case"cpu-pinned":return new st({location:"cpu-pinned",data:n.data,type:n.type,dims:i});case"texture":return new st({location:"texture",texture:n.texture,type:n.type,dims:i});case"gpu-buffer":return new st({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:i});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}}),st,pt=h(()=>{Y(),X(),Ke(),We(),st=class{constructor(n,i,s){ge();let u,c;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,u=n.type,c=n.dims,n.location){case"cpu-pinned":{let d=ie.get(u);if(!d)throw new TypeError(`unsupported type "${u}" to create tensor from pinned buffer`);if(!(n.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=n.data;break}case"texture":{if(u!=="float32")throw new TypeError(`unsupported type "${u}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.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=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,x;if(typeof n=="string")if(u=n,x=s,n==="string"){if(!Array.isArray(i))throw new TypeError("A string tensor's data must be a string array.");d=i}else{let k=ie.get(n);if(k===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(i)){if(n==="float16"&&k===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");n==="uint64"||n==="int64"?d=k.from(i,BigInt):d=k.from(i)}else if(i instanceof k)d=i;else throw new TypeError(`A ${u} tensor's data must be type of ${k}`)}else if(x=i,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let k=typeof n[0];if(k==="string")u="string",d=n;else if(k==="boolean")u="bool",d=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${k}.`)}else{let k=Me.get(n.constructor);if(k===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);u=k,d=n}if(x===void 0)x=[d.length];else if(!Array.isArray(x))throw new TypeError("A tensor's dims must be a number array");c=x,this.cpuData=d,this.dataLocation="cpu"}let f=Le(c);if(this.cpuData&&f!==this.cpuData.length)throw new Error(`Tensor's size(${f}) does not match data length(${this.cpuData.length}).`);this.type=u,this.dims=c,this.size=f}static async fromImage(n,i){return L(n,i)}static fromTexture(n,i){return Se(n,i)}static fromGpuBuffer(n,i){return Xe(n,i)}static fromPinnedBuffer(n,i,s){return me(n,i,s)}toDataURL(n){return ce(this,n)}toImageData(n){return xe(this,n)}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(n){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,n&&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(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Be(this,n)}}}),Ge,Te=h(()=>{pt(),Ge=st}),je,Ye,et,A,$e=h(()=>{j(),je=(n,i)=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||console.timeStamp(`${n}::ORT::${i}`)},Ye=(n,i)=>{var c;let s=((c=new Error().stack)==null?void 0:c.split(/\r\n|\r|\n/g))||[],u=!1;for(let f=0;f<s.length;f++){if(u&&!s[f].includes("TRACE_FUNC")){let d=`FUNC_${n}::${s[f].trim().split(" ")[1]}`;i&&(d+=`::${i}`),je("CPU",d);return}s[f].includes("TRACE_FUNC")&&(u=!0)}},et=n=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||Ye("BEGIN",n)},A=n=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||Ye("END",n)}}),Pe,se=h(()=>{w(),Te(),$e(),Pe=class Z2{constructor(i){this.handler=i}async run(i,s,u){et();let c={},f={};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 $ of s){if(typeof $!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf($)===-1)throw new RangeError(`'fetches' contains invalid output name: ${$}.`);c[$]=null}if(typeof u=="object"&&u!==null)f=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else{let $=!1,H=Object.getOwnPropertyNames(s);for(let q of this.outputNames)if(H.indexOf(q)!==-1){let v=s[q];(v===null||v instanceof Ge)&&($=!0,d=!1,c[q]=v)}if($){if(typeof u=="object"&&u!==null)f=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else f=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let $ of this.inputNames)if(typeof i[$]>"u")throw new Error(`input '${$}' is missing in 'feeds'.`);if(d)for(let $ of this.outputNames)c[$]=null;let x=await this.handler.run(i,c,f),k={};for(let $ in x)if(Object.hasOwnProperty.call(x,$)){let H=x[$];H instanceof Ge?k[$]=H:k[$]=new Ge(H.type,H.data,H.dims)}return A(),k}async release(){return this.handler.dispose()}static async create(i,s,u,c){et();let f,d={};if(typeof i=="string"){if(f=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(f=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 H=i,q=0,v=i.byteLength;if(typeof s=="object"&&s!==null)d=s;else if(typeof s=="number"){if(q=s,!Number.isSafeInteger(q))throw new RangeError("'byteOffset' must be an integer.");if(q<0||q>=H.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${H.byteLength}).`);if(v=i.byteLength-q,typeof u=="number"){if(v=u,!Number.isSafeInteger(v))throw new RangeError("'byteLength' must be an integer.");if(v<=0||q+v>H.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${H.byteLength-q}].`);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.");f=new Uint8Array(H,q,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[x,k]=await C(d),$=await x.createInferenceSessionHandler(f,k);return A(),new Z2($)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),re,ye=h(()=>{se(),re=Pe}),R=h(()=>{}),ee=h(()=>{}),D=h(()=>{}),ue=h(()=>{}),le,ke,Ne=h(()=>{w(),Te(),le="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",ke=class J2{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||"",f=s||{},[d,x]=await C(f);if(d.createTrainingSessionHandler){let k=await d.createTrainingSessionHandler(i.checkpointState,i.trainModel,u,c,x);return new J2(k,!!i.optimizerModel,!!i.evalModel)}else throw new Error(le)}typeNarrowingForRunStep(i,s,u,c,f){let d={},x={};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 k=!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.");k=!1;for(let $ of c){if(typeof $!="string")throw new TypeError("'fetches' must be a string array or an object.");if(s.indexOf($)===-1)throw new RangeError(`'fetches' contains invalid output name: ${$}.`);d[$]=null}if(typeof f=="object"&&f!==null)x=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else{let $=!1,H=Object.getOwnPropertyNames(c);for(let q of s)if(H.indexOf(q)!==-1){let v=c[q];(v===null||v instanceof Ge)&&($=!0,k=!1,d[q]=v)}if($){if(typeof f=="object"&&f!==null)x=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else x=c}}else if(typeof c<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let $ of i)if(typeof u[$]>"u")throw new Error(`input '${$}' is missing in 'feeds'.`);if(k)for(let $ of s)d[$]=null;return[d,x]}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,f]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,i,s,u),d=await this.handler.runTrainStep(i,c,f);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,f]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,i,s,u),d=await this.handler.runEvalStep(i,c,f);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()}}}),dt,Je=h(()=>{Ne(),dt=ke}),Ve={};g(Ve,{InferenceSession:()=>re,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>et,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>dt,env:()=>N,registerBackend:()=>O});var Z=h(()=>{b(),ae(),ye(),Te(),R(),ee(),$e(),D(),ue(),Je()}),ve=h(()=>{}),Re={};g(Re,{default:()=>tt});var qe,Qe,tt,ft=h(()=>{var n;xw(),wn(),Yr(),qe="ort-wasm-proxy-worker",Qe=((n=globalThis.self)==null?void 0:n.name)===qe,Qe&&(self.onmessage=i=>{let{type:s,in:u}=i.data;try{switch(s){case"init-wasm":Mi(u.wasm).then(()=>{xm(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:f}=u;Mm(f,c).then(()=>{postMessage({type:s})},d=>{postMessage({type:s,err:d})});break}case"copy-from":{let{buffer:c}=u,f=If(c);postMessage({type:s,out:f});break}case"create":{let{model:c,options:f}=u;Tm(c,f).then(d=>{postMessage({type:s,out:d})},d=>{postMessage({type:s,err:d})});break}case"release":km(u),postMessage({type:s});break;case"run":{let{sessionId:c,inputIndices:f,inputs:d,outputIndices:x,options:k}=u;Em(c,f,d,x,new Array(x.length).fill(null),k).then($=>{$.some(H=>H[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:$},Pm([...d,...$]))},$=>{postMessage({type:s,err:$})});break}case"end-profiling":Cm(u),postMessage({type:s});break;default:}}catch(c){postMessage({type:s,err:c})}}),tt=Qe?null:i=>new Worker(i??at,{type:"module",name:qe})}),ht={};g(ht,{default:()=>Et});var Tt,bt,Et,Lt=h(()=>{var n;bt=(Tt=import.meta.url,async function(i={}){function s(){return hr.buffer!=er.buffer&&Dn(),er}function u(){return hr.buffer!=er.buffer&&Dn(),yr}function c(){return hr.buffer!=er.buffer&&Dn(),ot}function f(){return hr.buffer!=er.buffer&&Dn(),Vt}function d(){return hr.buffer!=er.buffer&&Dn(),nr}function x(){return hr.buffer!=er.buffer&&Dn(),Wr}function k(){return hr.buffer!=er.buffer&&Dn(),pn}function $(){return hr.buffer!=er.buffer&&Dn(),si}var H,q,v=Object.assign({},i),oe=new Promise((m,F)=>{H=m,q=F}),te=typeof window=="object",de=typeof importScripts=="function",we=de&&self.name=="em-pthread";v.mountExternalData=(m,F)=>{(v.Fb||(v.Fb=new Map)).set(m,F)},v.unmountExternalData=()=>{delete v.Fb};var be=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let he=()=>{let m=(K,J,fe)=>(...ze)=>{let lt=io,yt=J==null?void 0:J();ze=K(...ze);let Pt=J==null?void 0:J();return yt!==Pt&&(K=Pt,fe(yt),J=fe=null),io!=lt?new Promise((Ft,Qt)=>{qm={resolve:Ft,reject:Qt}}):ze},F=K=>async(...J)=>{var fe;try{if(v.Eb)throw Error("Session already started");let ze=v.Eb={bc:J[0],errors:[]},lt=await K(...J);if(v.Eb!==ze)throw Error("Session mismatch");(fe=v.Mb)==null||fe.flush();let yt=ze.errors;if(0<yt.length){let Pt=await Promise.all(yt);if(Pt=Pt.filter(Ft=>Ft),0<Pt.length)throw Error(Pt.join(` `))}return lt}finally{v.Eb=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.Mb,v.Tb,v.Xb,v.Nb,v.Wb,v.jb,v.Yb,v.$b,v.Ub,v.Vb,v.Zb]=F;let K=v.Mb;v.jsepRegisterBuffer=(J,fe,ze,lt)=>K.registerBuffer(J,fe,ze,lt),v.jsepGetBuffer=J=>K.getBuffer(J),v.jsepCreateDownloader=(J,fe,ze)=>K.createDownloader(J,fe,ze),v.jsepOnReleaseSession=J=>{K.onReleaseSession(J)},v.jsepOnRunStart=J=>K.onRunStart(J)}};var De,Ae,Ie=Object.assign({},v),gt="./this.program",ut=(m,F)=>{throw F},vt="";(te||de)&&(de?vt=self.location.href:typeof document<"u"&&document.currentScript&&(vt=document.currentScript.src),Tt&&(vt=Tt),vt=vt.startsWith("blob:")?"":vt.substr(0,vt.replace(/[?#].*/,"").lastIndexOf("/")+1),de&&(Ae=m=>{var F=new XMLHttpRequest;return F.open("GET",m,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),De=(m,F,K)=>{var J=new XMLHttpRequest;J.open("GET",m,!0),J.responseType="arraybuffer",J.onload=()=>{J.status==200||J.status==0&&J.response?F(J.response):K()},J.onerror=K,J.send(null)});var Dt,Rt=console.log.bind(console),gr=console.error.bind(console),Mr=Rt,ir=gr;if(Object.assign(v,Ie),Ie=null,we){let m=function(F){try{var K=F.data,J=K.cmd;if(J==="load"){let fe=[];self.onmessage=ze=>fe.push(ze),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ze of fe)m(ze);self.onmessage=m};for(let ze of K.handlers)v[ze]&&!v[ze].proxy||(v[ze]=(...lt)=>{postMessage({Lb:"callHandler",kc:ze,args:lt})},ze=="print"&&(Mr=v[ze]),ze=="printErr"&&(ir=v[ze]));hr=K.wasmMemory,Dn(),Fr(K.wasmModule)}else if(J==="run"){Ym(K.pthread_ptr,0,0,1,0,0),Wm(K.pthread_ptr),bx(),qw(),Zr||(Wy(),Zr=!0);try{xx(K.start_routine,K.arg)}catch(fe){if(fe!="unwind")throw fe}}else J==="cancel"?Il()&&Hf(-1):K.target!=="setimmediate"&&(J==="checkMailbox"?Zr&&Lf():J&&(ir(`worker: received unknown command ${J}`),ir(K)))}catch(fe){throw Gy(),fe}};var Fr,Zr=!1;ir=function(...F){F=F.join(" "),console.error(F)},self.alert=function(...F){postMessage({Lb:"alert",text:F.join(" "),mc:Il()})},v.instantiateWasm=(F,K)=>new Promise(J=>{Fr=fe=>{fe=new WebAssembly.Instance(fe,Uw()),K(fe),J()}}),self.onunhandledrejection=F=>{throw F.reason||F},self.onmessage=m}v.wasmBinary&&(Dt=v.wasmBinary);var hr,Hr,Nt,er,yr,ot,Vt,nr,Wr,pn,kn,rs,si,gi=!1;function Dn(){var m=hr.buffer;v.HEAP8=er=new Int8Array(m),v.HEAP16=ot=new Int16Array(m),v.HEAPU8=yr=new Uint8Array(m),v.HEAPU16=Vt=new Uint16Array(m),v.HEAP32=nr=new Int32Array(m),v.HEAPU32=Wr=new Uint32Array(m),v.HEAPF32=pn=new Float32Array(m),v.HEAPF64=si=new Float64Array(m),v.HEAP64=kn=new BigInt64Array(m),v.HEAPU64=rs=new BigUint64Array(m)}if(!we){if(!((hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof be))throw ir("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");Dn()}var lp=[],Ln=[],Jn=[],$i=0,ns=null;function zf(){if(--$i==0&&ns){var m=ns;ns=null,m()}}function Pl(m){throw ir(m="Aborted("+m+")"),gi=!0,Nt=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),q(m),m}var Im,Rw=m=>m.startsWith("data:application/octet-stream;base64,"),Bw=m=>m.startsWith("file://");function Nw(m){if(m==Im&&Dt)return new Uint8Array(Dt);if(Ae)return Ae(m);throw"both async and sync fetching of the wasm failed"}function jw(m,F,K){return function(J){if(!Dt&&(te||de)){if(typeof fetch=="function"&&!Bw(J))return fetch(J,{credentials:"same-origin"}).then(fe=>{if(!fe.ok)throw`failed to load wasm binary file at '${J}'`;return fe.arrayBuffer()}).catch(()=>Nw(J));if(De)return new Promise((fe,ze)=>{De(J,lt=>fe(new Uint8Array(lt)),ze)})}return Promise.resolve().then(()=>Nw(J))}(m).then(J=>WebAssembly.instantiate(J,F)).then(K,J=>{ir(`failed to asynchronously prepare wasm: ${J}`),Pl(J)})}function Uw(){return{a:{M:vx,za:yx,b:Tx,$:Yw,z:ey,pa:ty,X:ny,Z:iy,qa:oy,na:sy,ga:ay,ma:ly,J:uy,Y:cy,V:dy,oa:py,W:fy,va:kx,D:Sx,P:Ex,O:Px,C:Ax,s:Ix,p:Fx,E:Ox,y:jx,Q:Ux,ta:Vx,ja:Wx,T:Gx,aa:Hx,F:qx,ia:Wm,sa:Kx,u:Xx,B:Zx,o:Jx,m:tM,c:Um,n:rM,k:oM,Aa:sM,r:aM,f:lM,v:uM,l:cM,g:dM,i:pM,j:fM,h:hM,e:mM,da:gM,ea:_M,fa:wM,ba:Ey,ca:Cy,S:yM,d:vM,N:bM,G:xM,K:MM,w:TM,ra:kM,U:SM,t:$y,x:EM,L:CM,R:PM,ya:$M,xa:AM,ka:Fy,la:Oy,_:Lm,A:zy,I:Dy,ha:Ly,H:Ry,a:hr,wa:Dm,ua:jy,q:OM}}}var Fm={849460:(m,F,K,J)=>{if(v===void 0||!v.Fb)return 1;if((m=An(m>>>0)).startsWith("./")&&(m=m.substring(2)),!(m=v.Fb.get(m)))return 2;if(J>>>=0,(F>>>=0)+(K>>>=0)>m.byteLength)return 3;try{return u().set(m.subarray(F,F+K),J>>>0),0}catch{return 4}},849961:()=>{v.Ub()},849992:()=>{v.Vb()},850021:()=>{v.Zb()},850046:m=>v.Tb(m),850079:m=>v.Xb(m),850111:(m,F,K)=>{v.Nb(m,F,K,!0)},850150:(m,F,K)=>{v.Nb(m,F,K)},850183:()=>typeof wasmOffsetConverter<"u",850240:m=>{v.jb("Abs",m,void 0)},850291:m=>{v.jb("Neg",m,void 0)},850342:m=>{v.jb("Floor",m,void 0)},850395:m=>{v.jb("Ceil",m,void 0)},850447:m=>{v.jb("Reciprocal",m,void 0)},850505:m=>{v.jb("Sqrt",m,void 0)},850557:m=>{v.jb("Exp",m,void 0)},850608:m=>{v.jb("Erf",m,void 0)},850659:m=>{v.jb("Sigmoid",m,void 0)},850714:(m,F,K)=>{v.jb("HardSigmoid",m,{alpha:F,beta:K})},850793:m=>{v.jb("Log",m,void 0)},850844:m=>{v.jb("Sin",m,void 0)},850895:m=>{v.jb("Cos",m,void 0)},850946:m=>{v.jb("Tan",m,void 0)},850997:m=>{v.jb("Asin",m,void 0)},851049:m=>{v.jb("Acos",m,void 0)},851101:m=>{v.jb("Atan",m,void 0)},851153:m=>{v.jb("Sinh",m,void 0)},851205:m=>{v.jb("Cosh",m,void 0)},851257:m=>{v.jb("Asinh",m,void 0)},851310:m=>{v.jb("Acosh",m,void 0)},851363:m=>{v.jb("Atanh",m,void 0)},851416:m=>{v.jb("Tanh",m,void 0)},851468:m=>{v.jb("Not",m,void 0)},851519:(m,F,K)=>{v.jb("Clip",m,{min:F,max:K})},851588:m=>{v.jb("Clip",m,void 0)},851640:(m,F)=>{v.jb("Elu",m,{alpha:F})},851698:m=>{v.jb("Relu",m,void 0)},851750:(m,F)=>{v.jb("LeakyRelu",m,{alpha:F})},851814:(m,F)=>{v.jb("ThresholdedRelu",m,{alpha:F})},851884:(m,F)=>{v.jb("Cast",m,{to:F})},851942:m=>{v.jb("Add",m,void 0)},851993:m=>{v.jb("Sub",m,void 0)},852044:m=>{v.jb("Mul",m,void 0)},852095:m=>{v.jb("Div",m,void 0)},852146:m=>{v.jb("Pow",m,void 0)},852197:m=>{v.jb("Equal",m,void 0)},852250:m=>{v.jb("Greater",m,void 0)},852305:m=>{v.jb("GreaterOrEqual",m,void 0)},852367:m=>{v.jb("Less",m,void 0)},852419:m=>{v.jb("LessOrEqual",m,void 0)},852478:(m,F,K,J,fe)=>{v.jb("ReduceMean",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},852637:(m,F,K,J,fe)=>{v.jb("ReduceMax",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},852795:(m,F,K,J,fe)=>{v.jb("ReduceMin",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},852953:(m,F,K,J,fe)=>{v.jb("ReduceProd",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853112:(m,F,K,J,fe)=>{v.jb("ReduceSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853270:(m,F,K,J,fe)=>{v.jb("ReduceL1",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853427:(m,F,K,J,fe)=>{v.jb("ReduceL2",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853584:(m,F,K,J,fe)=>{v.jb("ReduceLogSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853745:(m,F,K,J,fe)=>{v.jb("ReduceSumSquare",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853909:(m,F,K,J,fe)=>{v.jb("ReduceLogSumExp",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},854073:m=>{v.jb("Where",m,void 0)},854126:(m,F,K)=>{v.jb("Transpose",m,{perm:F?Array.from(d().subarray(F>>>0,K>>>0)):[]})},854234:(m,F,K,J)=>{v.jb("DepthToSpace",m,{blocksize:F,mode:An(K),format:J?"NHWC":"NCHW"})},854367:(m,F,K,J)=>{v.jb("DepthToSpace",m,{blocksize:F,mode:An(K),format:J?"NHWC":"NCHW"})},854500:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr)=>{v.jb("ConvTranspose",m,{format:Pt?"NHWC":"NCHW",autoPad:F,dilations:[K],group:J,kernelShape:[fe],pads:[ze,lt],strides:[yt],wIsConst:()=>!!s()[Ft>>>0],outputPadding:Qt?Array.from(d().subarray(Qt>>>0,Or>>>0)):[],outputShape:Br?Array.from(d().subarray(Br>>>0,nt>>>0)):[],activation:An(sr)})},854901:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt)=>{v.jb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:J,kernelShape:Array.from(d().subarray(fe>>>0,2+(fe>>>0)>>>0)),pads:Array.from(d().subarray(ze>>>0,4+(ze>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[Pt>>>0],outputPadding:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],outputShape:Or?Array.from(d().subarray(Or>>>0,Br>>>0)):[],activation:An(nt)})},855466:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr)=>{v.jb("ConvTranspose",m,{format:Pt?"NHWC":"NCHW",autoPad:F,dilations:[K],group:J,kernelShape:[fe],pads:[ze,lt],strides:[yt],wIsConst:()=>!!s()[Ft>>>0],outputPadding:Qt?Array.from(d().subarray(Qt>>>0,Or>>>0)):[],outputShape:Br?Array.from(d().subarray(Br>>>0,nt>>>0)):[],activation:An(sr)})},855867:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt)=>{v.jb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:J,kernelShape:Array.from(d().subarray(fe>>>0,2+(fe>>>0)>>>0)),pads:Array.from(d().subarray(ze>>>0,4+(ze>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[Pt>>>0],outputPadding:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],outputShape:Or?Array.from(d().subarray(Or>>>0,Br>>>0)):[],activation:An(nt)})},856432:(m,F)=>{v.jb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},856523:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("AveragePool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},856807:(m,F)=>{v.jb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},856898:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("AveragePool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},857182:(m,F)=>{v.jb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},857269:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("MaxPool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},857549:(m,F)=>{v.jb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},857636:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("MaxPool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},857916:(m,F,K,J,fe)=>{v.jb("Gemm",m,{alpha:F,beta:K,transA:J,transB:fe})},858020:m=>{v.jb("MatMul",m,void 0)},858074:(m,F,K,J)=>{v.jb("ArgMax",m,{keepDims:!!F,selectLastIndex:!!K,axis:J})},858182:(m,F,K,J)=>{v.jb("ArgMin",m,{keepDims:!!F,selectLastIndex:!!K,axis:J})},858290:(m,F)=>{v.jb("Softmax",m,{axis:F})},858353:(m,F)=>{v.jb("Concat",m,{axis:F})},858413:(m,F,K,J,fe)=>{v.jb("Split",m,{axis:F,numOutputs:K,splitSizes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},858553:m=>{v.jb("Expand",m,void 0)},858607:(m,F)=>{v.jb("Gather",m,{axis:Number(F)})},858678:(m,F)=>{v.jb("GatherElements",m,{axis:Number(F)})},858757:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt)=>{v.jb("Resize",m,{antialias:F,axes:K?Array.from(d().subarray(K>>>0,J>>>0)):[],coordinateTransformMode:An(fe),cubicCoeffA:ze,excludeOutside:lt,extrapolationValue:yt,keepAspectRatioPolicy:An(Pt),mode:An(Ft),nearestMode:An(Qt)})},859103:(m,F,K,J,fe,ze,lt)=>{v.jb("Slice",m,{starts:F?Array.from(d().subarray(F>>>0,K>>>0)):[],ends:J?Array.from(d().subarray(J>>>0,fe>>>0)):[],axes:ze?Array.from(d().subarray(ze>>>0,lt>>>0)):[]})},859319:m=>{v.jb("Tile",m,void 0)},859371:(m,F,K)=>{v.jb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},859485:(m,F,K)=>{v.jb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},859599:m=>{v.jb("Range",m,void 0)},859652:(m,F)=>{v.jb("Einsum",m,{equation:An(F)})},859733:(m,F,K,J,fe)=>{v.jb("Pad",m,{mode:F,value:K,pads:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},859860:(m,F,K,J,fe,ze)=>{v.jb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!fe,trainingMode:!!J,format:ze?"NHWC":"NCHW"})},860029:(m,F,K,J,fe,ze)=>{v.jb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!fe,trainingMode:!!J,format:ze?"NHWC":"NCHW"})},860198:(m,F,K)=>{v.jb("CumSum",m,{exclusive:Number(F),reverse:Number(K)})},860295:(m,F,K,J,fe,ze,lt,yt,Pt)=>{v.jb("Attention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:J,scale:fe,doRotary:ze,qkvHiddenSizes:lt?Array.from(d().subarray(Number(yt)>>>0,Number(yt)+lt>>>0)):[],pastPresentShareBuffer:!!Pt})},860567:m=>{v.jb("BiasAdd",m,void 0)},860622:m=>{v.jb("BiasSplitGelu",m,void 0)},860683:m=>{v.jb("FastGelu",m,void 0)},860739:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("Conv",m,{format:Or?"NHWC":"NCHW",auto_pad:F,dilations:K?Array.from(d().subarray(K>>>0,J>>>0)):[],group:fe,kernel_shape:ze?Array.from(d().subarray(ze>>>0,lt>>>0)):[],pads:yt?Array.from(d().subarray(yt>>>0,Pt>>>0)):[],strides:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],w_is_const:()=>!!s()[Br>>>0],activation:An(nt),activation_params:sr?Array.from(k().subarray(sr>>>0,jr>>>0)):[]})},861235:m=>{v.jb("Gelu",m,void 0)},861287:(m,F,K,J)=>{v.jb("GroupQueryAttention",m,{numHeads:F,kvNumHeads:K,scale:J})},861400:(m,F,K,J)=>{v.jb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!J})},861511:(m,F,K,J)=>{v.jb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!J})},861622:(m,F,K,J,fe,ze)=>{v.jb("MatMulNBits",m,{k:F,n:K,accuracyLevel:J,bits:fe,blockSize:ze})},861749:(m,F,K,J,fe,ze)=>{v.jb("MultiHeadAttention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:J,scale:fe,doRotary:ze})},861908:(m,F)=>{v.jb("QuickGelu",m,{alpha:F})},861972:(m,F,K,J,fe)=>{v.jb("RotaryEmbedding",m,{interleaved:!!F,numHeads:K,rotaryEmbeddingDim:J,scale:fe})},862111:(m,F,K)=>{v.jb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})},862213:m=>{v.Yb(m)},862247:(m,F)=>v.$b(m,F,v.Eb.bc,v.Eb.errors),862359:(m,F,K)=>{v.jb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})}};function yx(m,F,K){return xy(async()=>{await v.Wb(m,F,K)})}function vx(){return typeof wasmOffsetConverter<"u"}function Om(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}var zm=m=>{m.terminate(),m.onmessage=()=>{}},Vw=m=>{is.length==0&&(Xw(),Kw(is[0]));var F=is.pop();if(!F)return 6;Zs.push(F),ro[m.Ab]=F,F.Ab=m.Ab;var K={cmd:"run",start_routine:m.cc,arg:m.Pb,pthread_ptr:m.Ab};return F.postMessage(K,m.ic),0},Ys=0,rn=(m,F,...K)=>{for(var J=2*K.length,fe=eg(),ze=Jm(8*J),lt=ze>>>3,yt=0;yt<K.length;yt++){var Pt=K[yt];typeof Pt=="bigint"?(kn[lt+2*yt]=1n,kn[lt+2*yt+1]=Pt):(kn[lt+2*yt]=0n,$()[lt+2*yt+1>>>0]=Pt)}return m=Hy(m,0,J,ze,F),qf(fe),m};function Dm(m){if(we)return rn(0,1,m);if(Nt=m,!(0<Ys)){for(var F of Zs)zm(F);for(F of is)zm(F);is=[],Zs=[],ro=[],gi=!0}ut(m,new Om(m))}function Ww(m){if(we)return rn(1,0,m);Lm(m)}var Lm=m=>{if(Nt=m,we)throw Ww(m),"unwind";Dm(m)},is=[],Zs=[],Gw=[],ro={},Hw=m=>{var F=m.Ab;delete ro[F],is.push(m),Zs.splice(Zs.indexOf(m),1),m.Ab=0,Zm(F)};function qw(){Gw.forEach(m=>m())}var Kw=m=>new Promise(F=>{m.onmessage=fe=>{var ze=(fe=fe.data).cmd;if(fe.targetThread&&fe.targetThread!=Il()){var lt=ro[fe.targetThread];lt?lt.postMessage(fe,fe.transferList):ir(`Internal error! Worker sent a message "${ze}" to target pthread ${fe.targetThread}, but that thread no longer exists!`)}else ze==="checkMailbox"?Lf():ze==="spawnThread"?Vw(fe):ze==="cleanupThread"?Hw(ro[fe.thread]):ze==="killThread"?(fe=fe.thread,ze=ro[fe],delete ro[fe],zm(ze),Zm(fe),Zs.splice(Zs.indexOf(ze),1),ze.Ab=0):ze==="cancelThread"?ro[fe.thread].postMessage({cmd:"cancel"}):ze==="loaded"?(m.loaded=!0,F(m)):ze==="alert"?alert(`Thread ${fe.threadId}: ${fe.text}`):fe.target==="setimmediate"?m.postMessage(fe):ze==="callHandler"?v[fe.handler](...fe.args):ze&&ir(`worker sent an unknown command ${ze}`)},m.onerror=fe=>{throw ir(`worker sent an error! ${fe.filename}:${fe.lineno}: ${fe.message}`),fe};var K,J=[];for(K of[])v.hasOwnProperty(K)&&J.push(K);m.postMessage({cmd:"load",handlers:J,wasmMemory:hr,wasmModule:Hr})});function Xw(){var m=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});is.push(m)}var Df=m=>{for(;0<m.length;)m.shift()(v)},bx=()=>{var m=Il(),F=x()[m+52>>>2>>>0];m=x()[m+56>>>2>>>0],Ky(F,F-m),qf(F)},xx=(m,F)=>{Ys=0,m=Xy(m,F),0<Ys?Nt=m:Hf(m)};class Mx{constructor(F){this.Ib=F-24}}function Tx(m,F,K){var J=new Mx(m>>>=0);throw F>>>=0,K>>>=0,x()[J.Ib+16>>>2>>>0]=0,x()[J.Ib+4>>>2>>>0]=F,x()[J.Ib+8>>>2>>>0]=K,m}function Qw(m,F,K,J){return we?rn(2,1,m,F,K,J):Yw(m,F,K,J)}function Yw(m,F,K,J){if(m>>>=0,F>>>=0,K>>>=0,J>>>=0,be===void 0)return ir("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var fe=[];return we&&fe.length===0?Qw(m,F,K,J):(m={cc:K,Ab:m,Pb:J,ic:fe},we?(m.Lb="spawnThread",postMessage(m,fe),0):Vw(m))}var Zw=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Jw=(m,F,K)=>{var J=(F>>>=0)+K;for(K=F;m[K]&&!(K>=J);)++K;if(16<K-F&&m.buffer&&Zw)return Zw.decode(m.buffer instanceof be?m.slice(F,K):m.subarray(F,K));for(J="";F<K;){var fe=m[F++];if(128&fe){var ze=63&m[F++];if((224&fe)==192)J+=String.fromCharCode((31&fe)<<6|ze);else{var lt=63&m[F++];65536>(fe=(240&fe)==224?(15&fe)<<12|ze<<6|lt:(7&fe)<<18|ze<<12|lt<<6|63&m[F++])?J+=String.fromCharCode(fe):(fe-=65536,J+=String.fromCharCode(55296|fe>>10,56320|1023&fe))}}else J+=String.fromCharCode(fe)}return J},An=(m,F)=>(m>>>=0)?Jw(u(),m,F):"";function ey(m,F,K){return we?rn(3,1,m,F,K):0}function ty(m,F){if(we)return rn(4,1,m,F)}var Rm=m=>{for(var F=0,K=0;K<m.length;++K){var J=m.charCodeAt(K);127>=J?F++:2047>=J?F+=2:55296<=J&&57343>=J?(F+=4,++K):F+=3}return F},ry=(m,F,K,J)=>{if(!(0<J))return 0;var fe=K>>>=0;J=K+J-1;for(var ze=0;ze<m.length;++ze){var lt=m.charCodeAt(ze);if(55296<=lt&&57343>=lt&&(lt=65536+((1023<)<<10)|1023&m.charCodeAt(++ze)),127>=lt){if(K>=J)break;F[K++>>>0]=lt}else{if(2047>=lt){if(K+1>=J)break;F[K++>>>0]=192|lt>>6}else{if(65535>=lt){if(K+2>=J)break;F[K++>>>0]=224|lt>>12}else{if(K+3>=J)break;F[K++>>>0]=240|lt>>18,F[K++>>>0]=128|lt>>12&63}F[K++>>>0]=128|lt>>6&63}F[K++>>>0]=128|63<}}return F[K>>>0]=0,K-fe},$l=(m,F,K)=>ry(m,u(),F,K);function ny(m,F){if(we)return rn(5,1,m,F)}function iy(m,F,K){if(we)return rn(6,1,m,F,K)}function oy(m,F,K){return we?rn(7,1,m,F,K):0}function sy(m,F){if(we)return rn(8,1,m,F)}function ay(m,F,K){if(we)return rn(9,1,m,F,K)}function ly(m,F,K,J){if(we)return rn(10,1,m,F,K,J)}function uy(m,F,K,J){if(we)return rn(11,1,m,F,K,J)}function cy(m,F,K,J){if(we)return rn(12,1,m,F,K,J)}function dy(m){if(we)return rn(13,1,m)}function py(m,F){if(we)return rn(14,1,m,F)}function fy(m,F,K){if(we)return rn(15,1,m,F,K)}var hy,os,kx=()=>{Pl("")},no=m=>{for(var F="";u()[m>>>0];)F+=hy[u()[m++>>>0]];return F},Bm={},Nm={};function Mo(m,F,K={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(J,fe,ze={}){var lt=fe.name;if(!J)throw new os(`type "${lt}" must have a positive integer typeid pointer`);if(Nm.hasOwnProperty(J)){if(ze.Rb)return;throw new os(`Cannot register type '${lt}' twice`)}Nm[J]=fe,Bm.hasOwnProperty(J)&&(fe=Bm[J],delete Bm[J],fe.forEach(yt=>yt()))}(m,F,K)}var my=(m,F,K)=>{switch(F){case 1:return K?J=>s()[J>>>0]:J=>u()[J>>>0];case 2:return K?J=>c()[J>>>1>>>0]:J=>f()[J>>>1>>>0];case 4:return K?J=>d()[J>>>2>>>0]:J=>x()[J>>>2>>>0];case 8:return K?J=>kn[J>>>3]:J=>rs[J>>>3];default:throw new TypeError(`invalid integer width (${F}): ${m}`)}};function Sx(m,F,K){K>>>=0,Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:J=>J,toWireType:function(J,fe){if(typeof fe!="bigint"&&typeof fe!="number")throw fe=fe===null?"null":(J=typeof fe)=="object"||J==="array"||J==="function"?fe.toString():""+fe,new TypeError(`Cannot convert "${fe}" to ${this.name}`);return typeof fe=="number"&&(fe=BigInt(fe)),fe},argPackAdvance:ss,readValueFromPointer:my(F,K,F.indexOf("u")==-1),Db:null})}var ss=8;function Ex(m,F,K,J){Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:function(fe){return!!fe},toWireType:function(fe,ze){return ze?K:J},argPackAdvance:ss,readValueFromPointer:function(fe){return this.fromWireType(u()[fe>>>0])},Db:null})}var jm=[],To=[];function Um(m){9<(m>>>=0)&&--To[m+1]==0&&(To[m]=void 0,jm.push(m))}var Ai=m=>{if(!m)throw new os("Cannot use deleted val. handle = "+m);return To[m]},Ii=m=>{switch(m){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let F=jm.pop()||To.length;return To[F]=m,To[F+1]=1,F}};function Vm(m){return this.fromWireType(x()[m>>>2>>>0])}var Cx={name:"emscripten::val",fromWireType:m=>{var F=Ai(m);return Um(m),F},toWireType:(m,F)=>Ii(F),argPackAdvance:ss,readValueFromPointer:Vm,Db:null};function Px(m){return Mo(m>>>0,Cx)}var $x=(m,F)=>{switch(F){case 4:return function(K){return this.fromWireType(k()[K>>>2>>>0])};case 8:return function(K){return this.fromWireType($()[K>>>3>>>0])};default:throw new TypeError(`invalid float width (${F}): ${m}`)}};function Ax(m,F,K){K>>>=0,Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:J=>J,toWireType:(J,fe)=>fe,argPackAdvance:ss,readValueFromPointer:$x(F,K),Db:null})}function Ix(m,F,K,J,fe){if(m>>>=0,K>>>=0,F=no(F>>>0),fe===-1&&(fe=4294967295),fe=yt=>yt,J===0){var ze=32-8*K;fe=yt=>yt<<ze>>>ze}var lt=F.includes("unsigned")?function(yt,Pt){return Pt>>>0}:function(yt,Pt){return Pt};Mo(m,{name:F,fromWireType:fe,toWireType:lt,argPackAdvance:ss,readValueFromPointer:my(F,K,J!==0),Db:null})}function Fx(m,F,K){function J(ze){var lt=x()[ze>>>2>>>0];return ze=x()[ze+4>>>2>>>0],new fe(s().buffer,ze,lt)}var fe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][F];Mo(m>>>=0,{name:K=no(K>>>0),fromWireType:J,argPackAdvance:ss,readValueFromPointer:J},{Rb:!0})}function Ox(m,F){m>>>=0;var K=(F=no(F>>>0))==="std::string";Mo(m,{name:F,fromWireType:function(J){var fe=x()[J>>>2>>>0],ze=J+4;if(K)for(var lt=ze,yt=0;yt<=fe;++yt){var Pt=ze+yt;if(yt==fe||u()[Pt>>>0]==0){if(lt=An(lt,Pt-lt),Ft===void 0)var Ft=lt;else Ft+="\0",Ft+=lt;lt=Pt+1}}else{for(Ft=Array(fe),yt=0;yt<fe;++yt)Ft[yt]=String.fromCharCode(u()[ze+yt>>>0]);Ft=Ft.join("")}return oo(J),Ft},toWireType:function(J,fe){fe instanceof ArrayBuffer&&(fe=new Uint8Array(fe));var ze=typeof fe=="string";if(!(ze||fe instanceof Uint8Array||fe instanceof Uint8ClampedArray||fe instanceof Int8Array))throw new os("Cannot pass non-string to std::string");var lt=K&&ze?Rm(fe):fe.length,yt=Gf(4+lt+1),Pt=yt+4;if(x()[yt>>>2>>>0]=lt,K&&ze)$l(fe,Pt,lt+1);else if(ze)for(ze=0;ze<lt;++ze){var Ft=fe.charCodeAt(ze);if(255<Ft)throw oo(Pt),new os("String has UTF-16 code units that do not fit in 8 bits");u()[Pt+ze>>>0]=Ft}else for(ze=0;ze<lt;++ze)u()[Pt+ze>>>0]=fe[ze];return J!==null&&J.push(oo,yt),yt},argPackAdvance:ss,readValueFromPointer:Vm,Db(J){oo(J)}})}var gy=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,zx=(m,F)=>{for(var K=m>>1,J=K+F/2;!(K>=J)&&f()[K>>>0];)++K;if(32<(K<<=1)-m&&gy)return gy.decode(u().slice(m,K));for(K="",J=0;!(J>=F/2);++J){var fe=c()[m+2*J>>>1>>>0];if(fe==0)break;K+=String.fromCharCode(fe)}return K},Dx=(m,F,K)=>{if(K??(K=2147483647),2>K)return 0;var J=F;K=(K-=2)<2*m.length?K/2:m.length;for(var fe=0;fe<K;++fe){var ze=m.charCodeAt(fe);c()[F>>>1>>>0]=ze,F+=2}return c()[F>>>1>>>0]=0,F-J},Lx=m=>2*m.length,Rx=(m,F)=>{for(var K=0,J="";!(K>=F/4);){var fe=d()[m+4*K>>>2>>>0];if(fe==0)break;++K,65536<=fe?(fe-=65536,J+=String.fromCharCode(55296|fe>>10,56320|1023&fe)):J+=String.fromCharCode(fe)}return J},Bx=(m,F,K)=>{if(F>>>=0,K??(K=2147483647),4>K)return 0;var J=F;K=J+K-4;for(var fe=0;fe<m.length;++fe){var ze=m.charCodeAt(fe);if(55296<=ze&&57343>=ze&&(ze=65536+((1023&ze)<<10)|1023&m.charCodeAt(++fe)),d()[F>>>2>>>0]=ze,(F+=4)+4>K)break}return d()[F>>>2>>>0]=0,F-J},Nx=m=>{for(var F=0,K=0;K<m.length;++K){var J=m.charCodeAt(K);55296<=J&&57343>=J&&++K,F+=4}return F};function jx(m,F,K){if(m>>>=0,F>>>=0,K=no(K>>>=0),F===2)var J=zx,fe=Dx,ze=Lx,lt=yt=>f()[yt>>>1>>>0];else F===4&&(J=Rx,fe=Bx,ze=Nx,lt=yt=>x()[yt>>>2>>>0]);Mo(m,{name:K,fromWireType:yt=>{for(var Pt,Ft=x()[yt>>>2>>>0],Qt=yt+4,Or=0;Or<=Ft;++Or){var Br=yt+4+Or*F;Or!=Ft&<(Br)!=0||(Qt=J(Qt,Br-Qt),Pt===void 0?Pt=Qt:(Pt+="\0",Pt+=Qt),Qt=Br+F)}return oo(yt),Pt},toWireType:(yt,Pt)=>{if(typeof Pt!="string")throw new os(`Cannot pass non-string to C++ string type ${K}`);var Ft=ze(Pt),Qt=Gf(4+Ft+F);return x()[Qt>>>2>>>0]=Ft/F,fe(Pt,Qt+4,Ft+F),yt!==null&&yt.push(oo,Qt),Qt},argPackAdvance:ss,readValueFromPointer:Vm,Db(yt){oo(yt)}})}function Ux(m,F){Mo(m>>>=0,{Sb:!0,name:F=no(F>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Vx=()=>1;function Wx(m){Ym(m>>>0,!de,1,!te,131072,!1),qw()}var _y=m=>{if(!gi)try{if(m(),!(0<Ys))try{we?Hf(Nt):Lm(Nt)}catch(F){F instanceof Om||F=="unwind"||ut(1,F)}}catch(F){F instanceof Om||F=="unwind"||ut(1,F)}};function Wm(m){m>>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(d(),m>>>2,m).value.then(Lf),m+=128,Atomics.store(d(),m>>>2,1))}var Lf=()=>{var m=Il();m&&(Wm(m),_y(qy))};function Gx(m,F){(m>>>=0)==F>>>0?setTimeout(Lf):we?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=ro[m])&&m.postMessage({cmd:"checkMailbox"})}var Gm=[];function Hx(m,F,K,J,fe){for(F>>>=0,J/=2,Gm.length=J,K=fe>>>0>>>3,fe=0;fe<J;fe++)Gm[fe]=kn[K+2*fe]?kn[K+2*fe+1]:$()[K+2*fe+1>>>0];return(F?Fm[F]:zM[m])(...Gm)}function qx(m){m>>>=0,we?postMessage({cmd:"cleanupThread",thread:m}):Hw(ro[m])}function Kx(m){}var Hm=(m,F)=>{var K=Nm[m];if(K===void 0)throw m=Vy(m),K=no(m),oo(m),new os(`${F} has unknown type ${K}`);return K},wy=(m,F,K)=>{var J=[];return m=m.toWireType(J,K),J.length&&(x()[F>>>2>>>0]=Ii(J)),m};function Xx(m,F,K){return F>>>=0,K>>>=0,m=Ai(m>>>0),F=Hm(F,"emval::as"),wy(F,K,m)}var Rf=m=>{try{m()}catch(F){Pl(F)}},as=0,io=null,yy=0,Bf=[],vy={},by={},Qx=0,qm=null,Yx=[];function xy(m){return function(F){if(!gi){if(as===0){var K=!1,J=!1;F((fe=0)=>{if(!gi&&(yy=fe,K=!0,J)){as=2,Rf(()=>Zy(io)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),fe=!1;try{var ze=function(){var Pt=d()[io+8>>>2>>>0];return Pt=Kt[by[Pt]],--Ys,Pt()}()}catch(Pt){ze=Pt,fe=!0}var lt=!1;if(!io){var yt=qm;yt&&(qm=null,(fe?yt.reject:yt.resolve)(ze),lt=!0)}if(fe&&!lt)throw ze}}),J=!0,K||(as=1,io=function(){var fe=Gf(65548),ze=fe+12;x()[fe>>>2>>>0]=ze,x()[fe+4>>>2>>>0]=ze+65536,ze=Bf[0];var lt=vy[ze];return lt===void 0&&(lt=Qx++,vy[ze]=lt,by[lt]=ze),ze=lt,d()[fe+8>>>2>>>0]=ze,fe}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Rf(()=>Qy(io)))}else as===2?(as=0,Rf(Jy),oo(io),io=null,Yx.forEach(_y)):Pl(`invalid state: ${as}`);return yy}}(F=>{m().then(F)})}function Zx(m){return m>>>=0,xy(()=>(m=Ai(m)).then(Ii))}var Nf=[];function Jx(m,F,K,J){return K>>>=0,J>>>=0,(m=Nf[m>>>0])(null,F=Ai(F>>>0),K,J)}var eM={},jf=m=>{var F=eM[m];return F===void 0?no(m):F};function tM(m,F,K,J,fe){return K>>>=0,J>>>=0,fe>>>=0,(m=Nf[m>>>0])(F=Ai(F>>>0),F[K=jf(K)],J,fe)}var My=()=>typeof globalThis=="object"?globalThis:Function("return this")();function rM(m){return(m>>>=0)==0?Ii(My()):(m=jf(m),Ii(My()[m]))}var nM=m=>{var F=Nf.length;return Nf.push(m),F},iM=(m,F)=>{for(var K=Array(m),J=0;J<m;++J)K[J]=Hm(x()[F+4*J>>>2>>>0],"parameter "+J);return K},Ty=(m,F)=>Object.defineProperty(F,"name",{value:m});function oM(m,F,K){var J=(F=iM(m,F>>>0)).shift();m--;var fe=`return function (obj, func, destructorsRef, args) { `,ze=0,lt=[];K===0&<.push("obj");for(var yt=["retType"],Pt=[J],Ft=0;Ft<m;++Ft)lt.push("arg"+Ft),yt.push("argType"+Ft),Pt.push(F[Ft]),fe+=` var arg${Ft} = argType${Ft}.readValueFromPointer(args${ze?"+"+ze:""}); `,ze+=F[Ft].argPackAdvance;return fe+=` var rv = ${K===1?"new func":"func.call"}(${lt.join(", ")}); `,J.Sb||(yt.push("emval_returnValue"),Pt.push(wy),fe+=` return emval_returnValue(retType, destructorsRef, rv); `),yt.push(fe+`}; `),m=function(Qt){var Or=Function;if(!(Or instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof Or} which is not a function`);var Br=Ty(Or.name||"unknownFunctionName",function(){});return Br.prototype=Or.prototype,Br=new Br,(Qt=Or.apply(Br,Qt))instanceof Object?Qt:Br}(yt)(...Pt),K=`methodCaller<(${F.map(Qt=>Qt.name).join(", ")}) => ${J.name}>`,nM(Ty(K,m))}function sM(m){return m=jf(m>>>0),Ii(v[m])}function aM(m,F){return F>>>=0,m=Ai(m>>>0),F=Ai(F),Ii(m[F])}function lM(m){9<(m>>>=0)&&(To[m+1]+=1)}function uM(){return Ii([])}function cM(m){m=Ai(m>>>0);for(var F=Array(m.length),K=0;K<m.length;K++)F[K]=m[K];return Ii(F)}function dM(m){return Ii(jf(m>>>0))}function pM(){return Ii({})}function fM(m){for(var F=Ai(m>>>=0);F.length;){var K=F.pop();F.pop()(K)}Um(m)}function hM(m,F,K){F>>>=0,K>>>=0,m=Ai(m>>>0),F=Ai(F),K=Ai(K),m[F]=K}function mM(m,F){return F>>>=0,m=(m=Hm(m>>>0,"_emval_take_value")).readValueFromPointer(F),Ii(m)}function gM(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 Al=m=>m%4==0&&(m%100!=0||m%400==0),ky=[0,31,60,91,121,152,182,213,244,274,305,335],Sy=[0,31,59,90,120,151,181,212,243,273,304,334];function _M(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=(Al(m.getFullYear())?ky:Sy)[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 J=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(K!=J&&m.getTimezoneOffset()==Math.min(J,K)),d()[F+32>>>2>>>0]=m}function wM(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],J=F.getTimezoneOffset(),fe=new Date(F.getFullYear(),6,1).getTimezoneOffset(),ze=new Date(F.getFullYear(),0,1).getTimezoneOffset(),lt=Math.min(ze,fe);return 0>K?d()[m+32>>>2>>>0]=+(fe!=ze&<==J):0<K!=(lt==J)&&(fe=Math.max(ze,fe),F.setTime(F.getTime()+6e4*((0<K?lt:fe)-J))),d()[m+24>>>2>>>0]=F.getDay(),K=(Al(F.getFullYear())?ky:Sy)[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 Ey(m,F,K,J,fe,ze,lt){return we?rn(16,1,m,F,K,J,fe,ze,lt):-52}function Cy(m,F,K,J,fe,ze){if(we)return rn(17,1,m,F,K,J,fe,ze)}function yM(m,F,K,J){m>>>=0,F>>>=0,K>>>=0,J>>>=0;var fe=new Date().getFullYear(),ze=new Date(fe,0,1),lt=new Date(fe,6,1);fe=ze.getTimezoneOffset();var yt=lt.getTimezoneOffset(),Pt=Math.max(fe,yt);x()[m>>>2>>>0]=60*Pt,d()[F>>>2>>>0]=+(fe!=yt),ze=(m=Ft=>Ft.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ze),lt=m(lt),yt<fe?($l(ze,K,17),$l(lt,J,17)):($l(ze,J,17),$l(lt,K,17))}var Km=[],Py=(m,F)=>{Km.length=0;for(var K;K=u()[m++>>>0];){var J=K!=105;F+=(J&=K!=112)&&F%8?4:0,Km.push(K==112?x()[F>>>2>>>0]:K==106?kn[F>>>3]:K==105?d()[F>>>2>>>0]:$()[F>>>3>>>0]),F+=J?8:4}return Km};function vM(m,F,K){return m>>>=0,F=Py(F>>>0,K>>>0),Fm[m](...F)}function bM(m,F,K){return m>>>=0,F=Py(F>>>0,K>>>0),Fm[m](...F)}var xM=()=>{},MM=()=>Date.now();function TM(m,F){return ir(An(m>>>0,F>>>0))}var $y,kM=()=>{throw Ys+=1,"unwind"};function SM(){return 4294901760}$y=()=>performance.timeOrigin+performance.now();var EM=()=>navigator.hardwareConcurrency;function CM(){return Pl("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function PM(m){m>>>=0;var F=u().length;if(m<=F||4294901760<m)return!1;for(var K=1;4>=K;K*=2){var J=F*(1+.2/K);J=Math.min(J,m+100663296);var fe=Math;J=Math.max(m,J);e:{fe=(fe.min.call(fe,4294901760,J+(65536-J%65536)%65536)-hr.buffer.byteLength+65535)/65536;try{hr.grow(fe),Dn();var ze=1;break e}catch{}ze=void 0}if(ze)return!0}return!1}var Uf=()=>(Pl("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),up={},Ay=m=>{m.forEach(F=>{Uf()})};function $M(){var m=Error().stack.toString().split(` `);return m[0]=="Error"&&m.shift(),Ay(m),up.Ob=Uf(),up.ac=m,up.Ob}function AM(m,F,K){if(m>>>=0,F>>>=0,up.Ob==m)var J=up.ac;else(J=Error().stack.toString().split(` `))[0]=="Error"&&J.shift(),Ay(J);for(var fe=3;J[fe]&&Uf()!=m;)++fe;for(m=0;m<K&&J[m+fe];++m)d()[F+4*m>>>2>>>0]=Uf();return m}var Xm,Qm={},Iy=()=>{if(!Xm){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",_:gt};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]}`);Xm=K}return Xm};function Fy(m,F){if(we)return rn(18,1,m,F);m>>>=0,F>>>=0;var K=0;return Iy().forEach((J,fe)=>{var ze=F+K;for(fe=x()[m+4*fe>>>2>>>0]=ze,ze=0;ze<J.length;++ze)s()[fe++>>>0]=J.charCodeAt(ze);s()[fe>>>0]=0,K+=J.length+1}),0}function Oy(m,F){if(we)return rn(19,1,m,F);m>>>=0,F>>>=0;var K=Iy();x()[m>>>2>>>0]=K.length;var J=0;return K.forEach(fe=>J+=fe.length+1),x()[F>>>2>>>0]=J,0}function zy(m){return we?rn(20,1,m):52}function Dy(m,F,K,J){return we?rn(21,1,m,F,K,J):52}function Ly(m,F,K,J){return we?rn(22,1,m,F,K,J):70}var IM=[null,[],[]];function Ry(m,F,K,J){if(we)return rn(23,1,m,F,K,J);F>>>=0,K>>>=0,J>>>=0;for(var fe=0,ze=0;ze<K;ze++){var lt=x()[F>>>2>>>0],yt=x()[F+4>>>2>>>0];F+=8;for(var Pt=0;Pt<yt;Pt++){var Ft=u()[lt+Pt>>>0],Qt=IM[m];Ft===0||Ft===10?((m===1?Mr:ir)(Jw(Qt,0)),Qt.length=0):Qt.push(Ft)}fe+=yt}return x()[J>>>2>>>0]=fe,0}var By=[31,29,31,30,31,30,31,31,30,31,30,31],Ny=[31,28,31,30,31,30,31,31,30,31,30,31],FM=(m,F)=>{s().set(m,F>>>0)};function jy(m,F,K,J){function fe(nt,sr,jr){for(nt=typeof nt=="number"?nt.toString():nt||"";nt.length<sr;)nt=jr[0]+nt;return nt}function ze(nt,sr){return fe(nt,sr,"0")}function lt(nt,sr){function jr(tv){return 0>tv?-1:0<tv?1:0}var Js;return(Js=jr(nt.getFullYear()-sr.getFullYear()))===0&&(Js=jr(nt.getMonth()-sr.getMonth()))===0&&(Js=jr(nt.getDate()-sr.getDate())),Js}function yt(nt){switch(nt.getDay()){case 0:return new Date(nt.getFullYear()-1,11,29);case 1:return nt;case 2:return new Date(nt.getFullYear(),0,3);case 3:return new Date(nt.getFullYear(),0,2);case 4:return new Date(nt.getFullYear(),0,1);case 5:return new Date(nt.getFullYear()-1,11,31);case 6:return new Date(nt.getFullYear()-1,11,30)}}function Pt(nt){var sr=nt.Bb;for(nt=new Date(new Date(nt.Cb+1900,0,1).getTime());0<sr;){var jr=nt.getMonth(),Js=(Al(nt.getFullYear())?By:Ny)[jr];if(!(sr>Js-nt.getDate())){nt.setDate(nt.getDate()+sr);break}sr-=Js-nt.getDate()+1,nt.setDate(1),11>jr?nt.setMonth(jr+1):(nt.setMonth(0),nt.setFullYear(nt.getFullYear()+1))}return jr=new Date(nt.getFullYear()+1,0,4),sr=yt(new Date(nt.getFullYear(),0,4)),jr=yt(jr),0>=lt(sr,nt)?0>=lt(jr,nt)?nt.getFullYear()+1:nt.getFullYear():nt.getFullYear()-1}m>>>=0,F>>>=0,K>>>=0,J>>>=0;var Ft=x()[J+40>>>2>>>0];for(var Qt in J={fc:d()[J>>>2>>>0],ec:d()[J+4>>>2>>>0],Gb:d()[J+8>>>2>>>0],Kb:d()[J+12>>>2>>>0],Hb:d()[J+16>>>2>>>0],Cb:d()[J+20>>>2>>>0],ub:d()[J+24>>>2>>>0],Bb:d()[J+28>>>2>>>0],nc:d()[J+32>>>2>>>0],dc:d()[J+36>>>2>>>0],hc:Ft?An(Ft):""},K=An(K),Ft={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})K=K.replace(new RegExp(Qt,"g"),Ft[Qt]);var Or="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Br="January February March April May June July August September October November December".split(" ");for(Qt in Ft={"%a":nt=>Or[nt.ub].substring(0,3),"%A":nt=>Or[nt.ub],"%b":nt=>Br[nt.Hb].substring(0,3),"%B":nt=>Br[nt.Hb],"%C":nt=>ze((nt.Cb+1900)/100|0,2),"%d":nt=>ze(nt.Kb,2),"%e":nt=>fe(nt.Kb,2," "),"%g":nt=>Pt(nt).toString().substring(2),"%G":Pt,"%H":nt=>ze(nt.Gb,2),"%I":nt=>((nt=nt.Gb)==0?nt=12:12<nt&&(nt-=12),ze(nt,2)),"%j":nt=>{for(var sr=0,jr=0;jr<=nt.Hb-1;sr+=(Al(nt.Cb+1900)?By:Ny)[jr++]);return ze(nt.Kb+sr,3)},"%m":nt=>ze(nt.Hb+1,2),"%M":nt=>ze(nt.ec,2),"%n":()=>` `,"%p":nt=>0<=nt.Gb&&12>nt.Gb?"AM":"PM","%S":nt=>ze(nt.fc,2),"%t":()=>" ","%u":nt=>nt.ub||7,"%U":nt=>ze(Math.floor((nt.Bb+7-nt.ub)/7),2),"%V":nt=>{var sr=Math.floor((nt.Bb+7-(nt.ub+6)%7)/7);if(2>=(nt.ub+371-nt.Bb-2)%7&&sr++,sr)sr==53&&((jr=(nt.ub+371-nt.Bb)%7)==4||jr==3&&Al(nt.Cb)||(sr=1));else{sr=52;var jr=(nt.ub+7-nt.Bb-1)%7;(jr==4||jr==5&&Al(nt.Cb%400-1))&&sr++}return ze(sr,2)},"%w":nt=>nt.ub,"%W":nt=>ze(Math.floor((nt.Bb+7-(nt.ub+6)%7)/7),2),"%y":nt=>(nt.Cb+1900).toString().substring(2),"%Y":nt=>nt.Cb+1900,"%z":nt=>{var sr=0<=(nt=nt.dc);return nt=Math.abs(nt)/60,(sr?"+":"-")+("0000"+(nt/60*100+nt%60)).slice(-4)},"%Z":nt=>nt.hc,"%%":()=>"%"},K=K.replace(/%%/g,"\0\0"),Ft)K.includes(Qt)&&(K=K.replace(new RegExp(Qt,"g"),Ft[Qt](J)));return Qt=function(nt){var sr=Array(Rm(nt)+1);return ry(nt,sr,0,sr.length),sr}(K=K.replace(/\0\0/g,"%")),Qt.length>F?0:(FM(Qt,m),Qt.length-1)}function OM(m,F,K,J){return jy(m>>>0,F>>>0,K>>>0,J>>>0)}we||function(){for(var m=v.numThreads-1;m--;)Xw();lp.unshift(()=>{$i++,function(F){we?F():Promise.all(is.map(Kw)).then(F)}(()=>zf())})}();for(var Uy=Array(256),Vf=0;256>Vf;++Vf)Uy[Vf]=String.fromCharCode(Vf);hy=Uy,os=v.BindingError=class extends Error{constructor(m){super(m),this.name="BindingError"}},v.InternalError=class extends Error{constructor(m){super(m),this.name="InternalError"}},To.push(0,1,void 0,1,null,1,!0,1,!1,1),v.count_emval_handles=()=>To.length/2-5-jm.length;var zM=[Dm,Ww,Qw,ey,ty,ny,iy,oy,sy,ay,ly,uy,cy,dy,py,fy,Ey,Cy,Fy,Oy,zy,Dy,Ly,Ry],Kt=function(){function m(K,J){return Kt=K.exports,Kt=function(){var fe=Kt,ze={};for(let[lt,yt]of Object.entries(fe))ze[lt]=typeof yt=="function"?(...Pt)=>{Bf.push(lt);try{return yt(...Pt)}finally{gi||(Bf.pop(),io&&as===1&&Bf.length===0&&(as=0,Ys+=1,Rf(Yy),typeof Fibers<"u"&&Fibers.oc()))}}:yt;return ze}(),Kt=function(){var fe=Kt,ze=yt=>Pt=>yt(Pt)>>>0,lt=yt=>()=>yt()>>>0;return(fe=Object.assign({},fe)).Ca=ze(fe.Ca),fe.fb=lt(fe.fb),fe.gb=ze(fe.gb),fe.emscripten_main_runtime_thread_id=lt(fe.emscripten_main_runtime_thread_id),fe.sb=ze(fe.sb),fe.tb=lt(fe.tb),fe}(),Gw.push(Kt.ib),Ln.unshift(Kt.Ba),Hr=J,zf(),Kt}var F=Uw();if($i++,v.instantiateWasm)try{return v.instantiateWasm(F,m)}catch(K){ir(`Module.instantiateWasm callback failed with error: ${K}`),q(K)}return Im||(Im=v.locateFile?Rw("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(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(K,J){var fe=Im;return Dt||typeof WebAssembly.instantiateStreaming!="function"||Rw(fe)||Bw(fe)||typeof fetch!="function"?jw(fe,K,J):fetch(fe,{credentials:"same-origin"}).then(ze=>WebAssembly.instantiateStreaming(ze,K).then(J,function(lt){return ir(`wasm streaming compile failed: ${lt}`),ir("falling back to ArrayBuffer instantiation"),jw(fe,K,J)}))}(F,function(K){m(K.instance,K.module)}).catch(q),{}}(),Vy=m=>(Vy=Kt.Ca)(m),Wy=()=>(Wy=Kt.Da)();v._OrtInit=(m,F)=>(v._OrtInit=Kt.Ea)(m,F),v._OrtGetLastError=(m,F)=>(v._OrtGetLastError=Kt.Fa)(m,F),v._OrtCreateSessionOptions=(m,F,K,J,fe,ze,lt,yt,Pt,Ft)=>(v._OrtCreateSessionOptions=Kt.Ga)(m,F,K,J,fe,ze,lt,yt,Pt,Ft),v._OrtAppendExecutionProvider=(m,F)=>(v._OrtAppendExecutionProvider=Kt.Ha)(m,F),v._OrtAddFreeDimensionOverride=(m,F,K)=>(v._OrtAddFreeDimensionOverride=Kt.Ia)(m,F,K),v._OrtAddSessionConfigEntry=(m,F,K)=>(v._OrtAddSessionConfigEntry=Kt.Ja)(m,F,K),v._OrtReleaseSessionOptions=m=>(v._OrtReleaseSessionOptions=Kt.Ka)(m),v._OrtCreateSession=(m,F,K)=>(v._OrtCreateSession=Kt.La)(m,F,K),v._OrtReleaseSession=m=>(v._OrtReleaseSession=Kt.Ma)(m),v._OrtGetInputOutputCount=(m,F,K)=>(v._OrtGetInputOutputCount=Kt.Na)(m,F,K),v._OrtGetInputName=(m,F)=>(v._OrtGetInputName=Kt.Oa)(m,F),v._OrtGetOutputName=(m,F)=>(v._OrtGetOutputName=Kt.Pa)(m,F),v._OrtFree=m=>(v._OrtFree=Kt.Qa)(m),v._OrtCreateTensor=(m,F,K,J,fe,ze)=>(v._OrtCreateTensor=Kt.Ra)(m,F,K,J,fe,ze),v._OrtGetTensorData=(m,F,K,J,fe)=>(v._OrtGetTensorData=Kt.Sa)(m,F,K,J,fe),v._OrtReleaseTensor=m=>(v._OrtReleaseTensor=Kt.Ta)(m),v._OrtCreateRunOptions=(m,F,K,J)=>(v._OrtCreateRunOptions=Kt.Ua)(m,F,K,J),v._OrtAddRunConfigEntry=(m,F,K)=>(v._OrtAddRunConfigEntry=Kt.Va)(m,F,K),v._OrtReleaseRunOptions=m=>(v._OrtReleaseRunOptions=Kt.Wa)(m),v._OrtCreateBinding=m=>(v._OrtCreateBinding=Kt.Xa)(m),v._OrtBindInput=(m,F,K)=>(v._OrtBindInput=Kt.Ya)(m,F,K),v._OrtBindOutput=(m,F,K,J)=>(v._OrtBindOutput=Kt.Za)(m,F,K,J),v._OrtClearBoundOutputs=m=>(v._OrtClearBoundOutputs=Kt._a)(m),v._OrtReleaseBinding=m=>(v._OrtReleaseBinding=Kt.$a)(m),v._OrtRunWithBinding=(m,F,K,J,fe)=>(v._OrtRunWithBinding=Kt.ab)(m,F,K,J,fe),v._OrtRun=(m,F,K,J,fe,ze,lt,yt)=>(v._OrtRun=Kt.bb)(m,F,K,J,fe,ze,lt,yt),v._OrtEndProfiling=m=>(v._OrtEndProfiling=Kt.cb)(m),v._JsepOutput=(m,F,K)=>(v._JsepOutput=Kt.db)(m,F,K),v._JsepGetNodeName=m=>(v._JsepGetNodeName=Kt.eb)(m);var Wf,Il=()=>(Il=Kt.fb)(),Gf=v._malloc=m=>(Gf=v._malloc=Kt.gb)(m),oo=v._free=m=>(oo=v._free=Kt.hb)(m),Ym=(m,F,K,J,fe,ze)=>(Ym=Kt.kb)(m,F,K,J,fe,ze),Gy=()=>(Gy=Kt.lb)(),Hy=(m,F,K,J,fe)=>(Hy=Kt.mb)(m,F,K,J,fe),Zm=m=>(Zm=Kt.nb)(m),Hf=m=>(Hf=Kt.ob)(m),qy=()=>(qy=Kt.pb)(),Ky=(m,F)=>(Ky=Kt.qb)(m,F),qf=m=>(qf=Kt.rb)(m),Jm=m=>(Jm=Kt.sb)(m),eg=()=>(eg=Kt.tb)(),Xy=v.dynCall_ii=(m,F)=>(Xy=v.dynCall_ii=Kt.vb)(m,F),Qy=m=>(Qy=Kt.wb)(m),Yy=()=>(Yy=Kt.xb)(),Zy=m=>(Zy=Kt.yb)(m),Jy=()=>(Jy=Kt.zb)();function ev(){0<$i||(we?(H(v),we||Df(Ln),startWorker(v)):(Df(lp),0<$i||Wf||(Wf=!0,v.calledRun=!0,gi||(we||Df(Ln),H(v),we||Df(Jn)))))}return v.___start_em_js=862461,v.___stop_em_js=862683,v.stackSave=()=>eg(),v.stackRestore=m=>qf(m),v.stackAlloc=m=>Jm(m),v.UTF8ToString=An,v.stringToUTF8=$l,v.lengthBytesUTF8=Rm,ns=function m(){Wf||ev(),Wf||(ns=m)},ev(),oe}),Et=bt,((n=globalThis.self)==null?void 0:n.name)==="em-pthread"&&bt()}),at,Ot,Ut,Xt,Yt,rr,Ht,Pr,Yr=h(()=>{var n,i;ve(),at=import.meta.url??(typeof document<"u"?(n=document.currentScript)==null?void 0:n.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}},Xt=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},Yt=(ft(),y(Re)).default,rr=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ut(at))return[void 0,Yt()];let s=await Xt(at);return[s,Yt(s)]},Ht=(Lt(),y(ht)).default,Pr=async(s,u,c)=>[void 0,Ht]}),$r,mt,$t,Bt,un,Bi,Mi,Gr,wn=h(()=>{Yr(),mt=!1,$t=!1,Bt=!1,un=()=>{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}},Bi=()=>{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}},Mi=async n=>{if(mt)return Promise.resolve();if($t)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bt)throw new Error("previous call to 'initializeWebAssembly()' failed.");$t=!0;let i=n.initTimeout,s=n.numThreads;if(!Bi())throw new Error("WebAssembly SIMD is not supported in the current environment.");let u=un();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."),n.numThreads=s=1);let c=n.wasmPaths,f=typeof c=="string"?c:void 0,d=c==null?void 0:c.mjs,x=(d==null?void 0:d.href)??d,k=c==null?void 0:c.wasm,$=(k==null?void 0:k.href)??k,H=n.wasmBinary,[q,v]=await Pr(x,f,s>1),oe=!1,te=[];if(i>0&&te.push(new Promise(de=>{setTimeout(()=>{oe=!0,de()},i)})),te.push(new Promise((de,we)=>{let be={numThreads:s};H?be.wasmBinary=H:($||f)&&(be.locateFile=(he,De)=>$??(f??De)+he),v(be).then(he=>{$t=!1,mt=!0,$r=he,de(),q&&URL.revokeObjectURL(q)},he=>{$t=!1,Bt=!0,we(he)})})),await Promise.race(te),oe)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Gr=()=>{if(mt&&$r)return $r;throw new Error("WebAssembly is not initialized yet.")}}),Kr,pi,Dr,Ni=h(()=>{wn(),Kr=(n,i)=>{let s=Gr(),u=s.lengthBytesUTF8(n)+1,c=s._malloc(u);return s.stringToUTF8(n,c,u),i.push(c),c},pi=(n,i,s,u)=>{if(typeof n=="object"&&n!==null){if(s.has(n))throw new Error("Circular reference in options");s.add(n)}Object.entries(n).forEach(([c,f])=>{let d=i?i+c:c;if(typeof f=="object")pi(f,d+".",s,u);else if(typeof f=="string"||typeof f=="number")u(d,f.toString());else if(typeof f=="boolean")u(d,f?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof f}`)})},Dr=n=>{let i=Gr(),s=i.stackSave();try{let u=i.stackAlloc(8);i._OrtGetLastError(u,u+4);let c=i.HEAP32[u/4],f=i.HEAPU32[u/4+1],d=f?i.UTF8ToString(f):"";throw new Error(`${n} ERROR_CODE: ${c}, ERROR_MESSAGE: ${d}`)}finally{i.stackRestore(s)}}}),Ti,Cs=h(()=>{wn(),Ni(),Ti=n=>{let i=Gr(),s=0,u=[],c=n||{};try{if((n==null?void 0:n.logSeverityLevel)===void 0)c.logSeverityLevel=2;else if(typeof n.logSeverityLevel!="number"||!Number.isInteger(n.logSeverityLevel)||n.logSeverityLevel<0||n.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${n.logSeverityLevel}`);if((n==null?void 0:n.logVerbosityLevel)===void 0)c.logVerbosityLevel=0;else if(typeof n.logVerbosityLevel!="number"||!Number.isInteger(n.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${n.logVerbosityLevel}`);(n==null?void 0:n.terminate)===void 0&&(c.terminate=!1);let f=0;return(n==null?void 0:n.tag)!==void 0&&(f=Kr(n.tag,u)),s=i._OrtCreateRunOptions(c.logSeverityLevel,c.logVerbosityLevel,!!c.terminate,f),s===0&&Dr("Can't create run options."),(n==null?void 0:n.extra)!==void 0&&pi(n.extra,"",new WeakSet,(d,x)=>{let k=Kr(d,u),$=Kr(x,u);i._OrtAddRunConfigEntry(s,k,$)!==0&&Dr(`Can't set a run config entry: ${d} - ${x}.`)}),[s,u]}catch(f){throw s!==0&&i._OrtReleaseRunOptions(s),u.forEach(d=>i._free(d)),f}}}),Lo,Ro,Bo,No,ji,Ps=h(()=>{wn(),Ni(),Lo=n=>{switch(n){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${n}`)}},Ro=n=>{switch(n){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${n}`)}},Bo=n=>{n.extra||(n.extra={}),n.extra.session||(n.extra.session={});let i=n.extra.session;i.use_ort_model_bytes_directly||(i.use_ort_model_bytes_directly="1"),n.executionProviders&&n.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(n.enableMemPattern=!1)},No=(n,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 x=Kr("deviceType",s),k=Kr(d,s);Gr()._OrtAddSessionConfigEntry(n,x,k)!==0&&Dr(`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 x=Kr("preferredLayout",s),k=Kr(d.preferredLayout,s);Gr()._OrtAddSessionConfigEntry(n,x,k)!==0&&Dr(`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 f=Kr(c,s);Gr()._OrtAppendExecutionProvider(n,f)!==0&&Dr(`Can't append execution provider: ${c}.`)}},ji=n=>{let i=Gr(),s=0,u=[],c=n||{};Bo(c);try{let f=Lo(c.graphOptimizationLevel??"all"),d=Ro(c.executionMode??"sequential"),x=typeof c.logId=="string"?Kr(c.logId,u):0,k=c.logSeverityLevel??2;if(!Number.isInteger(k)||k<0||k>4)throw new Error(`log serverity level is not valid: ${k}`);let $=c.logVerbosityLevel??0;if(!Number.isInteger($)||$<0||$>4)throw new Error(`log verbosity level is not valid: ${$}`);let H=typeof c.optimizedModelFilePath=="string"?Kr(c.optimizedModelFilePath,u):0;if(s=i._OrtCreateSessionOptions(f,!!c.enableCpuMemArena,!!c.enableMemPattern,d,!!c.enableProfiling,0,x,k,$,H),s===0&&Dr("Can't create session options."),c.executionProviders&&No(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 q=Kr("enableGraphCapture",u),v=Kr(c.enableGraphCapture.toString(),u);i._OrtAddSessionConfigEntry(s,q,v)!==0&&Dr(`Can't set a session config entry: 'enableGraphCapture' - ${c.enableGraphCapture}.`)}if(c.freeDimensionOverrides)for(let[q,v]of Object.entries(c.freeDimensionOverrides)){if(typeof q!="string")throw new Error(`free dimension override name must be a string: ${q}`);if(typeof v!="number"||!Number.isInteger(v)||v<0)throw new Error(`free dimension override value must be a non-negative integer: ${v}`);let oe=Kr(q,u);i._OrtAddFreeDimensionOverride(s,oe,v)!==0&&Dr(`Can't set a free dimension override: ${q} - ${v}.`)}return c.extra!==void 0&&pi(c.extra,"",new WeakSet,(q,v)=>{let oe=Kr(q,u),te=Kr(v,u);i._OrtAddSessionConfigEntry(s,oe,te)!==0&&Dr(`Can't set a session config entry: ${q} - ${v}.`)}),[s,u]}catch(f){throw s!==0&&i._OrtReleaseSessionOptions(s),u.forEach(d=>i._free(d)),f}}}),fo,fi,ki,Si,Ji,ho,mo,Zt=h(()=>{fo=n=>{switch(n){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;default:throw new Error(`unsupported data type: ${n}`)}},fi=n=>{switch(n){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";default:throw new Error(`unsupported data type: ${n}`)}},ki=n=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][n],Si=n=>{switch(n){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: ${n}`)}},Ji=n=>{switch(n){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: ${n}`)}},ho=n=>n==="float32"||n==="float16"||n==="int32"||n==="int64"||n==="uint32"||n==="uint8"||n==="bool",mo=n=>{switch(n){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: ${n}`)}}}),eo,jo=h(()=>{ve(),eo=async n=>{if(typeof n=="string"){let i=await fetch(n);if(!i.ok)throw new Error(`failed to load external data file: ${n}`);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: ${n}, no response body.`);let c=i.body.getReader(),f;try{f=new ArrayBuffer(u)}catch(x){if(x instanceof RangeError){let k=Math.ceil(u/65536);f=new WebAssembly.Memory({initial:k,maximum:k}).buffer}else throw x}let d=0;for(;;){let{done:x,value:k}=await c.read();if(x)break;let $=k.byteLength;new Uint8Array(f,d,$).set(k),d+=$}return new Uint8Array(f,0,u)}}else return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n instanceof Uint8Array?n:new Uint8Array(n)}}),Uo,go,Vo,Wo,_o,Go,Vr,jn=h(()=>{Zt(),Uo=["V","I","W","E","F"],go=(n,i)=>{console.log(`[${Uo[n]},${new Date().toISOString()}]${i}`)},_o=(n,i)=>{Vo=n,Wo=i},Go=(n,i)=>{let s=Ji(n),u=Ji(Vo);s>=u&&go(s,typeof i=="function"?i():i)},Vr=(...n)=>{Wo&&Go(...n)}}),Ue,W=h(()=>{Zt(),Ue=(n,i)=>new(Si(i))(n)}),pe=h(()=>{}),Ce,Fe,Oe,rt,Mt,St,kt,It,tr,Ar=h(()=>{jn(),pe(),Ce=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]]),Fe=[],Oe=n=>Math.ceil(n/16)*16,rt=n=>{for(let i=0;i<Fe.length;i++){let s=Fe[i];if(n<=s)return s}return Math.ceil(n/16)*16},Mt=1,St=()=>Mt++,kt=async(n,i,s,u)=>{let c=Oe(s),f=n.device.createBuffer({size:c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=n.getCommandEncoder();n.endComputePass(),d.copyBufferToBuffer(i,0,f,0,c),n.flush(),await f.mapAsync(GPUMapMode.READ);let x=f.getMappedRange();if(u){let k=u();return k.set(new Uint8Array(x,0,s)),k}else return new Uint8Array(x.slice(0,s))}finally{f.destroy()}},It=class{constructor(n){this.backend=n,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 Ce)Fe.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[])}upload(n,i){let s=i.buffer,u=i.byteOffset,c=i.byteLength,f=Oe(c),d=this.storageCache.get(n);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 x=this.backend.device.createBuffer({mappedAtCreation:!0,size:f,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),k=x.getMappedRange();new Uint8Array(k).set(new Uint8Array(s,u,c)),x.unmap();let $=this.backend.getCommandEncoder();this.backend.endComputePass(),$.copyBufferToBuffer(x,0,d.gpuData.buffer,0,f),Vr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${n})`),this.buffersForUploadingPending.push(x)}memcpy(n,i){let s=this.storageCache.get(n);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),f=this.backend.getCommandEncoder();this.backend.endComputePass(),f.copyBufferToBuffer(s.gpuData.buffer,0,u.gpuData.buffer,0,c)}registerExternalBuffer(n,i,s){let u;if(s){if(u=this.externalBuffers.get(s),u===void 0)throw new Error("previous buffer is not registered");if(n===s)return Vr("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=St();return this.storageCache.set(u,{gpuData:{id:u,type:0,buffer:n},originalSize:i}),this.externalBuffers.set(n,u),Vr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${u}, registered.`),u}unregisterExternalBuffer(n){let i=this.externalBuffers.get(n);i!==void 0&&(this.storageCache.delete(i),this.externalBuffers.delete(n),Vr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${i}`))}create(n,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=rt(n),u,c=(i&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,f=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||f){let x=(c?this.freeBuffers:this.freeUniformBuffers).get(s);x?x.length>0?u=x.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:St(),type:0,buffer:u};return this.storageCache.set(d.id,{gpuData:d,originalSize:n}),Vr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${n}) => id=${d.id}`),d}get(n){var i;return(i=this.storageCache.get(n))==null?void 0:i.gpuData}release(n){let i=this.storageCache.get(n);if(!i)throw new Error("releasing data does not exist");return Vr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${n}), gpuDataId=${i.gpuData.id}`),this.storageCache.delete(n),this.buffersPending.push(i.gpuData.buffer),i.originalSize}async download(n,i){let s=this.storageCache.get(n);if(!s)throw new Error("data does not exist");await kt(this.backend,s.gpuData.buffer,s.originalSize,i)}refreshPendingBuffers(){for(let n of this.buffersForUploadingPending)n.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let n of this.buffersPending){let i=Ce.get(n.size);if((n.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(n.size)||[];i===void 0||s.length>=i?n.destroy():s.push(n)}else if((n.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(n.size)||[];i===void 0||s.length>=i?n.destroy():s.push(n)}else n.destroy()}this.buffersPending=[]}else{let n=this.capturedPendingBuffers.get(this.backend.currentSessionId);n||(n=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,n));for(let i of this.buffersPending)n.push(i);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(n=>{n.forEach(i=>{i.destroy()})}),this.freeUniformBuffers.forEach(n=>{n.forEach(i=>{i.destroy()})}),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(n=>{n.forEach(i=>{i.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(n){let i=this.capturedPendingBuffers.get(n);i&&(i.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(n))}},tr=(...n)=>new It(...n)}),or,qt,_r=h(()=>{or=class{constructor(n){Object.assign(this,n)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(n=>`${this[n]}`).join(";")),this.key}},qt=n=>new or(n)}),Cn,gn,ct,Kn,Tr,cn,On,Jt=h(()=>{Cn=class{static calcMatMulShape(n,i){return n[1]!==i[0]?void 0:[n[0],i[1]]}},gn=class{static calcShape(n,i,s=!1){let u=n.length,c=i.length;if(u===0)return i;if(c===0)return n;let f=Math.max(n.length,i.length),d=new Array(f);if(s){if(u<2||c<2)return;let x=Cn.calcMatMulShape([n[u-2],n[u-1]],[i[c-2],i[c-1]]);if(x===void 0)return;[d[f-2],d[f-1]]=x}for(let x=s?3:1;x<=f;x++){let k=u-x<0?1:n[u-x],$=c-x<0?1:i[c-x];if(k!==$&&k>1&&$>1)return;let H=Math.max(k,$);if(k&&$)d[f-x]=Math.max(k,$);else{if(H>1)return;d[f-x]=0}}return d}static isValidBroadcast(n,i){let s=n.length,u=i.length;if(s>u)return!1;for(let c=1;c<=s;c++)if(n[s-c]!==1&&n[s-c]!==i[u-c])return!1;return!0}},ct=class kh{static size(i){return kh.getSizeFromDimensionRange(i,0,i.length)}static convertShape(i,s=4){let u=i.length;if(u===0)return[];let c=new Array(u),f=u-1;for(;f>=0;){if(i[f]%s===0){c[f]=i[f]/s;break}if(s%i[f]!==0)throw new Error("cannot convert shape");c[f]=1,s/=i[f],f--}for(f--;f>=0;f--)c[f]=i[f];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 kh.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 kh.getSizeFromDimensionRange(i,0,s)}static getSizeFromDimensionRange(i,s,u){let c=1;for(let f=s;f<u;f++){if(i[f]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");c*=i[f]}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,f)=>c+s[f]+s[f+u])}static areEqual(i,s){return i.length!==s.length?!1:i.every((u,c)=>u===s[c])}},Kn=class xp{static adjustPoolAttributes(i,s,u,c,f,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 x=0;x<s.length-2;x++)x>=u.length?u.push(s[x+2]):u[x]=s[x+2];for(let x=0;x<u.length;x++)if(x<c.length){if(c[x]<0)throw new Error("strides should be greater than or equal to 1")}else c.push(1);for(let x=0;x<u.length;x++)if(x<f.length){if(f[x]<0)throw new Error("dilations should be greater than or equal to 1")}else f.push(1);for(let x=0;x<u.length*2;x++)if(x<d.length){if(d[x]<0)throw new Error("pad should be greater than or equal to 1")}else d.push(0);for(let x=0;x<u.length;x++){if(u[x]<=0)throw new Error("kernel shapes need to be greater than 0");if(d[x]>=u[x]||d[x+u.length]>=u[x])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(i,s,u,c,f,d,x){if(x){if(f.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 k=0;k<i.length-2;k++)xp.adjustPadAndReturnShape(i[k+(d?1:2)],s[k],u[k],c[k],f,k,k+i.length-2,x)}}static computePoolOutputShape(i,s,u,c,f,d,x){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let k=[s[0],s[1]];return xp.computeShapeHelper(i,s,k,u,c,f,d,x),k}static computeConvOutputShape(i,s,u,c,f,d,x){if(i.length<=0||s.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let k=[i[0],s[0]];return xp.computeShapeHelper(!1,i,k,u,c,f,d,x),k}static computeShapeHelper(i,s,u,c,f,d,x,k){if(i)for(let $=0;$<s.length-2;$++)u.push(1);else for(let $=0;$<s.length-2;$++)u.push(xp.adjustPadAndReturnShape(s[$+2],c[$],f[$],d[$],x,$,$+s.length-2,k))}static adjustPadAndReturnShape(i,s,u,c,f,d,x,k){let $=u*(c-1)+1;if(k&&k!=="NOTSET")switch(k){case"VALID":return f[d]=0,f[x]=0,Math.floor((i-$)/s+1);case"SAME_LOWER":case"SAME_UPPER":if(u!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let H=((i+s-1)/s-1)*s+c-i;return f[d]=Math.floor(k==="SAME_LOWER"?(H+1)/2:H/2),f[x]=H-f[d],Math.floor((i+H-c)/s+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((i+f[d]+f[x]-$)/s+1)}},Tr=class{static getShapeOfGemmResult(n,i,s,u,c){if(n.length!==2||s.length!==2)throw new Error("shape need to be of size 2");let f,d,x;i?(f=n[1],d=n[0]):(f=n[0],d=n[1]);let k=-1;if(u?(x=s[0],k=1):(x=s[1],k=0),s[k]!==d)throw new Error("dimension mismatch");if(f<=0||x<=0||d<=0)throw new Error("invalid shape specified");if(c&&!gn.isValidBroadcast(c,[f,x]))throw new Error("gemm: invalid bias shape for broadcast");return[f,x,d]}},cn=-34028234663852886e22,On=34028234663852886e22}),Un,yn,Sr,Er,At,vr,Lr,Xr,Vn,zt,$s,_t,Gt,ma,ga,cu,wo,ar=h(()=>{Zt(),Jt(),Un=64,yn=(n,i)=>{if(i===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(n){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: ${n}`)}},Sr=(n,i=1)=>{let s=yn(n,i);return typeof s=="string"?s:s[0]},Er=(n,i=1)=>{let s=yn(n,i);return typeof s=="string"?s:s[1]},At=(...n)=>{let i=[];return n.forEach(s=>{s.length!==0&&i.push({type:12,data:s},{type:12,data:ct.computeStrides(s)})}),i},vr=n=>n%4===0?4:n%2===0?2:1,Lr=(n="f32",i,s="0")=>!i||i===1?`${n}(${s})`:`vec${i}<${n}>(${s})`,Xr=(n,i,s)=>n==="f32"?s:i===1?`f32(${s})`:`vec${i}<f32>(${s})`,Vn=(n,i)=>i===4?`(${n}.x + ${n}.y + ${n}.z + ${n}.w)`:i===2?`(${n}.x + ${n}.y)`:i===3?`(${n}.x + ${n}.y + ${n}.z)`:n,zt=(n,i,s,u)=>n.startsWith("uniforms.")&&s>4?typeof i=="string"?u==="f16"?`${n}[(${i}) / 8][(${i}) % 8 / 4][(${i}) % 8 % 4]`:`${n}[(${i}) / 4][(${i}) % 4]`:u==="f16"?`${n}[${Math.floor(i/8)}][${Math.floor(i%8/4)}][${i%8%4}]`:`${n}[${Math.floor(i/4)}][${i%4}]`:s>1?`${n}[${i}]`:n,$s=(n,i,s,u,c)=>{let f=typeof s=="number",d=f?s:s.length,x=[...new Array(d).keys()],k=d<2?"u32":d<=4?`vec${d}<u32>`:`array<u32, ${d}>`,$=yn(i,c),H=typeof $=="string"?$:$[1],q=typeof $=="string"?$:$[0],v={indices:k,value:H,storage:q,tensor:i},oe=ot=>typeof ot=="string"?ot:`${ot}u`,te={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},de=f?"uniforms.":"",we=`${de}${n}_shape`,be=`${de}${n}_strides`,he="";for(let ot=0;ot<d-1;ot++)he+=` let dim${ot} = current / ${zt(be,ot,d)}; let rest${ot} = current % ${zt(be,ot,d)}; indices[${ot}] = dim${ot}; current = rest${ot}; `;he+=`indices[${d-1}] = current;`;let De=d<2?"":` fn o2i_${n}(offset: u32) -> ${v.indices} { var indices: ${v.indices}; var current = offset; ${he} return indices; }`,Ae=ot=>(te.offsetToIndices=!0,d<2?ot:`o2i_${n}(${ot})`),Ie=[];if(d>=2)for(let ot=d-1;ot>=0;ot--)Ie.push(`${zt(be,ot,d)} * (indices[${ot}])`);let gt=d<2?"":` fn i2o_${n}(indices: ${v.indices}) -> u32 { return ${Ie.join("+")}; }`,ut=ot=>(te.indicesToOffset=!0,d<2?ot:`i2o_${n}(${ot})`),vt=(...ot)=>d===0?"0u":`${v.indices}(${ot.map(oe).join(",")})`,Dt=(ot,Vt)=>d<2?`${ot}`:`${zt(ot,Vt,d)}`,Rt=(ot,Vt,nr)=>d<2?`${ot}=${nr};`:`${zt(ot,Vt,d)}=${nr};`,gr={},Mr=(ot,Vt)=>{te.broadcastedIndicesToOffset=!0;let nr=`${Vt.name}broadcastedIndicesTo${n}Offset`;if(nr in gr)return`${nr}(${ot})`;let Wr=[];for(let pn=d-1;pn>=0;pn--){let kn=Vt.indicesGet("outputIndices",pn+Vt.rank-d);Wr.push(`${Dt(be,pn)} * (${kn} % ${Dt(we,pn)})`)}return gr[nr]=`fn ${nr}(outputIndices: ${Vt.type.indices}) -> u32 { return ${Wr.length>0?Wr.join("+"):"0u"}; }`,`${nr}(${ot})`},ir=(ot,Vt)=>(()=>{if(v.storage===v.value)return`${n}[${ot}]=${Vt};`;if(v.storage==="vec2<u32>"&&v.value==="i32")return`${n}[${ot}]=vec2<u32>(u32(${Vt}), select(0u, 0xFFFFFFFFu, ${Vt} < 0));`;if(v.storage==="vec2<u32>"&&v.value==="u32")return`${n}[${ot}]=vec2<u32>(u32(${Vt}), 0u);`;if(v.storage==="u32"&&v.value==="vec4<bool>")return`${n}[${ot}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${Vt}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),Fr=ot=>(()=>{if(v.storage===v.value)return`${n}[${ot}]`;if(v.storage==="vec2<u32>"&&v.value==="i32")return`i32(${n}[${ot}].x)`;if(v.storage==="vec2<u32>"&&v.value==="u32")return`u32(${n}[${ot}].x)`;if(v.storage==="u32"&&v.value==="vec4<bool>")return`vec4<bool>(bool(${n}[${ot}] & 0xFFu), bool(${n}[${ot}] & 0xFF00u), bool(${n}[${ot}] & 0xFF0000u), bool(${n}[${ot}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),Zr=d<2?"":` fn get_${n}ByIndices(indices: ${v.indices}) -> ${H} { return ${Fr(`i2o_${n}(indices)`)}; }`,hr=d<2?"":(()=>{let ot=x.map(nr=>`d${nr}: u32`).join(", "),Vt=x.map(nr=>`d${nr}`).join(", ");return` fn get_${n}(${ot}) -> ${H} { return get_${n}ByIndices(${vt(Vt)}); }`})(),Hr=(...ot)=>{if(ot.length!==d)throw new Error(`indices length must be ${d}`);let Vt=ot.map(oe).join(",");return d===0?Fr("0u"):d===1?Fr(Vt[0]):(te.get=!0,te.getByIndices=!0,te.indicesToOffset=!0,`get_${n}(${Vt})`)},Nt=ot=>d<2?Fr(ot):(te.getByIndices=!0,te.indicesToOffset=!0,`get_${n}ByIndices(${ot})`),er=d<2?"":` fn set_${n}ByIndices(indices: ${v.indices}, value: ${H}) { ${ir(`i2o_${n}(indices)`,"value")} }`,yr=d<2?"":(()=>{let ot=x.map(nr=>`d${nr}: u32`).join(", "),Vt=x.map(nr=>`d${nr}`).join(", ");return` fn set_${n}(${ot}, value: ${H}) { set_${n}ByIndices(${vt(Vt)}, value); }`})();return{impl:()=>{let ot=[],Vt=!1;return te.offsetToIndices&&(ot.push(De),Vt=!0),te.indicesToOffset&&(ot.push(gt),Vt=!0),te.broadcastedIndicesToOffset&&(Object.values(gr).forEach(nr=>ot.push(nr)),Vt=!0),te.set&&(ot.push(yr),Vt=!0),te.setByIndices&&(ot.push(er),Vt=!0),te.get&&(ot.push(hr),Vt=!0),te.getByIndices&&(ot.push(Zr),Vt=!0),!f&&Vt&&ot.unshift(`const ${we} = ${v.indices}(${s.join(",")});`,`const ${be} = ${v.indices}(${ct.computeStrides(s).join(",")});`),ot.join(` `)},type:v,offsetToIndices:Ae,indicesToOffset:ut,broadcastedIndicesToOffset:Mr,indices:vt,indicesGet:Dt,indicesSet:Rt,set:(...ot)=>{if(ot.length!==d+1)throw new Error(`indices length must be ${d}`);let Vt=ot[d];if(typeof Vt!="string")throw new Error("value must be string");let nr=ot.slice(0,d).map(oe).join(",");return d===0?ir("0u",Vt):d===1?ir(nr[0],Vt):(te.set=!0,te.setByIndices=!0,te.indicesToOffset=!0,`set_${n}(${nr}, ${Vt})`)},setByOffset:ir,setByIndices:(ot,Vt)=>d<2?ir(ot,Vt):(te.setByIndices=!0,te.indicesToOffset=!0,`set_${n}ByIndices(${ot}, ${Vt});`),get:Hr,getByOffset:Fr,getByIndices:Nt,usage:u,name:n,strides:be,shape:we,rank:d}},_t=(n,i,s,u=1)=>$s(n,i,s,"input",u),Gt=(n,i,s,u=1)=>$s(n,i,s,"output",u),ma=(n,i,s,u=1)=>$s(n,i,s,"internal",u),ga=class{constructor(n,i){this.normalizedDispatchGroup=n,this.limits=i,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(n){return`if (global_idx >= ${typeof n=="number"?`${n}u`:n}) { return; }`}mainStart(n=Un){let i=typeof n=="number"?n:n[0],s=typeof n=="number"?1:n[1],u=typeof n=="number"?1:n[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,f=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(${f}) { ${d} `}appendVariableUniforms(n){n.rank!==0&&(n.shape.startsWith("uniforms.")&&this.uniforms.push({name:n.shape.replace("uniforms.",""),type:"u32",length:n.rank}),n.strides.startsWith("uniforms.")&&this.uniforms.push({name:n.strides.replace("uniforms.",""),type:"u32",length:n.rank}))}declareVariable(n,i){if(n.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(n),this.appendVariableUniforms(n);let s=n.usage==="input"?"read":"read_write",u=n.type.storage;return`@group(0) @binding(${i}) var<storage, ${s}> ${n.name}: array<${u}>;`}declareVariables(...n){return n.map(i=>this.declareVariable(i,this.variableIndex++)).join(` `)}registerInternalVariable(n){if(n.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(n),this.appendVariableUniforms(n)}registerInternalVariables(...n){return n.forEach(i=>this.registerInternalVariable(i)),this}registerUniform(n,i,s=1){return this.uniforms.push({name:n,type:i,length:s}),this}registerUniforms(n){return this.uniforms=this.uniforms.concat(n),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let n=[];for(let{name:i,type:s,length:u}of this.uniforms)if(u&&u>4)s==="f16"?n.push(`@align(16) ${i}:array<mat2x4<${s}>, ${Math.ceil(u/8)}>`):n.push(`${i}:array<vec4<${s}>, ${Math.ceil(u/4)}>`);else{let c=u==null||u===1?s:`vec${u}<${s}>`;n.push(`${i}:${c}`)}return` struct Uniforms { ${n.join(", ")} }; @group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(n=>n.impl()).join(` `)+this.internalVariables.map(n=>n.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let n=i=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(i)];return this.uniforms.map(i=>[n(i.type),i.length??1])}},cu=(n,i)=>new ga(n,i),wo=(n,i)=>{let s=n.length,u=[];for(let c=0;c<s;c++){let f=s-1-c,d=n[f]||1;(i[i.length-1-c]||1)>1&&d===1&&u.unshift(f)}return u}}),du,_a,Ho,pu,hi,fu,wa,yo=h(()=>{Zt(),Jt(),_r(),ar(),du=n=>{if(!n||n.length!==1)throw new Error("Transpose requires 1 input.")},_a=(n,i)=>i&&i.length!==n?[...new Array(n).keys()].reverse():i,Ho=(n,i)=>ct.sortBasedOnPerm(n,_a(n.length,i)),pu=(n,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`);for(let f=0;f<i;++f)c.push(s.indicesSet("a",n[f],`i[${f}]`));return c.push("return a;}"),c.join(` `)},hi=(n,i)=>{let s=n.dataType,u=n.dims.length,c=_a(u,i),f=Ho(n.dims,c),d=Gt("output",s,f.length),x=_t("a",s,u),k;if(c.length===2&&c[0]===1&&c[1]===0){let $=d.type.value,H=[16,16,1];k=q=>` ${q.registerUniform("output_size","u32").declareVariables(x,d)} var<workgroup> tile : array<array<${$}, ${H[0]+1}>, ${H[0]}>; ${q.mainStart(H)} var x = workgroup_id.x * ${H[0]}u + local_id.x; var y = workgroup_id.y * ${H[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] = ${x.getByOffset("y * width + x")}; } workgroupBarrier(); x = workgroup_id.y * ${H[0]}u + local_id.x; y = workgroup_id.x * ${H[0]}u + local_id.y; if (x < height && y < width) { ${d.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} } }`}else k=$=>` ${$.registerUniform("output_size","u32").declareVariables(x,d)} ${pu(c,u,x,d)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${d.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${d.setByOffset("global_idx",x.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:$=>{let H=ct.size(f);return{outputs:[{dims:f,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:[{type:12,data:H},...At($[0].dims,f)]}},getShaderSource:k}},fu=(n,i)=>{du(n.inputs),n.compute(hi(n.inputs[0],i.perm))},wa=n=>qt({perm:n.perm})}),hu,mu,gu,_u,ya,wu,yu,va,vu,bu,Xn,xu,Mu,ba,Tu,ku,xa,Su,Eu,Ma,Cu,rf=h(()=>{Zt(),Jt(),ar(),$a(),yo(),hu={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"},mu={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"},gu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},_u={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ya=(n,i)=>{let s=[];for(let u=i-n;u<i;++u)s.push(u);return s},wu=(n,i)=>{let s=[],u=n.length;for(let f=0;f<u;f++)i.indexOf(f)===-1&&s.push(n[f]);let c=i.map(f=>n[f]);return[s,c]},yu=(n,i)=>{let s=n.length+i.length,u=[],c=0;for(let f=0;f<s;f++)i.indexOf(f)===-1?u.push(n[c++]):u.push(1);return u},va=(n,i)=>{for(let s=0;s<n.length;++s)if(n[n.length-s-1]!==i-1-s)return!1;return!0},vu=(n,i)=>{let s=[];if(!va(n,i)){for(let u=0;u<i;++u)n.indexOf(u)===-1&&s.push(u);n.forEach(u=>s.push(u))}return s},bu=(n,i,s,u,c,f,d)=>{let x=s[0].dims,k=ct.size(f),$=ct.size(d),H=_t("_A",s[0].dataType,x),q=Gt("output",c,f),v=32,oe=` var<workgroup> aBestValues : array<f32, ${v}>; `;return{name:n,shaderCache:i,getShaderSource:te=>` ${te.registerUniform("reduceSize","u32").declareVariables(H,q)} ${oe} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${te.mainStart(v)} let outputIndex = global_idx / ${v}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${gu[u]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${v}) { let candidate = f32(${H.getByOffset("offset + k")}); bestValue = ${hu[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 = ${mu[u]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${q.setByOffset("outputIndex",`${u==="mean"?`${q.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${q.type.storage}(${_u[u]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:f,dataType:c}],dispatchGroup:{x:k},programUniforms:[{type:12,data:$}]})}},Xn=(n,i,s,u)=>{let c=n.inputs.length===1?s:Is(n.inputs,s),f=c.axes;f.length===0&&!c.noopWithEmptyAxes&&(f=n.inputs[0].dims.map((oe,te)=>te));let d=ct.normalizeAxes(f,n.inputs[0].dims.length),x=d,k=n.inputs[0],$=vu(x,n.inputs[0].dims.length);$.length>0&&(k=n.compute(hi(n.inputs[0],$),{inputs:[0],outputs:[-1]})[0],x=ya(x.length,k.dims.length));let[H,q]=wu(k.dims,x),v=H;c.keepDims&&(v=yu(H,d)),n.compute(bu(i,{hint:c.cacheKey,inputDependencies:["type"]},[k],u,n.inputs[0].dataType,v,q),{inputs:[k]})},xu=(n,i)=>{Xn(n,"ReduceMeanShared",i,"mean")},Mu=(n,i)=>{Xn(n,"ReduceL1Shared",i,"l1")},ba=(n,i)=>{Xn(n,"ReduceL2Shared",i,"l2")},Tu=(n,i)=>{Xn(n,"ReduceLogSumExpShared",i,"logSumExp")},ku=(n,i)=>{Xn(n,"ReduceMaxShared",i,"max")},xa=(n,i)=>{Xn(n,"ReduceMinShared",i,"min")},Su=(n,i)=>{Xn(n,"ReduceProdShared",i,"prod")},Eu=(n,i)=>{Xn(n,"ReduceSumShared",i,"sum")},Ma=(n,i)=>{Xn(n,"ReduceSumSquareShared",i,"sumSquare")},Cu=(n,i)=>{Xn(n,"ReduceLogSumShared",i,"logSum")}}),Qn,Pu,As,Is,ii,$u,Ta,Au,Iu,ka,Fu,Ou,Sa,zu,Du,Yn,Lu,Ru,Ea,Bu,Nu,Ca,ju,Uu,Pa,Vu,$a=h(()=>{Zt(),Jt(),_r(),ar(),rf(),Qn=n=>{if(!n||n.length===0||n.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(n.length===2&&n[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Pu=n=>["","",`var value = ${n.getByIndices("input_indices")};`,""],As=(n,i,s,u,c,f,d=!1,x=!1)=>{let k=[],$=s[0].dims,H=$.length,q=ct.normalizeAxes(c,H),v=!x&&q.length===0;$.forEach((de,we)=>{v||q.indexOf(we)>=0?d&&k.push(1):k.push(de)});let oe=k.length,te=ct.size(k);return{name:n,shaderCache:i,getShaderSource:de=>{let we=[],be=_t("_A",s[0].dataType,H),he=Gt("output",f,oe),De=u(be,he,q),Ae=De[2];for(let Ie=0,gt=0;Ie<H;Ie++)v||q.indexOf(Ie)>=0?(d&>++,Ae=`for(var j${Ie}: u32 = 0; j${Ie} < ${$[Ie]}; j${Ie}++) { ${De[2].includes("last_index")?`let last_index = j${Ie};`:""} ${be.indicesSet("input_indices",Ie,`j${Ie}`)} ${Ae} }`):(we.push(`${be.indicesSet("input_indices",Ie,he.indicesGet("output_indices",gt))};`),gt++);return` ${de.registerUniform("output_size","u32").declareVariables(be,he)} ${de.mainStart()} ${de.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${be.type.indices}; let output_indices = ${he.offsetToIndices("global_idx")}; ${we.join(` `)} ${De[0]} // init ops for reduce max/min ${De[1]} ${Ae} ${De[3]} ${De.length===4?he.setByOffset("global_idx","value"):De.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:k,dataType:f}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:[{type:12,data:te},...At($,k)]})}},Is=(n,i)=>{let s=[];return n[1].dims[0]>0&&n[1].getBigInt64Array().forEach(u=>s.push(Number(u))),qt({axes:s,keepDims:i.keepDims,noopWithEmptyAxes:i.noopWithEmptyAxes})},ii=(n,i,s,u)=>{let c=n.inputs,f=c.length===1?s:Is(c,s);n.compute(As(i,{hint:f.cacheKey,inputDependencies:["rank"]},[c[0]],f.noopWithEmptyAxes&&f.axes.length===0?Pu:u,f.axes,c[0].dataType,f.keepDims,f.noopWithEmptyAxes),{inputs:[0]})},$u=(n,i)=>{Qn(n.inputs),ii(n,"ReduceLogSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Ta=(n,i)=>{Qn(n.inputs),ii(n,"ReduceL1",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Au=(n,i)=>{Qn(n.inputs),ii(n,"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);"])},Iu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceLogSumExp",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ka=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMax",i,(s,u,c)=>{let f=[];for(let d=0;d<s.rank;d++)(c.indexOf(d)>=0||c.length===0)&&f.push(s.indicesSet("input_indices",d,0));return[`${f.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Fu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMean",i,(s,u,c)=>{let f=1;for(let d=0;d<s.rank;d++)(c.indexOf(d)>=0||c.length===0)&&(f*=n.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${u.type.value}(sum / ${f});`]})},Ou=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMin",i,(s,u,c)=>{let f=[];for(let d=0;d<s.rank;d++)(c.indexOf(d)>=0||c.length===0)&&f.push(`input_indices[${d}] = 0;`);return[`${f.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Sa=(n,i)=>{Qn(n.inputs),ii(n,"ReduceProd",i,(s,u)=>[`var value = ${u.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},zu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Du=(n,i)=>{Qn(n.inputs),ii(n,"ReduceSumSquare",i,(s,u)=>[`var t = ${u.type.value}(0); var value = ${u.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Yn=(n,i,s)=>{if(i.length===0)return s;let u=1,c=1;for(let f=0;f<i.length;f++)i.indexOf(f)===-1?u*=n[f]:c*=n[f];return c<32&&u>1024},Lu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Fu(n,i):xu(n,i)},Ru=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Ta(n,i):Mu(n,i)},Ea=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Au(n,i):ba(n,i)},Bu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Iu(n,i):Tu(n,i)},Nu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ka(n,i):ku(n,i)},Ca=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Ou(n,i):xa(n,i)},ju=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Sa(n,i):Su(n,i)},Uu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?zu(n,i):Eu(n,i)},Pa=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Du(n,i):Ma(n,i)},Vu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?$u(n,i):Cu(n,i)}}),Fs,Wu,Gu,Os,nf=h(()=>{Zt(),_r(),$a(),Fs=n=>{if(!n||n.length===0||n.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(n[0].dataType!==1)throw new Error("Invalid input type.")},Wu=(n,i)=>{Fs(n.inputs);let s=(u,c,f)=>{let d=[];for(let x=0;x<u.rank;x++)(f.indexOf(x)>=0||f.length===0)&&d.push(`input_indices[${x}] = 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")]};n.compute(As("ArgMin",{hint:i.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},Gu=(n,i)=>{Fs(n.inputs);let s=(u,c,f)=>{let d=[];for(let x=0;x<u.rank;x++)(f.indexOf(x)>=0||f.length===0)&&d.push(`input_indices[${x}] = 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")]};n.compute(As("argMax",{hint:i.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},Os=n=>qt(n)}),Hu,Aa,qu,Ku,vo,Xu,Qu,zs=h(()=>{Zt(),pe(),ar(),Hu=(n,i)=>{let s=n[0],u=n[1],c=n[2],f=n[3],d=n[4],x=n[5];if(d&&x)throw new Error("Attention cannot have both past and relative_position_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let k=s.dims[0],$=s.dims[1],H=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]!==H)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 q=c.dims[0]/3,v=q,oe=v;if(i.qkvHiddenSizes.length>0){if(i.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let De of i.qkvHiddenSizes)if(De%i.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");q=i.qkvHiddenSizes[0],v=i.qkvHiddenSizes[1],oe=i.qkvHiddenSizes[2]}let te=$;if(q!==v)throw new Error("qkv_hidden_sizes first element should be same as the second");if(c.dims[0]!==q+v+oe)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let de=0;if(d){if(v!==oe)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]!==k)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||(de=d.dims[3])}let we=te+de,be=-1,he=0;if(f)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");return{batchSize:k,sequenceLength:$,pastSequenceLength:de,kvSequenceLength:te,totalSequenceLength:we,maxSequenceLength:be,inputHiddenSize:H,hiddenSize:q,vHiddenSize:oe,headSize:Math.floor(q/i.numHeads),vHeadSize:Math.floor(oe/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:he,scale:i.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Aa=(n,i,s,u)=>{let c=vr(u),f=64,d=u/c;d<f?f=1:d/8<64&&(f=Math.ceil(d/8));let x=Math.ceil(u/c/f),k=[{type:i.dataType,data:1/u},{type:12,data:d},{type:12,data:x}],$=Sr(i.dataType,c),H=Er(1,c),q=v=>{let oe=Gt("x",i.dataType,i.dims,c),te=[{name:"d_inv",type:Er(i.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var<workgroup> thread_max: array<f32, ${f}>; var<workgroup> thread_sum: array<f32, ${f}>; ${v.registerUniforms(te).declareVariables(oe)} ${v.mainStart([f,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = workgroup_id.x * uniforms.d_comp + local_offset; var thread_max_vector = ${H}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${H}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(c){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: ${c}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${f}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${H}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${H}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(c){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: ${c}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${f}; 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] = ${oe.type.value}(uniforms.d_inv); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${H}(x[offset + i]); x[offset + i] = ${oe.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${f};${$};${c}`},getShaderSource:q,getRunData:()=>({outputs:[],dispatchGroup:{x:s},programUniforms:k})}},qu=(n,i,s,u,c,f,d,x)=>{let k=x+f.kvSequenceLength,$=[f.batchSize,f.numHeads,f.sequenceLength,k],H=f.kvNumHeads===void 0&&n.outputCount>1,q=H?[f.batchSize,f.numHeads,k,f.headSize]:void 0,v=d.scale===0?1/Math.sqrt(f.headSize):d.scale,oe=vr(f.headSize),te=f.headSize/oe,de=12,we={x:Math.ceil(k/de),y:Math.ceil(f.sequenceLength/de),z:f.batchSize*f.numHeads},be=[{type:12,data:f.sequenceLength},{type:12,data:te},{type:12,data:k},{type:12,data:f.numHeads},{type:1,data:v},{type:12,data:x},{type:12,data:f.kvSequenceLength}],he=["type","type"];u&&he.push("type"),c&&he.push("type");let De=[{dims:$,dataType:i.dataType,gpuDataType:0}];H&&De.push({dims:q,dataType:i.dataType,gpuDataType:0});let Ae=Ie=>{let gt=_t("q",i.dataType,i.dims,oe),ut=_t("key",s.dataType,s.dims,oe),vt=[gt,ut];if(u){let ir=_t("past_key",u.dataType,u.dims,oe);vt.push(ir)}c&&vt.push(_t("relative_position_bias",c.dataType,c.dims));let Dt=Gt("output",i.dataType,$),Rt=[Dt];H&&Rt.push(Gt("present_key",i.dataType,q,oe));let gr=Er(1,oe),Mr=[{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 = ${de}u; var<workgroup> tileQ: array<${gt.type.storage}, ${de*de}>; var<workgroup> tileK: array<${gt.type.storage}, ${de*de}>; ${Ie.registerUniforms(Mr).declareVariables(...vt,...Rt)} ${Ie.mainStart([de,de,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; ${u&&H?` 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;`} ${H?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${gr}(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; ${u&&H?` 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];"} ${H?"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 += ${gr}(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(oe){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: ${oe}`)}})()}; output[outputIdx] = ${Dt.type.value} (sum * uniforms.alpha) + ${c?"relative_position_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${oe};${c!==void 0};${u!==void 0};${n.outputCount}`,inputDependencies:he},getRunData:()=>({outputs:De,dispatchGroup:we,programUniforms:be}),getShaderSource:Ae}},Ku=(n,i,s,u,c,f)=>{let d=f+c.kvSequenceLength,x=c.nReps?c.nReps:1,k=c.vHiddenSize*x,$=c.kvNumHeads==null&&n.outputCount>1,H=$?[c.batchSize,c.numHeads,d,c.headSize]:void 0,q=[c.batchSize,c.sequenceLength,k],v=12,oe={x:Math.ceil(c.vHeadSize/v),y:Math.ceil(c.sequenceLength/v),z:c.batchSize*c.numHeads},te=[{type:12,data:c.sequenceLength},{type:12,data:d},{type:12,data:c.vHeadSize},{type:12,data:c.numHeads},{type:12,data:k},{type:12,data:f},{type:12,data:c.kvSequenceLength}],de=u?["type","type","type"]:["type","type"],we=[{dims:q,dataType:i.dataType,gpuDataType:0}];$&&we.push({dims:H,dataType:i.dataType,gpuDataType:0});let be=he=>{let De=_t("probs",i.dataType,i.dims),Ae=_t("v",s.dataType,s.dims),Ie=[De,Ae];u&&Ie.push(_t("past_value",u.dataType,u.dims));let gt=[Gt("output",i.dataType,q)];$&>.push(Gt("present_value",i.dataType,H));let ut=[{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<${De.type.value}, ${v*v}>; var<workgroup> tileK: array<${De.type.value}, ${v*v}>; ${he.registerUniforms(ut).declareVariables(...Ie,...gt)} ${he.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; ${u&&$?` 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; `} ${$?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${De.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; ${u&&$?` 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]; `} ${$?"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};${n.outputCount}`,inputDependencies:de},getRunData:()=>({outputs:we,dispatchGroup:oe,programUniforms:te}),getShaderSource:be}},vo=(n,i,s,u,c,f,d,x,k,$,H)=>{let q=n.outputCount,v=$.kvNumHeads!==void 0||q>1?$.pastSequenceLength:0,oe=v+$.kvSequenceLength,te=$.kvNumHeads===void 0&&q>1&&d?[i,s,d]:[i,s];k&&te.push(k);let de=n.compute(qu(n,i,s,q>1?d:void 0,k,$,H,v),{inputs:te,outputs:$.kvNumHeads===void 0&&q>1?[-1,1]:[-1]})[0];n.compute(Aa(n,de,$.batchSize*$.numHeads*$.sequenceLength,oe),{inputs:[de],outputs:[]});let we=$.kvNumHeads===void 0&&q>1&&x?[de,u,x]:[de,u];n.compute(Ku(n,de,u,q>1&&x?x:void 0,$,v),{inputs:we,outputs:$.kvNumHeads===void 0&&q>1?[0,2]:[0]})},Xu=(n,i)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.headSize],u=i.sequenceLength,c=i.inputHiddenSize,f=i.headSize,d=12,x={x:Math.ceil(i.headSize/d),y:Math.ceil(i.sequenceLength/d),z:i.batchSize*i.numHeads},k=[n.inputs[0],n.inputs[1],n.inputs[2]],$=[{type:12,data:u},{type:12,data:c},{type:12,data:f},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:i.hiddenSize},{type:12,data:i.hiddenSize+i.hiddenSize+i.vHiddenSize}],H=q=>{let v=Gt("output_q",k[0].dataType,s),oe=Gt("output_k",k[0].dataType,s),te=Gt("output_v",k[0].dataType,s),de=_t("input",k[0].dataType,k[0].dims),we=_t("weight",k[1].dataType,k[1].dims),be=_t("bias",k[2].dataType,k[2].dims),he=de.type.storage,De=[{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}>; ${q.registerUniforms(De).declareVariables(de,we,be,v,oe,te)} ${q.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 n.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:s,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:n.inputs[0].dataType,gpuDataType:0}],dispatchGroup:x,programUniforms:$}),getShaderSource:H},{inputs:k,outputs:[-1,-1,-1]})},Qu=(n,i)=>{let s=Hu(n.inputs,i),[u,c,f]=Xu(n,s);return vo(n,u,c,f,n.inputs[4],void 0,void 0,void 0,n.inputs[5],s,i)}}),Yu,Zu,Ju,ec,tc=h(()=>{Z(),Zt(),Jt(),_r(),ar(),Yu=(n,i)=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(u,c,f)=>{let d=c.length;if(d!==u.length)throw new Error(`${f}: num dimensions != ${d}`);c.forEach((x,k)=>{if(x!==u[k])throw new Error(`${f}: dim[${k}] do not match`)})};if(n[0].dims.length>1){let u=i.format==="NHWC"?i.spatial?n[0].dims.slice(-1):n[0].dims.slice(-1).concat(n[0].dims.slice(1,n[0].dims.length-1)):n[0].dims.slice(1,i.spatial?2:void 0);s(n[1].dims,u,"Invalid input scale"),s(n[2].dims,u,"Invalid input B"),s(n[3].dims,u,"Invalid input mean"),s(n[4].dims,u,"Invalid input var")}else s(n[1].dims,[1],"Invalid input scale"),s(n[2].dims,[1],"Invalid input B"),s(n[3].dims,[1],"Invalid input mean"),s(n[4].dims,[1],"Invalid input var")},Zu=(n,i)=>{let{epsilon:s,spatial:u,format:c}=i,f=n[0].dims,d=u?vr(f[f.length-1]):1,x=c==="NHWC"&&f.length>1?d:1,k=ct.size(f)/d,$=u,H=$?f.length:f,q=_t("x",n[0].dataType,n[0].dims,d),v=_t("scale",n[1].dataType,n[1].dims,x),oe=_t("bias",n[2].dataType,n[2].dims,x),te=_t("inputMean",n[3].dataType,n[3].dims,x),de=_t("inputVar",n[4].dataType,n[4].dims,x),we=Gt("y",n[0].dataType,H,d),be=()=>{let De="";if(u)De=`let cOffset = ${f.length===1?"0u":c==="NHWC"?`outputIndices[${f.length-1}] / ${d}`:"outputIndices[1]"};`;else if(c==="NCHW")De=` ${we.indicesSet("outputIndices","0","0")} let cOffset = ${we.indicesToOffset("outputIndices")};`;else{De=`var cIndices = ${v.type.indices}(0); cIndices[0] = outputIndices[${f.length-1}];`;for(let Ae=1;Ae<v.rank;Ae++)De+=`cIndices[${Ae}] = outputIndices[${Ae}];`;De+=`let cOffset = ${v.indicesToOffset("cIndices")};`}return De},he=De=>` const epsilon = ${s}; ${De.registerUniform("outputSize","u32").declareVariables(q,v,oe,te,de,we)} ${De.mainStart()} ${De.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${we.offsetToIndices(`global_idx * ${d}`)}; ${be()} let scale = ${v.getByOffset("cOffset")}; let bias = ${oe.getByOffset("cOffset")}; let inputMean = ${te.getByOffset("cOffset")}; let inputVar = ${de.getByOffset("cOffset")}; let x = ${q.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${we.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${i.epsilon}_${i.format}_${u}_${d}`,inputDependencies:$?["rank","type","type","type","type"]:void 0},getShaderSource:he,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$?[{type:12,data:k},...At(f)]:[{type:12,data:k}]})}},Ju=n=>qt(n),ec=(n,i)=>{let{inputs:s,outputCount:u}=n,c=Ju({...i,outputCount:u});if(N.webgpu.validateInputContent&&Yu(s,c),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");n.compute(Zu(s,c))}}),rc,nc,Ia,of=h(()=>{Jt(),ar(),rc=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(n[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},nc=n=>{let i=n[0].dims,s=n[0].dims[2],u=ct.size(i)/4,c=n[0].dataType,f=_t("input",c,i,4),d=_t("bias",c,[s],4),x=_t("residual",c,i,4),k=Gt("output",c,i,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:i,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:$=>` const channels = ${s}u / 4; ${$.declareVariables(f,d,x,k)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes(u)} let value = ${f.getByOffset("global_idx")} + ${d.getByOffset("global_idx % channels")} + ${x.getByOffset("global_idx")}; ${k.setByOffset("global_idx","value")} }`}},Ia=n=>{rc(n.inputs),n.compute(nc(n.inputs))}}),ic,br,oc,sc,Fa,ac,lc,Oa,uc,cc,Ds,dc,pc,fc,za,hc,bo,mc,Ls,gc,Da,_c,wc,yc,La,vc,bc,Ra,xc,Mc,Ba,Tc,kc,Na,Sc,ja,Ua,Va,Wa,Ec,Cc,Ga,Pc,$c,Ac,Ha=h(()=>{Zt(),Jt(),_r(),ar(),ic=(n,i,s,u,c,f)=>{let d=Math.ceil(i/4),x="";typeof c=="string"?x=`${c}(a)`:x=c("a");let k=_t("inputData",s,[d],4),$=Gt("outputData",u,[d],4);return` ${n.registerUniform("vec_size","u32").declareVariables(k,$)} ${f??""} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${k.getByOffset("global_idx")}; ${$.setByOffset("global_idx",x)} }`},br=(n,i,s,u,c,f=n.dataType)=>({name:i,shaderCache:{hint:c,inputDependencies:["type"]},getShaderSource:d=>ic(d,ct.size(n.dims),n.dataType,f,s,u),getRunData:d=>({outputs:[{dims:n.dims,dataType:f}],dispatchGroup:{x:Math.ceil(ct.size(d[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(ct.size(n.dims)/4)}]})}),oc=n=>{n.compute(br(n.inputs[0],"Abs","abs"))},sc=n=>{n.compute(br(n.inputs[0],"Acos","acos"))},Fa=n=>{n.compute(br(n.inputs[0],"Acosh","acosh"))},ac=n=>{n.compute(br(n.inputs[0],"Asin","asin"))},lc=n=>{n.compute(br(n.inputs[0],"Asinh","asinh"))},Oa=n=>{n.compute(br(n.inputs[0],"Atan","atan"))},uc=n=>{n.compute(br(n.inputs[0],"Atanh","atanh"))},cc=n=>qt(n),Ds=(n,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}`)}n.compute(br(n.inputs[0],"Cast",s,void 0,i.cacheKey,i.to))},dc=n=>{let i=n.length>=2&&n[1].data!==0?n[1].getFloat32Array()[0]:cn,s=n.length>=3&&n[2].data!==0?n[2].getFloat32Array()[0]:On;return qt({min:i,max:s})},pc=(n,i)=>{let s=n.inputs.length===1?i:dc(n.inputs),u=Er(n.inputs[0].dataType);n.compute(br(n.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]})},fc=n=>{n.compute(br(n.inputs[0],"Ceil","ceil"))},za=n=>{n.compute(br(n.inputs[0],"Cos","cos"))},hc=n=>{n.compute(br(n.inputs[0],"Cosh","cosh"))},bo=n=>qt(n),mc=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.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))},Ls=(n="f32")=>` const r0: ${n} = 0.3275911; const r1: ${n} = 0.254829592; const r2: ${n} = -0.284496736; const r3: ${n} = 1.421413741; const r4: ${n} = -1.453152027; const r5: ${n} = 1.061405429; fn erf_vf32(v: vec4<${n}>) -> vec4<${n}> { 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)); }`,gc=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"Erf",s=>`erf_vf32(${s})`,Ls(i)))},Da=n=>{n.compute(br(n.inputs[0],"Exp","exp"))},_c=n=>{n.compute(br(n.inputs[0],"Floor","floor"))},wc=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,Ls(i)))},yc=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"LeakyRelu",u=>`select(leaky_relu_alpha_ * ${u}, ${u}, ${u} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${i.alpha});`,i.cacheKey))},La=n=>{n.compute(br(n.inputs[0],"Not",i=>`!${i}`))},vc=n=>{n.compute(br(n.inputs[0],"Neg",i=>`-${i}`))},bc=n=>{n.compute(br(n.inputs[0],"Reciprocal",i=>`1.0/${i}`))},Ra=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"Relu",s=>`select(vec4<${i}>(0.0), ${s}, ${s} > vec4<${i}>(0.0))`))},xc=n=>{n.compute(br(n.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},Mc=n=>qt(n),Ba=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.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))},Tc=n=>{n.compute(br(n.inputs[0],"Sin","sin"))},kc=n=>{n.compute(br(n.inputs[0],"Sinh","sinh"))},Na=n=>{n.compute(br(n.inputs[0],"Sqrt","sqrt"))},Sc=n=>{n.compute(br(n.inputs[0],"Tan","tan"))},ja=n=>`sign(${n}) * (1 - exp(-2 * abs(${n}))) / (1 + exp(-2 * abs(${n})))`,Ua=n=>{n.compute(br(n.inputs[0],"Tanh",ja))},Va=(n="f32")=>` const fast_gelu_a: ${n} = 0.5; const fast_gelu_b: ${n} = 0.7978845608028654; const fast_gelu_c: ${n} = 0.035677408136300125; fn tanh_v(v: vec4<${n}>) -> vec4<${n}> { return ${ja("v")}; } `,Wa=n=>`(fast_gelu_a + fast_gelu_a * tanh_v(${n} * (fast_gelu_c * ${n} * ${n} + fast_gelu_b))) * ${n}`,Ec=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"FastGelu",Wa,Va(i),void 0,n.inputs[0].dataType))},Cc=(n,i)=>{let s=Er(n.inputs[0].dataType);return n.compute(br(n.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},Ga=n=>{n.compute(br(n.inputs[0],"Log","log"))},Pc=(n,i)=>` const alpha = vec4<${n}>(${i}); const one = ${n}(1.0); const zero = ${n}(0.0); fn quick_gelu_impl(x: vec4<${n}>) -> vec4<${n}> { let v = x *alpha; var x1 : vec4<${n}>; 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; } `,$c=n=>`quick_gelu_impl(${n})`,Ac=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"QuickGelu",$c,Pc(s,i.alpha),i.cacheKey,n.inputs[0].dataType))}}),qa,Ic,Fc,Oc=h(()=>{Jt(),ar(),Ha(),qa=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(n[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Ic=n=>{let i=n[0].dims.slice();i[2]=i[2]/2;let s=_t("input",n[0].dataType,n[0].dims,4),u=_t("bias",n[0].dataType,[n[0].dims[2]],4),c=Gt("output",n[0].dataType,i,4),f=ct.size(i)/4,d=Sr(n[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)}}),getShaderSource:x=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${n[0].dims[2]/4/2}u; ${x.declareVariables(s,u,c)} ${Ls(d)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes(f)} 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")} }`}},Fc=n=>{qa(n.inputs),n.compute(Ic(n.inputs))}}),zc,Dc,Zn,Lc,Rc,Ka,Bc,Nc,jc,Uc,Vc,Wc,Xa,sf=h(()=>{Zt(),Jt(),ar(),zc=(n,i,s,u,c,f,d,x,k,$,H,q)=>{let v,oe;typeof x=="string"?v=oe=(he,De)=>`${x}((${he}),(${De}))`:typeof x=="function"?v=oe=x:(v=x.scalar,oe=x.vector);let te=Gt("outputData",H,u.length,4),de=_t("aData",k,i.length,4),we=_t("bData",$,s.length,4),be;if(c)if(f){let he=ct.size(i)===1,De=ct.size(s)===1,Ae=i.length>0&&i[i.length-1]%4===0,Ie=s.length>0&&s[s.length-1]%4===0;he||De?be=te.setByOffset("global_idx",oe(he?`${de.type.value}(${de.getByOffset("0")}.x)`:de.getByOffset("global_idx"),De?`${we.type.value}(${we.getByOffset("0")}.x)`:we.getByOffset("global_idx"))):be=` let outputIndices = ${te.offsetToIndices("global_idx * 4u")}; let offsetA = ${de.broadcastedIndicesToOffset("outputIndices",te)}; let offsetB = ${we.broadcastedIndicesToOffset("outputIndices",te)}; ${te.setByOffset("global_idx",oe(d||Ae?de.getByOffset("offsetA / 4u"):`${de.type.value}(${de.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||Ie?we.getByOffset("offsetB / 4u"):`${we.type.value}(${we.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else be=te.setByOffset("global_idx",oe(de.getByOffset("global_idx"),we.getByOffset("global_idx")));else{if(!f)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let he=(De,Ae,Ie="")=>{let gt=`aData[indexA${Ae}][componentA${Ae}]`,ut=`bData[indexB${Ae}][componentB${Ae}]`;return` let outputIndices${Ae} = ${te.offsetToIndices(`global_idx * 4u + ${Ae}u`)}; let offsetA${Ae} = ${de.broadcastedIndicesToOffset(`outputIndices${Ae}`,te)}; let offsetB${Ae} = ${we.broadcastedIndicesToOffset(`outputIndices${Ae}`,te)}; let indexA${Ae} = offsetA${Ae} / 4u; let indexB${Ae} = offsetB${Ae} / 4u; let componentA${Ae} = offsetA${Ae} % 4u; let componentB${Ae} = offsetB${Ae} % 4u; ${De}[${Ae}] = ${Ie}(${v(gt,ut)}); `};H===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` ${n.registerUniform("vec_size","u32").declareVariables(de,we,te)} ${q??""} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${be} }`},Dc=(n,i,s,u,c,f,d=s.dataType)=>{let x=!ct.areEqual(s.dims,u.dims),k=s.dims,$=ct.size(s.dims),H=!1,q=!1,v=[x];if(x){let oe=gn.calcShape(s.dims,u.dims,!1);if(!oe)throw new Error("Can't perform binary op on the given tensors");k=oe,$=ct.size(k);let te=ct.size(s.dims)===1,de=ct.size(u.dims)===1,we=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(te),v.push(de),v.push(we),v.push(be);let he=1;for(let De=1;De<k.length;De++){let Ae=s.dims[s.dims.length-De]??1,Ie=u.dims[u.dims.length-De]??1;if(Ae===Ie)he*=Ae;else break}he%4===0?(q=!0,H=!0):(te||de||we||be)&&(H=!0)}else H=!0;return v.push(H),{name:n,shaderCache:{hint:i+v.map(oe=>oe.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:oe=>zc(oe,s.dims,u.dims,k,H,x,q,c,s.dataType,u.dataType,d,f),getRunData:()=>({outputs:[{dims:k,dataType:d}],dispatchGroup:{x:Math.ceil($/64/4)},programUniforms:[{type:12,data:Math.ceil(ct.size(k)/4)},...At(s.dims,u.dims,k)]})}},Zn=(n,i,s,u,c,f)=>{n.compute(Dc(i,c??"",n.inputs[0],n.inputs[1],s,u,f))},Lc=n=>{Zn(n,"Add",(i,s)=>`${i}+${s}`)},Rc=n=>{Zn(n,"Div",(i,s)=>`${i}/${s}`)},Ka=n=>{Zn(n,"Equal",{scalar:(i,s)=>`u32(${i}==${s})`,vector:(i,s)=>`vec4<u32>(${i}==${s})`},void 0,void 0,9)},Bc=n=>{Zn(n,"Mul",(i,s)=>`${i}*${s}`)},Nc=n=>{let i=_t("input",n.inputs[0].dataType,n.inputs[0].dims).type.value;Zn(n,"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)); } `)},jc=n=>{Zn(n,"Sub",(i,s)=>`${i}-${s}`)},Uc=n=>{Zn(n,"Greater",{scalar:(i,s)=>`u32(${i}>${s})`,vector:(i,s)=>`vec4<u32>(${i}>${s})`},void 0,void 0,9)},Vc=n=>{Zn(n,"Less",{scalar:(i,s)=>`u32(${i}<${s})`,vector:(i,s)=>`vec4<u32>(${i}<${s})`},void 0,void 0,9)},Wc=n=>{Zn(n,"GreaterOrEqual",{scalar:(i,s)=>`u32(${i}>=${s})`,vector:(i,s)=>`vec4<u32>(${i}>=${s})`},void 0,void 0,9)},Xa=n=>{Zn(n,"LessOrEqual",{scalar:(i,s)=>`u32(${i}<=${s})`,vector:(i,s)=>`vec4<u32>(${i}<=${s})`},void 0,void 0,9)}}),Gc,Qa,Hc,qc,Ui,Kc,af=h(()=>{Zt(),Jt(),_r(),ar(),Gc=(n,i)=>{if(!n||n.length<1)throw new Error("too few inputs");let s=0,u=n[s],c=u.dataType,f=u.dims.length;n.forEach((d,x)=>{if(x!==s){if(d.dataType!==c)throw new Error("input tensors should be one type");if(d.dims.length!==f)throw new Error("input tensors should have the same shape");d.dims.forEach((k,$)=>{if($!==i&&k!==u.dims[$])throw new Error("non concat dimensions must match")})}})},Qa=(n,i)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array<u32, ${n}u>(${i}); for (var i: u32 = 0u; i < ${n}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${n}u; }`,Hc=(n,i)=>{let s=n.length,u=[];for(let c=0;c<s;++c){let f=i.setByOffset("global_idx",n[c].getByIndices("indices"));s===1?u.push(f):c===0?u.push(`if (inputIndex == ${c}u) { ${f} }`):c===s-1?u.push(`else { ${f} }`):u.push(`else if (inputIndex == ${c}) { ${f} }`)}return u.join(` `)},qc=(n,i,s,u)=>{let c=ct.size(s),f=new Array(n.length),d=new Array(n.length),x=0,k=[],$=[],H=[{type:12,data:c}];for(let de=0;de<n.length;++de)x+=n[de].dims[i],f[de]=x,$.push(n[de].dims.length),d[de]=_t(`input${de}`,u,$[de]),k.push("rank"),H.push({type:12,data:f[de]});for(let de=0;de<n.length;++de)H.push(...At(n[de].dims));H.push(...At(s));let q=Gt("output",u,s.length),v=q.indicesGet("indices",i),oe=Array.from(Array(f.length).keys()).map(de=>`uniforms.sizeInConcatAxis${de}`).join(","),te=de=>` ${(()=>{de.registerUniform("outputSize","u32");for(let we=0;we<n.length;we++)de.registerUniform(`sizeInConcatAxis${we}`,"u32");return de.declareVariables(...d,q)})()} ${Qa(f.length,oe)} ${de.mainStart()} ${de.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var indices = ${q.offsetToIndices("global_idx")}; let inputIndex = calculateInputIndex(${v}); if (inputIndex != 0u) { let sizeInConcatAxis = array<u32, ${f.length}u>(${oe}); ${v} -= sizeInConcatAxis[inputIndex - 1u]; } ${Hc(d,q)} }`;return{name:"Concat",shaderCache:{hint:`${i}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:s,dataType:u}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:H}),getShaderSource:te}},Ui=(n,i)=>{let s=n.inputs,u=s[0].dims,c=ct.normalizeAxis(i.axis,u.length);Gc(s,c);let f=u.slice();f[c]=s.reduce((x,k)=>x+(k.dims.length>c?k.dims[c]:0),0);let d=s.filter(x=>ct.size(x.dims)>0);n.compute(qc(d,c,f,s[0].dataType),{inputs:d})},Kc=n=>qt({axis:n.axis})}),Vi,Wi,Ei,Ya,Gi=h(()=>{Zt(),Jt(),Vi=(n,i,s="f32")=>{switch(n.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 ${n.activation}`)}},Wi=(n,i)=>{n.activation==="Clip"?i.push({type:1,data:n.clipMax},{type:1,data:n.clipMin}):n.activation==="HardSigmoid"?i.push({type:1,data:n.alpha},{type:1,data:n.beta}):n.activation==="LeakyRelu"&&i.push({type:1,data:n.alpha})},Ei=(n,i)=>{n.activation==="Clip"?i.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):n.activation==="HardSigmoid"?i.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):n.activation==="LeakyRelu"&&i.push({name:"alpha",type:"f32"})},Ya=n=>{let i=(n==null?void 0:n.activation)||"";if(i==="HardSigmoid"){let[s,u]=(n==null?void 0:n.activation_params)||[.2,.5];return{activation:i,alpha:s,beta:u}}else if(i==="Clip"){let[s,u]=(n==null?void 0:n.activation_params)||[cn,On];return{activation:i,clipMax:u,clipMin:s}}else if(i==="LeakyRelu"){let[s]=(n==null?void 0:n.activation_params)||[.01];return{activation:i,alpha:s}}return{activation:i}}}),vn,Za,xo=h(()=>{vn=(n,i)=>{switch(n){case 1:return i;case 2:return`vec2<${i}>`;case 3:return`vec3<${i}>`;case 4:return`vec4<${i}>`;default:throw new Error(`${n}-component is not supported.`)}},Za=n=>` ${n?"value = value + getBiasByOutputCoords(coords);":""} `}),Ja,Xc=h(()=>{Ja=n=>` 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(${n}.x), i32(${n}.y), i32(${n}.z), 1)); } `}),Qc,qo,Rs,el,Yc,Bs,Ns,tl,js=h(()=>{Zt(),Jt(),ar(),Gi(),xo(),Qc=(n,i)=>n?` 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":""}); `,qo=(n,i)=>n?` 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];"} }`,Rs=(n,i,s="f32",u,c=!1,f=32,d=!1,x=32)=>{let k=i[1]*n[1],$=i[0]*n[0],H=c?k:f,q=c?f:k,v=H/i[0],oe=f/i[1];if(!((c&&v===4&&n[1]===4||!c&&(v===3||v===4))&&H%i[0]===0&&f%i[1]===0&&n[0]===4))throw new Error(`If transposeA ${c} is true, innerElementSize ${v} and workPerThread[1] ${n[1]} must be 4. Otherwise, innerElementSize ${v} must be 3 or 4. tileAWidth ${H} must be divisible by workgroupSize[0]${i[0]}. tileInner ${f} must be divisible by workgroupSize[1] ${i[1]}. colPerThread ${n[0]} must be 4.`);return` var<workgroup> mm_Asub: array<array<vec${v}<${s}>, ${H/v}>, ${q}>; var<workgroup> mm_Bsub: array<array<vec4<${s}>, ${$/n[0]}>, ${f}>; const rowPerThread = ${n[1]}; const colPerThread = ${n[0]}; const innerElementSize = ${v}; const tileInner = ${f}; @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) * ${k}; let num_tiles = ${d?`${Math.ceil(x/f)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${d?`i32(globalId.z) * ${x}`:"0"}; var acc: array<vec4<${s}>, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${oe}; 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 < ${oe}; 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];"} ${qo(c,v)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},el=(n,i)=>n?` 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":""}); `,Yc=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Bs=(n,i,s="f32",u,c=!1,f=32,d=!1,x=32,k=!1)=>{let $=n[1]*i[1],H=n[0]*i[0],q=c?$:f,v=c?f:$;if(!(v%i[1]===0&&q%i[0]===0&&f%i[1]===0))throw new Error(`tileAHight ${v} must be divisible by workgroupSize[1]${i[1]}, tileAWidth ${q} must be divisible by workgroupSize[0]${i[0]}, tileInner ${f} must be divisible by workgroupSize[1]${i[1]}`);let oe=v/i[1],te=q/i[0],de=f/i[1],we=k?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${$}; let globalColStart = i32(workgroupId.x) * ${H}; // 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 < ${q}; inputCol = inputCol + ${i[0]}) { ${el(c,u)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${i[1]}) { for (var inputCol = localCol; inputCol < ${H}; 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) * ${$}; let tileRowA = i32(localId.y) * ${oe}; let tileColA = i32(localId.x) * ${te}; let tileRowB = i32(localId.y) * ${de}; // 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 < ${oe}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${te}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${el(c,u)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${de}; 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) { ${Yc(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}, ${q}>, ${v}>; var<workgroup> mm_Bsub : array<array<${s}, ${H}>, ${f}>; const rowPerThread = ${n[1]}; const colPerThread = ${n[0]}; const tileInner = ${f}; @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(x/f)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${d?`i32(globalId.z) * ${x}`:"0"}; var acc : array<array<${s}, colPerThread>, rowPerThread>; ${we} } `},Ns=(n,i,s,u,c,f=!1)=>{let[d,x,k]=c,[$,H,q,v]=u,oe=wo(d,k),te=wo(x,k),de=Sr(u[0].type.tensor),we=()=>{let he=H.rank,De=$.rank,Ae=`var aIndices: ${H.type.indices};`;for(let Ie=he-2-1,gt=De-1;Ie>=0;Ie--,gt--)Ae+=` aIndices[${Ie}] = ${De>1?`batchIndices[${gt}]`:"batchIndices"};`;return oe.forEach(Ie=>{Ae+=` aIndices[${Ie}] = 0;`}),Ae+=` aIndices[${he-2}] = u32(row); aIndices[${he-1}] = u32(colIn);`,Ae},be=()=>{let he=q.rank,De=$.rank,Ae=`var bIndices: ${q.type.indices};`;for(let Ie=he-2-1,gt=De-1;Ie>=0;Ie--,gt--)Ae+=` bIndices[${Ie}] = ${De>1?`batchIndices[${gt}]`:"batchIndices"};`;return te.forEach(Ie=>{Ae+=` bIndices[${Ie}] = 0;`}),Ae+=` bIndices[${he-2}] = u32(row); bIndices[${he-1}] = u32(colIn);`,Ae};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${$.type.indices}) -> ${vn(n,de)} { var value = ${vn(n,de)}(0.0); let col = colIn * ${n}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${we()} value = ${H.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${$.type.indices}) -> ${vn(n,de)} { var value = ${vn(n,de)}(0.0); let col = colIn * ${n}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${be()} value = ${q.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${vn(n,de)}) { let col = colIn * ${n}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3<i32>(batch, row, colIn); ${i?`value = value + ${f?"bias[colIn]":`${vn(n,de)}(bias[row])`};`:""} ${s} ${v.setByIndices("vec3<u32>(coords)","value")} } } `},tl=(n,i,s,u,c=!1)=>{let f=n[0].dims,d=n[1].dims,x=f.slice(0,-2),k=d.slice(0,-2),$=u?u.slice(0,-2):s.slice(0,-2),H=ct.size($),q=f[f.length-2],v=f[f.length-1],oe=d[d.length-1],te=v%4===0&&oe%4===0,de=q<=8?[4,1,1]:[4,4,1],we=[8,8,1],be=[Math.ceil(oe/we[0]/de[0]),Math.ceil(q/we[1]/de[1]),Math.ceil(H/we[2]/de[2])],he=te?4:1,De=[...x,q,v/he],Ae=De.length,Ie=[...k,v,oe/he],gt=Ie.length,ut=[H,q,oe/he],vt=[{type:6,data:q},{type:6,data:oe},{type:6,data:v}];Wi(i,vt),vt.push(...At($,De,Ie));let Dt=["rank","rank"],Rt=n.length>2;Rt&&(vt.push(...At(n[2].dims)),Dt.push("rank")),vt.push(...At(ut));let gr=Mr=>{let ir=$.length,Fr=ma("batchDims",n[0].dataType,ir,1),Zr=Sr(n[0].dataType),hr=_t("a",n[0].dataType,Ae,he),Hr=_t("b",n[1].dataType,gt,he),Nt=Gt("result",n[0].dataType,ut.length,he),er=[hr,Hr];if(Rt){let Wr=c?he:1;er.push(_t("bias",n[2].dataType,n[2].dims.length,Wr))}let yr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ei(i,yr);let ot=Sr(Nt.type.tensor),Vt=Vi(i,Nt.type.value,ot),nr=Ns(he,Rt,Vt,[Fr,hr,Hr,Nt],[x,k,$],c);return` ${Mr.registerUniforms(yr).registerInternalVariables(Fr).declareVariables(...er,Nt)} ${nr} ${te?Rs(de,we,Zr,Fr):Bs(de,we,Zr,Fr)} `};return{name:"MatMul",shaderCache:{hint:`${de};${i.activation};${te};${c}`,inputDependencies:Dt},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:vt}),getShaderSource:gr}}}),Zc,lf,uf=h(()=>{Zt(),jn(),ar(),Gi(),xo(),Xc(),js(),Zc=(n,i,s,u,c=!1,f,d=4,x=4,k=4,$="f32")=>{let H=Dt=>{switch(Dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${$}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},q=Dt=>{switch(Dt){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 ${Dt} is not supported.`)}},v=n?` let coord = vec4<i32>(batch, xRow, xCol, xCh); `:` let coord = vec4<i32>(batch, xCh, xRow, xCol); `,oe=n?` let coords = vec4<i32>( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4<i32>( batch, row, col / outWidth, col % outWidth); `,te=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",de=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",we=n?"row":"col",be=n?"col":"row",he=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${we} / outWidth; let outCol = ${we} % 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 = ${vn(d,$)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${te} && xCol >= 0 && xCol < ${de}) { ${v} let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape)); ${H(d)} } return resData;`,De=n?i&&u?` let col = colIn * ${d}; ${he}`:` let col = colIn * ${d}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${he} } return ${vn(d,$)}(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 ${vn(d,$)}(0.0);`,Ae=`${q(x)}`,Ie=vn(k,$),gt=vn(n?d:x,$),ut=vn(n?x:d,$),vt=Vi(f,Ie,$);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${gt} { ${n?De:Ae} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${ut} { ${n?Ae:De} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Ie}) { let col = colIn * ${k}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${oe} ${Za(c)} ${vt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},lf=(n,i,s,u,c,f,d,x)=>{let k=i.format==="NHWC",$=k?n[0].dims[3]:n[0].dims[1],H=s[0],q=k?s[2]:s[3],v=k?s[1]:s[2],oe=k?s[3]:s[1],te=k&&($%4===0||$%3===0)&&oe%4===0,de=k?oe:q*v,we=k?q*v:oe,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],De=[Math.ceil(de/be[0]/he[0]),Math.ceil(we/be[1]/he[1]),Math.ceil(H/be[2]/he[2])];Vr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${De}`);let Ae=te?k&&$%4!==0?3:4:1,Ie=be[1]*he[1],gt=be[0]*he[0],ut=Math.max(be[0]*Ae,be[1]),vt=u%Ie===0,Dt=c%gt===0,Rt=f%ut===0,gr=te?[Ae,4,4]:[1,1,1],Mr=[{type:6,data:u},{type:6,data:c},{type:6,data:f},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];Wi(i,Mr),Mr.push(...At(n[0].dims,n[1].dims));let ir=["rank","rank"];d&&(Mr.push(...At(n[2].dims)),ir.push("rank")),Mr.push(...At(s));let Fr=Zr=>{let hr=[{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}];Ei(i,hr);let Hr=te?4:1,Nt=Sr(n[0].dataType),er=` fn setOutputAtIndex(flatIndex : i32, value : ${te?`vec4<${Nt}>`:Nt}) { result[flatIndex] = ${te?`vec4<${Nt}>`:Nt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${te?`vec4<${Nt}>`:Nt}) { let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${te?"/ 4":""}, value); }`,yr=_t("x",n[0].dataType,n[0].dims.length,Ae===3?1:Ae),ot=_t("w",n[1].dataType,n[1].dims.length,Hr),Vt=[yr,ot],nr=Gt("result",n[0].dataType,s.length,Hr);if(d){let Wr=_t("bias",n[2].dataType,n[2].dims.length,Hr);Vt.push(Wr),er+=` fn getBiasByOutputCoords(coords : vec4<i32>) -> ${te?`vec4<${Nt}>`:Nt} { return bias[coords.${k?"w":"y"}${te?"/ 4":""}]; }`}return` ${Ja("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 }; ${Zr.registerUniforms(hr).declareVariables(...Vt,nr)} ${er} ${Zc(k,vt,Dt,Rt,d,i,gr[0],gr[1],gr[2],Nt)} ${te?Rs(he,be,Nt,void 0,!k,ut):Bs(he,be,Nt,void 0,!k,ut,!1,void 0,x)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${Ae};${te};${vt};${Dt};${Rt};${Ie};${gt};${ut}`,inputDependencies:ir},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:De[0],y:De[1],z:De[2]},programUniforms:Mr}),getShaderSource:Fr}}}),Jc,rl,Ci,ed,nl,td,rd,nd,il=h(()=>{Zt(),jn(),Jt(),ar(),Gi(),xo(),Jc=n=>{let i=1;for(let s=0;s<n.length;s++)i*=n[s];return i},rl=n=>typeof n=="number"?[n,n,n]:n,Ci=(n,i)=>i<=1?n:n+(n-1)*(i-1),ed=(n,i,s,u=1)=>{let c=Ci(i,u);return Math.floor((n[0]*(s-1)-s+c)/2)},nl=(n,i,s,u,c)=>{c==null&&(c=ed(n,i[0],u[0]));let f=[0,0,0,s];for(let d=0;d<3;d++)n[d]+2*c>=i[d]&&(f[d]=Math.trunc((n[d]-i[d]+2*c)/u[d]+1));return f},td=(n,i,s,u,c,f,d,x,k,$)=>{let H,q,v,oe;if(n==="VALID"&&(n=0),typeof n=="number"){H={top:n,bottom:n,left:n,right:n,front:n,back:n};let te=nl([i,s,u,1],[x,k,$],1,[c,f,d],n);q=te[0],v=te[1],oe=te[2]}else if(Array.isArray(n)){if(!n.every((de,we,be)=>de===be[0]))throw Error(`Unsupported padding parameter: ${n}`);H={top:n[0],bottom:n[1],left:n[2],right:n[3],front:n[4],back:n[5]};let te=nl([i,s,u,1],[x,k,$],1,[c,f,d],n[0]);q=te[0],v=te[1],oe=te[2]}else if(n==="SAME_UPPER"){q=Math.ceil(i/c),v=Math.ceil(s/f),oe=Math.ceil(u/d);let te=(q-1)*c+x-i,de=(v-1)*f+k-s,we=(oe-1)*d+$-u,be=Math.floor(te/2),he=te-be,De=Math.floor(de/2),Ae=de-De,Ie=Math.floor(we/2),gt=we-Ie;H={top:De,bottom:Ae,left:Ie,right:gt,front:be,back:he}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:H,outDepth:q,outHeight:v,outWidth:oe}},rd=(n,i,s,u,c,f=!1,d="channelsLast")=>{let x,k,$,H,q;if(d==="channelsLast")[x,k,$,H,q]=n;else if(d==="channelsFirst")[x,q,k,$,H]=n;else throw new Error(`Unknown dataFormat ${d}`);let[v,,oe,te,de]=i,[we,be,he]=rl(s),[De,Ae,Ie]=rl(u),gt=Ci(oe,De),ut=Ci(te,Ae),vt=Ci(de,Ie),{padInfo:Dt,outDepth:Rt,outHeight:gr,outWidth:Mr}=td(c,k,$,H,we,be,he,gt,ut,vt),ir=f?v*q:v,Fr=[0,0,0,0,0];return d==="channelsFirst"?Fr=[x,ir,Rt,gr,Mr]:d==="channelsLast"&&(Fr=[x,Rt,gr,Mr,ir]),{batchSize:x,dataFormat:d,inDepth:k,inHeight:$,inWidth:H,inChannels:q,outDepth:Rt,outHeight:gr,outWidth:Mr,outChannels:ir,padInfo:Dt,strideDepth:we,strideHeight:be,strideWidth:he,filterDepth:oe,filterHeight:te,filterWidth:de,effectiveFilterDepth:gt,effectiveFilterHeight:ut,effectiveFilterWidth:vt,dilationDepth:De,dilationHeight:Ae,dilationWidth:Ie,inShape:n,outShape:Fr,filterShape:i}},nd=(n,i,s,u,c,f)=>{let d=f==="channelsLast";d?n[0].dims[3]:n[0].dims[1];let x=[64,1,1],k={x:s.map((we,be)=>be)},$=[Math.ceil(Jc(k.x.map(we=>s[we]))/x[0]),1,1];Vr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${$}`);let H=1,q=ct.size(s),v=[{type:12,data:q},{type:12,data:u},{type:12,data:c},{type:12,data:i.strides},{type:12,data:i.dilations}];Wi(i,v),v.push(...At(n[0].dims,n[1].dims));let oe=["rank","rank"],te=n.length===3;te&&(v.push(...At(n[2].dims)),oe.push("rank")),v.push(...At(s));let de=we=>{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}];Ei(i,be);let he=1,De=Sr(n[0].dataType),Ae=_t("x",n[0].dataType,n[0].dims.length,H),Ie=_t("W",n[1].dataType,n[1].dims.length,he),gt=[Ae,Ie],ut=Gt("result",n[0].dataType,s.length,he),vt="";if(te){let gr=_t("bias",n[2].dataType,n[2].dims.length,he);gt.push(gr),vt+=` fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${De} { return bias[${d?zt("coords",4,5):zt("coords",1,5)}]; }`}let Dt=vn(H,De),Rt=Vi(i,Dt,De);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 ${Ae.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")}; } ${we.registerUniforms(be).declareVariables(...gt,ut)} ${we.mainStart()} ${we.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${ut.offsetToIndices("global_idx")}; let batch = ${zt("coords",0,Ae.rank)}; let d2 = ${d?zt("coords",Ae.rank-1,Ae.rank):zt("coords",1,Ae.rank)}; let xFRCCorner = vec3<u32>(${d?zt("coords",1,Ae.rank):zt("coords",2,Ae.rank)}, ${d?zt("coords",2,Ae.rank):zt("coords",3,Ae.rank)}, ${d?zt("coords",3,Ae.rank):zt("coords",4,Ae.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${d?zt("uniforms.x_shape",1,Ae.rank):zt("uniforms.x_shape",2,Ae.rank)}; let xShapeZ = ${d?zt("uniforms.x_shape",2,Ae.rank):zt("uniforms.x_shape",3,Ae.rank)}; let xShapeW = ${d?zt("uniforms.x_shape",3,Ae.rank):zt("uniforms.x_shape",4,Ae.rank)}; let xShapeU = ${d?zt("uniforms.x_shape",4,Ae.rank):zt("uniforms.x_shape",1,Ae.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); } } } } ${te?"value = value + getBiasByOutputCoords(coords)":""}; ${Rt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${d};${H};${te}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:v}),getShaderSource:de}}}),id,od,cf=h(()=>{Zt(),Jt(),ar(),cd(),Gi(),id=(n,i,s)=>{let u=n.length>2,c=u?"value += b[output_channel];":"",f=n[0].dims,d=n[1].dims,x=d[0]/i.group,k=i.format==="NHWC",$=Us(f,d,i.dilations,i.pads,i.strides,k),H=ct.size($),q=[{type:12,data:H},{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:x}];Wi(i,q),q.push(...At(f,d));let v=["rank","rank"];u&&(q.push(...At(n[2].dims)),v.push("rank")),q.push(...At($));let oe=te=>{let de=Gt("output",n[0].dataType,$.length),we=Sr(de.type.tensor),be=Vi(i,de.type.value,we),he=_t("x",n[0].dataType,f.length),De=_t("w",n[1].dataType,d.length),Ae=[he,De];u&&Ae.push(_t("b",n[2].dataType,n[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 Ei(i,Ie),` ${te.registerUniforms(Ie).declareVariables(...Ae,de)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${de.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${k?3:1}]; let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${k?1:2}], outputIndices[${k?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${de.type.value} = ${de.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[${k?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[${k?2:3}]) { continue; } let xVal = ${k?he.get("batch","xHeight","xWidth","input_channel"):he.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${De.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${c} ${be} ${de.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:i.cacheKey,inputDependencies:v},getRunData:()=>({outputs:[{dims:s?s($):$,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:q}),getShaderSource:oe}},od=(n,i,s)=>{let u=n.length>2,c=vr(s[3]),f=vr(s[2]),d=ct.size(s)/c/f,x=[n[0].dims[0],n[0].dims[1],n[0].dims[2],n[0].dims[3]/c],k=[n[1].dims[0],n[1].dims[1],n[1].dims[2],n[1].dims[3]/c],$=[s[0],s[1],s[2],s[3]/c],H=[{type:12,data:d},{type:6,data:[i.strides[0],i.strides[1]]},{type:6,data:[i.pads[0],i.pads[1]]}];Wi(i,H),H.push(...At(x,k,$));let q=(f-1)*i.strides[1]+k[1],v=oe=>{let te=Gt("output",n[0].dataType,$.length,c),de=Sr(te.type.tensor),we=Vi(i,te.type.value,de),be=_t("x",n[0].dataType,x.length,c),he=_t("w",n[1].dataType,k.length,c),De=[be,he];u&&De.push(_t("b",n[2].dataType,n[2].dims,c));let Ae=u?"value += b[output_channel];":"",Ie=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ei(i,Ie),` ${oe.registerUniforms(Ie).declareVariables(...De,te)} ${oe.mainStart()} ${oe.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] / ${f}u; let col = (index1 % width1) * ${f}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}, ${q}>; var values: array<${te.type.value}, ${f}>; 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 < ${k[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 < ${q}; 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 < ${k[1]}; w_width++) { let w_val = ${he.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${f}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${f}u; i++) { var value = values[i]; ${Ae} ${we} ${te.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${c};${f};${q};${k[0]};${k[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:H}),getShaderSource:v}}}),ol,sd,ad,sl=h(()=>{Zt(),Jt(),js(),ar(),Gi(),ol=(n,i,s,u,c=!1)=>{let f=n[0].dims,d=n[1].dims,x=f[f.length-2],k=d[d.length-1],$=f[f.length-1],H=vr(k),q=vr($),v=vr(x),oe=ct.size(s)/H/v,te=n.length>2,de=u?u.slice(0,-2):s.slice(0,-2),we=[ct.size(de),x,k],be=[{type:12,data:oe},{type:12,data:x},{type:12,data:k},{type:12,data:$}];Wi(i,be),be.push(...At(de,f,d)),te&&be.push(...At(n[2].dims)),be.push(...At(we));let he=De=>{let Ae=ma("batch_dims",n[0].dataType,de.length),Ie=_t("a",n[0].dataType,f.length,q),gt=_t("b",n[1].dataType,d.length,H),ut=Gt("output",n[0].dataType,we.length,H),vt=Sr(ut.type.tensor),Dt=Vi(i,ut.type.value,vt),Rt=[Ie,gt],gr="";if(te){let er=c?H:1;Rt.push(_t("bias",n[2].dataType,n[2].dims.length,er)),gr=`${c?`value += bias[col / ${er}];`:`value += ${ut.type.value}(bias[row + i]);`}`}let Mr=f.slice(0,-2),ir=d.slice(0,-2),Fr=wo(Mr,de),Zr=wo(ir,de),hr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ei(i,hr);let Hr=(er,yr)=>{let ot=er.rank,Vt=er.name;if(ot===2)return`var ${Vt}_indices = ${er.type.indices}(0u, 0u);`;let nr=Ae.rank,Wr=`var ${Vt}_indices: ${er.type.indices};`;for(let pn=ot-2-1,kn=nr-1;pn>=0;pn--,kn--)Wr+=` ${Vt}_indices[${pn}] = ${nr>1?`batch_indices[${kn}]`:"batch_indices"};`;return yr.forEach(pn=>{Wr+=` ${Vt}_indices[${pn}] = 0;`}),Wr+=`${Vt}_indices[${ot-2}] = 0u; ${Vt}_indices[${ot-1}] = 0u;`,Wr},Nt=()=>{let er=`var a_data: ${Ie.type.value};`;for(let yr=0;yr<q;yr++)er+=` let b_data${yr} = b[(b_offset + (k + ${yr}) * uniforms.N + col) / ${H}];`;for(let yr=0;yr<v;yr++){er+=`a_data = a[(a_offset + (row + ${yr}) * uniforms.K + k) / ${q}];`;for(let ot=0;ot<q;ot++)er+=` values[${yr}] = fma(${gt.type.value}(a_data${q===1?"":`[${ot}]`}), b_data${ot}, values[${yr}]); `}return er};return` ${De.registerUniforms(hr).registerInternalVariables(Ae).declareVariables(...Rt,ut)} ${De.mainStart()} ${De.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let col = (global_idx % (uniforms.N / ${H})) * ${H}; var index1 = global_idx / (uniforms.N / ${H}); let stride1 = uniforms.M / ${v}; let row = (index1 % stride1) * ${v}; let batch = index1 / stride1; ${s.length===2?"":`let batch_indices = ${Ae.offsetToIndices("batch")};`} ${Hr(Ie,Fr)} let a_offset = ${Ie.indicesToOffset("a_indices")}; ${Hr(gt,Zr)} let b_offset = ${gt.indicesToOffset("b_indices")}; var values: array<${ut.type.value}, ${v}>; for (var k: u32 = 0u; k < uniforms.K; k = k + ${q}) { ${Nt()} } for (var i = 0u; i < ${v}u; i++) { var value = values[i]; ${gr} ${Dt} let cur_indices = ${ut.type.indices}(batch, row + i, col); let offset = ${ut.indicesToOffset("cur_indices")}; ${ut.setByOffset(`offset / ${H}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${i.activation};${H};${q};${v};${c}`,inputDependencies:te?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(oe/64)},programUniforms:be}),getShaderSource:he}},sd=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.")},ad=n=>{sd(n.inputs);let i=gn.calcShape(n.inputs[0].dims,n.inputs[1].dims,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let s=i[i.length-1],u=n.inputs[0].dims[n.inputs[0].dims.length-1];s<8&&u<8?n.compute(ol(n.inputs,{activation:""},i)):n.compute(tl(n.inputs,{activation:""},i))}}),Us,Vs,al,Ws,ll,ul,ld,ud,Ko,cd=h(()=>{Jt(),uf(),il(),js(),cf(),Gi(),sl(),yo(),Us=(n,i,s,u,c,f)=>{let d=n[0],x=n.slice(f?1:2,f?3:4),k=x.length,$=i[0],H=i.slice(2).map((v,oe)=>v+(v-1)*(s[oe]-1)),q=x.map((v,oe)=>v+u[oe]+u[oe+k]).map((v,oe)=>Math.floor((v-H[oe]+c[oe])/c[oe]));return q.splice(0,0,d),q.splice(f?3:1,0,$),q},Vs=[2,3,1,0],al=(n,i)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length>5)throw new Error("greater than 5D is not supported");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let s=n[0].dims[i.format==="NHWC"?n[0].dims.length-1:1],u=n[1].dims[1]*i.group;if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(n.length===3&&(n[2].dims.length!==1||n[1].dims[0]!==n[2].dims[0]))throw new Error("invalid bias");let c=n[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!==n[1].dims.length-2)throw new Error("invalid kernel shape")},Ws=(n,i)=>{let s=n.kernelShape.slice();for(let f=2;f<i[1].dims.length;++f)s[f-2]===0&&(s[f-2]=i[1].dims[f]);let u=n.pads.slice();Kn.adjustPadsBasedOnAutoPad(i[0].dims,n.strides,n.dilations,s,u,n.format==="NHWC",n.autoPad);let c=Object.assign({},n);return Object.assign(c,{kernelShape:s,pads:u}),c},ll=n=>{let i=Ya(n),s=n.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],c=n.dilations,f=n.group,d=n.kernel_shape,x=n.pads,k=n.strides,$=n.w_is_const();return{autoPad:u,format:s,dilations:c,group:f,kernelShape:d,pads:x,strides:k,wIsConst:$,...i,cacheKey:`${n.format};${i.activation};`}},ul=(n,i,s)=>{let u=Ws(s,i),c=s.format==="NHWC";if(s.group!==1){if(!n.adapterInfo.isArchitecture("ampere")&&c&&i[1].dims[0]===s.group&&i[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1){let gt=Us(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),ut=n.kernelCustomData.wT??n.compute(hi(i[1],Vs),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=ut);let vt=[i[0],ut];i.length===3&&vt.push(i[2]),n.compute(od(vt,u,gt),{inputs:vt})}else n.compute(id(i,u));return}let f=i.length===3,d=i[0].dims[c?1:2],x=i[0].dims[c?2:3],k=i[0].dims[c?3:1],$=i[1].dims[2],H=i[1].dims[3],q=Us(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),v=q[c?1:2],oe=q[c?2:3],te=q[c?3:1],de=c&&$===d&&H===x&&s.pads[0]===0&&s.pads[1]===0;if(de||$===1&&H===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 gt=q[0],ut,vt,Dt,Rt=[];if(c){let ir=n.kernelCustomData.wT??n.compute(hi(i[1],Vs),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=ir),de){let Fr=d*x*k;ut=i[0].reshape([1,gt,Fr]),vt=ir.reshape([1,Fr,te]),Dt=[1,gt,te]}else ut=i[0].reshape([gt,d*x,k]),vt=ir.reshape([1,k,te]),Dt=[gt,v*oe,te];Rt.push(ut),Rt.push(vt)}else ut=i[0].reshape([gt,k,d*x]),vt=i[1].reshape([1,te,k]),Dt=[gt,te,v*oe],Rt.push(vt),Rt.push(ut);f&&Rt.push(i[2]);let gr=Dt[2],Mr=Rt[0].dims[Rt[0].dims.length-1];gr<8&&Mr<8?n.compute(ol(Rt,u,q,Dt,c),{inputs:Rt}):n.compute(tl(Rt,u,q,Dt,c),{inputs:Rt});return}let we=!0,be=n.kernelCustomData.wT??n.compute(hi(i[1],Vs),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=be);let he=[i[0],be];f&&he.push(i[2]);let De=c?v*oe:te,Ae=c?te:v*oe,Ie=$*H*k;n.compute(lf(he,u,q,De,Ae,Ie,f,we),{inputs:he})},ld=(n,i)=>{let s=i.format==="NHWC",u=[n.inputs[0].reshape(s?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&u.push(n.inputs[2]);let c=[0,i.pads[0],0,i.pads[1]],f=[1].concat(i.strides),d=[1].concat(i.dilations),x=[1].concat(i.kernelShape),k=Ws({...i,pads:c,strides:f,dilations:d,kernelShape:x},u);n.compute(id(u,k,$=>s?[$[0],$[2],$[3]]:[]))},ud=(n,i,s)=>{let u=s.format==="NHWC"?"channelsLast":"channelsFirst",c=Ws(s,i),f=s.autoPad==="NOTSET"?s.pads:s.autoPad,d=rd(i[0].dims,i[1].dims,s.strides,s.dilations,f,!1,u);n.compute(nd(i,c,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],u))},Ko=(n,i)=>{al(n.inputs,i),n.inputs[0].dims.length===3?ld(n,i):n.inputs[0].dims.length===5?ud(n,n.inputs,i):ul(n,n.inputs,i)}}),dd,pd,df=h(()=>{Zt(),jn(),ar(),Gi(),xo(),Xc(),js(),dd=(n,i=!1,s,u,c=4)=>{let f=we=>{switch(we){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 ${we} is not supported.`)}},d=n?` let coord = vec4<i32>(batch, iXR, iXC, xCh); `:` let coord = vec4<i32>(batch, xCh, iXR, iXC); `,x=n?` let coords = vec4<i32>( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4<i32>( batch, row, col / outWidth, col % outWidth); `,k=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",$=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",H=n?"row":"col",q=n?"col":"row",v=` let inChannels = ${n?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${H} / outWidth; let outCol = ${H} % outWidth; let WRow = ${q} / (uniforms.filter_dims[1] * inChannels); let WCol = ${q} / 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(${k}) || fract(xR) > 0.0) { return ${u}(0.0); } if (xC < 0.0 || xC >= f32(${$}) || fract(xC) > 0.0) { return ${u}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${q} % inChannels; ${d} return x[getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape))/${c}];`,oe=n?` 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);`,te=` let col = colIn * ${c}; let inChannels = ${n?"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 (${n?"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); ${f(c)} } return ${u}(0.0); `,de=Vi(s,u);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${u} { ${n?oe:te} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${u} { ${n?te:oe} } 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 = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${x} ${Za(i)} ${de} result[getIndexFromCoords4D(coords, vec4<i32>(uniforms.result_shape))/${c}] = value; } }`},pd=(n,i,s,u,c,f,d,x)=>{let k=i.format==="NHWC",$=k?n[0].dims[3]:n[0].dims[1],H=s[0],q=k?s[2]:s[3],v=k?s[1]:s[2],oe=k?s[3]:s[1],te=k&&$%4===0&&$%3&&oe%4===0,de=k?oe:q*v,we=k?q*v:oe,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],De=[Math.ceil(de/be[0]/he[0]),Math.ceil(we/be[1]/he[1]),Math.ceil(H/be[2]/he[2])];Vr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${De}`);let Ae=te?4:1,Ie=Math.max(be[0]*Ae,be[1]),gt=te?4:1,ut=[i.kernelShape[k?1:2],i.kernelShape[k?2:3]],vt=[ut[0]+(i.dilations[0]<=1?0:(ut[0]-1)*(i.dilations[0]-1)),ut[1]+(i.dilations[1]<=1?0:(ut[1]-1)*(i.dilations[1]-1))],Dt=[vt[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),vt[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Rt=[{type:6,data:u},{type:6,data:c},{type:6,data:f},{type:6,data:i.strides},{type:6,data:i.dilations},{type:6,data:ut},{type:6,data:Dt}];Wi(i,Rt),Rt.push(...At(n[0].dims,n[1].dims));let gr=["rank","rank"];d&&(Rt.push(...At(n[2].dims)),gr.push("rank")),Rt.push(...At(s));let Mr=ir=>{let Fr=_t("x",n[0].dataType,n[0].dims.length,gt),Zr=_t("w",n[1].dataType,n[1].dims.length,1),hr=Gt("result",n[0].dataType,s.length,gt),Hr=[Fr,Zr],Nt="";if(d){let ot=_t("bias",n[2].dataType,n[2].dims.length,gt);Hr.push(ot),Nt+=` fn getBiasByOutputCoords(coords : vec4<i32>) -> ${ot.type.value} { return bias[coords.${k?"w":"y"}${te?"/ 4":""}]; }`}let er=[{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:ut.length},{name:"pads",type:"i32",length:Dt.length}];Ei(i,er);let yr=Sr(n[0].dataType,1);if(yr!=="f16"&&yr!=="f32")throw new Error(`elemType ${yr} is not supported.`);return` ${Ja("uniforms.result_strides")} ${ir.registerUniforms(er).declareVariables(...Hr,hr)}; ${Nt} ${dd(k,d,i,Fr.type.value,Ae)} ${te?Rs(he,be,yr,void 0,!k,Ie):Bs(he,be,yr,void 0,!k,Ie,!1,void 0,x)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${i.cacheKey};${he};${be};${te}`,inputDependencies:gr},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:De[0],y:De[1],z:De[2]},programUniforms:Rt}),getShaderSource:Mr}}}),cl,Xo,mm=h(()=>{Zt(),jn(),Jt(),ar(),cl=(n,i,s,u,c,f=!1,d,x,k=!1)=>{let $=k?1:2,H=k?2:3,q=k?3:1,v=f?2:1,oe=` fn setOutputAtIndex(flatIndex : u32, value : ${f?`vec4<${d}>`:d}) { result[flatIndex] = ${f?`vec4<${d}>`:d}(value); }`;u&&(oe+=` fn getBiasByOutputCoords(coords : vec4<u32>) -> ${f?`vec4<${d}>`:d} { return bias[coords.${k?"w":"y"}${f?"/ 4":""}]; }`);let te=f?4:1,de=_t("W",i[1].dataType,i[1].dims.length,te),we=_t("Dy",i[0].dataType,i[0].dims.length,te),be=[we,de];u&&be.push(_t("bias",i[2].dataType,[s[q]].length,te));let he=Gt("result",i[0].dataType,s.length,te),De=`{ 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 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${we.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 = ${we.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[${q}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${we.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 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${we.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")}; } }`,Ae=` let outputIndices = ${he.offsetToIndices("global_idx")}; let batch = ${he.indicesGet("outputIndices",0)}; let d1 = ${he.indicesGet("outputIndices",q)}; let r = ${he.indicesGet("outputIndices",$)}; let c = ${he.indicesGet("outputIndices",H)}; 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[${$}]) || 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[${H}]) || 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 = ${k?we.get("batch","idyR","idyC","inputChannel"):we.get("batch","inputChannel","idyR","idyC")}; let wValue = ${de.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` ${n.registerUniforms(x).declareVariables(...be,he)} ${oe} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${f?De:Ae}}`},Xo=(n,i,s)=>{let u=n.length>2,c=i.outputShape,f=ct.size(c),d=[Math.ceil(f/64),1,1];Vr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${d}`);let x=i.format==="NHWC",k=["rank","rank"],$=[i.strides[0],i.strides[1]],H=[i.kernelShape[x?1:2],i.kernelShape[x?2:3]],q=[i.dilations[0],i.dilations[1]],v=[H[0]+(i.dilations[0]<=1?0:(i.kernelShape[x?1:2]-1)*(i.dilations[0]-1)),H[1]+(i.dilations[1]<=1?0:(i.kernelShape[x?2:3]-1)*(i.dilations[1]-1))],oe=[v[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),v[1]-1-Math.floor(i.pads[1]+i.pads[3])/2],te=!1,de=i.group,we=n[1].dims,be=we[0]/de,he=we[1],De=[{type:12,data:f},{type:12,data:$},{type:12,data:H},{type:12,data:q},{type:12,data:v},{type:6,data:oe},{type:12,data:be},{type:12,data:he},...At(n[0].dims,n[1].dims)];u&&(De.push(...At(n[2].dims)),k.push("rank")),De.push(...At(c));let Ae=d[1]===1&&d[2]===1,Ie=gt=>{let ut=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:$.length},{name:"filter_dims",type:"u32",length:H.length},{name:"dilations",type:"u32",length:H.length},{name:"effective_filter_dims",type:"u32",length:v.length},{name:"pads",type:"i32",length:oe.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],vt=Sr(n[0].dataType);return`${cl(gt,n,c,u,Ae,te,vt,ut,x)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${i.cacheKey};`,inputDependencies:k},getRunData:()=>({dispatchGroup:{x:d[0],y:d[1],z:d[2]},outputs:[{dims:s?s(c):c,dataType:n[0].dataType}],programUniforms:De}),getShaderSource:Ie}}}),fd,hd,dl,pl,md,fl,gd,_d,hl,pf,gm=h(()=>{df(),mm(),Gi(),yo(),fd=(n,i,s,u,c,f)=>(n-1)*i+s+(u-1)*c+1-f,hd=(n,i,s,u,c)=>{let f=Math.floor(n/2);i==="SAME_UPPER"?(s[u]=f,s[c]=n-f):i==="SAME_LOWER"&&(s[u]=n-f,s[c]=f)},dl=(n,i,s,u,c,f,d,x,k,$)=>{let H=n.length-2,q=$.length===0;if(k.length===0)for(let te=0;te<H;++te)k.push(0);let v=n[0],oe=i[x?3:1]*c;for(let te=0,de=n.length-H-(x?1:0);te<H;++te,++de){let we=n[de],be=q?we*d[te]:$[te],he=fd(we,d[te],f[te],i[de],s[te],be);hd(he,u,f,te,te+H),q&&$.push(d[te]*(we-1)+k[te]+(i[de]-1)*s[te]+1-f[te]-f[te+H])}$.splice(0,0,v),$.splice(x?3:1,0,oe)},pl=(n,i)=>{let s=n.kernelShape.slice();if(n.kernelShape.length===0||n.kernelShape.reduce((q,v)=>q*v,1)===0){s.length=0;for(let q=2;q<i[1].dims.length;++q)s.push(i[1].dims[q])}let u=n.format==="NHWC";s.splice(0,0,i[1].dims[0]),s.splice(u?3:1,0,i[1].dims[1]);let c=n.pads.slice(),f=n.outputShape.slice(),d=n.outputPadding.slice(),x=i[0].dims,k=n.dilations.slice();if(k.reduce((q,v)=>q+v,0)===0){let q=i[0].dims.length-2;k=new Array(q).fill(1)}let $=n.strides.slice();if($.reduce((q,v)=>q+v,0)===0){let q=i[0].dims.length-2;$=new Array(q).fill(1)}dl(x,s,k,n.autoPad,n.group,c,$,u,d,f);let H=Object.assign({},n);return Object.assign(H,{kernelShape:s,pads:c,outputPadding:d,outputShape:f,dilations:k,strides:$}),H},md=n=>{let i=Ya(n),s=n.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof n.autoPad>"u"?0:n.autoPad],c=n.dilations,f=n.group,d=n.kernelShape,x=n.pads,k=n.strides,$=n.wIsConst(),H=n.outputPadding,q=n.outputShape;return{autoPad:u,format:s,dilations:c,group:f,kernelShape:d,outputPadding:H,outputShape:q,pads:x,strides:k,wIsConst:$,...i,cacheKey:`${n.format};${i.activation};`}},fl=(n,i)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let s=n[0].dims[i.format==="NHWC"?n[0].dims.length-1:1],u=n[1].dims[0];if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let c=n[1].dims[1]*i.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==c))throw new Error("invalid bias");let f=n[0].dims.length-2;if(i.dilations.reduce((d,x)=>d+x,0)>0&&i.dilations.length!==f)throw new Error(`dilations should be ${f}D`);if(i.strides.reduce((d,x)=>d+x,0)>0&&i.strides.length!==f)throw new Error(`strides should be ${f}D`);if(i.pads.reduce((d,x)=>d+x,0)>0&&i.pads.length!==f*2)throw new Error(`pads should be ${f*2}D`);if(i.outputPadding.length!==f&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${f}D`);if(i.kernelShape.reduce((d,x)=>d+x,0)>0&&i.kernelShape.length!==0&&i.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape")},gd=[2,3,1,0],_d=(n,i,s)=>{let u=pl(s,i),c=s.format==="NHWC",f=u.outputShape,d=f[c?3:1],x=i[0].dims[c?3:1];if(u.group!==1||d===1&&x===1){n.compute(Xo(i,u));return}let k=f[c?1:2],$=f[c?2:3],H=i[1].dims[2],q=i[1].dims[3],v=c?k*$:d,oe=c?d:k*$,te=H*q*x,de=!0,we=n.kernelCustomData.wT??n.compute(hi(i[1],gd),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=we);let be=[i[0],we],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])),n.compute(pd(be,u,f,v,oe,te,he,de),{inputs:be})},hl=(n,i)=>{let s=i.format==="NHWC",u=[n.inputs[0].reshape(s?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&u.push(n.inputs[2]);let c=i.kernelShape;(c.length===0||c[0]===0)&&(c=[n.inputs[1].dims[2]]);let f=i.dilations;(f.length===0||f[0]===0)&&(f=[1]);let d=i.strides;(d.length===0||d[0]===0)&&(d=[1]);let x=i.pads;x.length===0&&(x=[0,0]),x=[0,x[0],0,x[1]],d=[1].concat(d),f=[1].concat(f),c=[1].concat(c);let k=pl({...i,pads:x,strides:d,dilations:f,kernelShape:c},u);n.compute(Xo(u,k,$=>s?[$[0],$[2],$[3]]:[$[0],$[1],$[3]]))},pf=(n,i)=>{fl(n.inputs,i),n.inputs[0].dims.length===3?hl(n,i):_d(n,n.inputs,i)}}),ml,gl,wd,ff=h(()=>{Zt(),Jt(),_r(),ar(),ml=(n,i,s,u)=>{let c=ct.size(i),f=i.length,d=_t("input",n,f),x=Gt("output",n,f),k=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),$=ct.normalizeAxis(k,f),H=q=>{let v=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,oe=zt("uniforms.input_shape","uniforms.axis",f),te=u.reverse?v+(u.exclusive?" + 1":""):"0",de=u.reverse?oe:v+(u.exclusive?"":" + 1");return` ${q.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,x)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${x.offsetToIndices("global_idx")}; var sum = ${x.type.value}(0); let first : i32 = ${te}; let last : i32 = ${de}; for (var i : i32 = first; i < last; i++) { ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${d.getByIndices("inputIndices")}; } ${x.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:12,data:$},...At(i,i)]}),getShaderSource:H}},gl=(n,i)=>{let s=n.inputs[0].dims,u=n.inputs[0].dataType,c=n.inputs[1];n.compute(ml(u,s,c,i),{inputs:[0]})},wd=n=>{let i=n.exclusive===1,s=n.reverse===1;return qt({exclusive:i,reverse:s})}}),_l,yd,vd,wl,bd,hf=h(()=>{Zt(),Jt(),_r(),ar(),_l=n=>{if(!n||n.length!==1)throw new Error("DepthToSpace requires 1 input.");if(n[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},yd=(n,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`);for(let f=0;f<i;++f)c.push(s.indicesSet("a",n[f],`i[${f}]`));return c.push("return a;}"),c.join(` `)},vd=(n,i)=>{let s,u,c,f,d,x,k=i.format==="NHWC",$=i.blocksize,H=i.mode==="DCR";k?([s,u,c,f]=n.dims,d=H?[s,u,c,$,$,f/$**2]:[s,u,c,f/$**2,$,$],x=H?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,u,c,f]=[n.dims[0],n.dims[2],n.dims[3],n.dims[1]],d=H?[s,$,$,f/$**2,u,c]:[s,f/$**2,$,$,u,c],x=H?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let q=n.reshape(d),v=q.dims.length,oe=n.dataType,te=_t("a",oe,v),de=Gt("output",oe,v),we=be=>` ${be.registerUniform("output_size","u32").declareVariables(te,de)} ${yd(x,v,te,de)} ${be.mainStart()} ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${de.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${de.setByOffset("global_idx",te.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${n.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:be=>{let he=k?[s,u*$,c*$,f/$**2]:[s,f/$**2,u*$,c*$],De=ct.size(he),Ae=q.dims,Ie=ct.sortBasedOnPerm(Ae,x);return{outputs:[{dims:he,dataType:be[0].dataType}],dispatchGroup:{x:Math.ceil(De/64)},programUniforms:[{type:12,data:De},...At(Ae,Ie)]}},getShaderSource:we}},wl=(n,i)=>{_l(n.inputs),n.compute(vd(n.inputs[0],i))},bd=n=>qt({blocksize:n.blocksize,mode:n.mode,format:n.format})}),Qo,Yo,yl,Rr,mf,gf,_f,Gs,xd,Md,Td,wf=h(()=>{Zt(),Jt(),_r(),ar(),Qo="[a-zA-Z]|\\.\\.\\.",Yo="("+Qo+")+",yl="^"+Yo+"$",Rr="("+Yo+",)*"+Yo,mf="^"+Rr+"$",gf=class{constructor(n=-1){this.symbolToIndices=new Map,this.inputIndex=n}addSymbol(n,i){let s=this.symbolToIndices.get(n);s===void 0?s=[i]:s.push(i),this.symbolToIndices.set(n,s)}},_f=class{constructor(n,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(mf)))throw new Error("Invalid LHS term");if(s.split(",").forEach((f,d)=>{let x=n[d].dims.slice();if(!f.match(RegExp(yl)))throw new Error("Invalid LHS term");let k=this.processTerm(f,!0,x,d);this.lhs.push(k)}),u==="")u+=[...this.symbolToInfo.entries()].filter(([f,d])=>d.count===1||f==="...").map(([f])=>f).join("");else if(!u.match(RegExp(Yo)))throw new Error("Invalid RHS");(c=u.match(RegExp(Qo,"g")))==null||c.forEach(f=>{if(f==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(f);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(u,!1,this.outputDims)}addSymbol(n,i,s){let u=this.symbolToInfo.get(n);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(n,u)}processTerm(n,i,s,u=-1){let c=s.length,f=!1,d=[],x=0;if(!n.match(RegExp(yl))&&!i&&n!=="")throw new Error("Invalid LHS term");let k=n.match(RegExp(Qo,"g")),$=new gf(u);return k==null||k.forEach((H,q)=>{if(H==="..."){if(f)throw new Error("Only one ellipsis is allowed per input term");f=!0;let v=c-k.length+1;if(v<0)throw new Error("Ellipsis out of bounds");if(d=s.slice(x,x+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 oe=0;oe<d.length;oe++){let te=String.fromCharCode(48+oe);$.addSymbol(te,q+oe),this.addSymbol(te,s[x++],u)}}else $.addSymbol(H,q+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(H,s[x++],u)}),$}},Gs=n=>n+"_max",xd=(n,i,s,u)=>{let c=n.map($=>$.length).map(($,H)=>_t(`input${H}`,i,$)),f=ct.size(u),d=Gt("output",i,u.length),x=[...s.symbolToInfo.keys()].filter($=>!s.rhs.symbolToIndices.has($)),k=$=>{let H=[],q="var prod = 1.0;",v="var sum = 0.0;",oe="sum += prod;",te=[],de=[],we=[],be=[],he=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((Ae,Ie)=>{var gt;if(s.rhs.symbolToIndices.has(Ie)){let ut=(gt=s.rhs.symbolToIndices.get(Ie))==null?void 0:gt[0];ut!==void 0&&s.lhs.forEach((vt,Dt)=>{if(Ae.inputIndices.includes(Dt)){let Rt=vt.symbolToIndices.get(Ie);if(Rt===void 0)throw new Error("Invalid symbol error");Rt.forEach(gr=>{H.push(`${c[Dt].indicesSet(`input${Dt}Indices`,gr,d.indicesGet("outputIndices",ut))}`)})}})}else s.lhs.forEach((ut,vt)=>{if(Ae.inputIndices.includes(vt)){let Dt=ut.symbolToIndices.get(Ie);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Rt=>{te.push(`${c[vt].indicesSet(`input${vt}Indices`,Rt,`${Ie}`)}`)}),be.push(`prod *= ${c[vt].getByIndices(`input${vt}Indices`)};`)}}),de.push(`for(var ${Ie}: u32 = 0; ${Ie} < uniforms.${Gs(Ie)}; ${Ie}++) {`),we.push("}")});let De=he?[...H,`let sum = ${c.map((Ae,Ie)=>Ae.getByIndices(`input${Ie}Indices`)).join(" * ")};`]:[...H,v,...de,...te,q,...be,oe,...we];return` ${$.registerUniforms(x.map(Ae=>({name:`${Gs(Ae)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...c,d)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${d.offsetToIndices("global_idx")}; ${c.map((Ae,Ie)=>`var input${Ie}Indices: ${c[Ie].type.indices};`).join(` `)} ${De.join(` `)}; ${d.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:n.map(()=>"rank")},getRunData:()=>{let $=x.filter(q=>s.symbolToInfo.has(q)).map(q=>{var v;return{type:12,data:((v=s.symbolToInfo.get(q))==null?void 0:v.dimValue)||0}});$.push({type:12,data:f});let H=n.map((q,v)=>[...At(q)]).reduce((q,v)=>q.concat(v),$);return H.push(...At(u)),{outputs:[{dims:u,dataType:i}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:H}},getShaderSource:k}},Md=(n,i)=>{let s=new _f(n.inputs,i.equation),u=s.outputDims,c=n.inputs.map((f,d)=>f.dims);n.compute(xd(c,n.inputs[0].dataType,s,u))},Td=n=>{let i=n.equation.replace(/\s+/g,"");return qt({equation:i})}}),vl,Hs,kd,Sd,bl,_m=h(()=>{Zt(),Jt(),ar(),vl=n=>{if(!n||n.length!==2)throw new Error("Expand requires 2 input.");let i=n[0].dims,s=Array.from(n[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")},Hs=(n,i)=>{let s=n.length-i.length,u=[];for(let c=0;c<s;++c)u.push(n[c]);for(let c=0;c<i.length;++c)u.push(i[c]===1?n[c+s]:i[c]);return u},kd=(n,i)=>n.length>i.length?Hs(n,i):Hs(i,n),Sd=n=>{let i=n[0].dims,s=Array.from(n[1].getBigInt64Array(),Number),u=kd(i,s),c=n[0].dataType,f=c===9?4:1,d=Math.ceil(ct.size(u)/f),x=$=>{let H=_t("input",c,i.length,f),q=Gt("output",c,u.length,f),v;if(c===9){let oe=(te,de,we="")=>` let outputIndices${de} = ${q.offsetToIndices(`outputOffset + ${de}u`)}; let offset${de} = ${H.broadcastedIndicesToOffset(`outputIndices${de}`,q)}; let index${de} = offset${de} / 4u; let component${de} = offset${de} % 4u; ${te}[${de}] = ${we}(${H.getByOffset(`index${de}`)}[component${de}]); `;v=` let outputOffset = global_idx * ${f}; var data = vec4<u32>(0); ${oe("data",0,"u32")} ${oe("data",1,"u32")} ${oe("data",2,"u32")} ${oe("data",3,"u32")} ${q.setByOffset("global_idx","data")} }`}else v=` let outputIndices = ${q.offsetToIndices("global_idx")}; let inputOffset = ${H.broadcastedIndicesToOffset("outputIndices",q)}; ${q.setByOffset("global_idx",H.getByOffset("inputOffset"))} }`;return` ${$.registerUniform("vec_size","u32").declareVariables(H,q)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${v}`},k=[{type:12,data:d},...At(i,u)];return{name:"Expand",shaderCache:{hint:`${u.length}`,inputDependencies:["rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:k})}},bl=n=>{vl(n.inputs),n.compute(Sd(n.inputs),{inputs:[0]})}}),yf,Ed,vf=h(()=>{Zt(),Jt(),ar(),Ha(),yf=n=>{let i=n[0].dataType,s=ct.size(n[0].dims),u=ct.size(n[1].dims),c=u%4===0,f=d=>{let x=_t("x",i,[1],4),k=_t("bias",i,[1],4),$=Gt("y",i,[1],4),H=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],q=oe=>` let bias${oe}_offset: u32 = (global_idx * 4 + ${oe}) % uniforms.bias_size; let bias${oe} = ${k.getByOffset(`bias${oe}_offset / 4`)}[bias${oe}_offset % 4];`,v=c?` let bias = ${k.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${q(0)}${q(1)}${q(2)}${q(3)} let bias = ${x.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(H).declareVariables(x,k,$)} ${Va(Er(i))} ${d.mainStart(Un)} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${x.getByOffset("global_idx")}; ${v} let x_in = x + bias; ${$.setByOffset("global_idx",Wa("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${c}`,inputDependencies:["type","type"]},getShaderSource:f,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/Un/4)}})}},Ed=n=>{n.inputs.length<2||ct.size(n.inputs[1].dims)===0?Ec(n):n.compute(yf(n.inputs))}}),Cd,Pd,$d,Ad,bf=h(()=>{Zt(),Jt(),_r(),ar(),Cd=n=>{if(!n||n.length!==2)throw new Error("Gather requires 2 inputs.")},Pd=(n,i)=>{let s=n[0].dims,u=n[1].dims,c=s.length,f=ct.normalizeAxis(i.axis,c),d=s.slice(0);d.splice(f,1,...u);let x=s[f],k=n[0].dataType===9?4:1,$=Math.ceil(ct.size(d)/k),H=[{type:12,data:$},{type:6,data:x},{type:12,data:f},...At(n[0].dims,n[1].dims,d)],q=v=>{let oe=_t("data",n[0].dataType,n[0].dims.length,k),te=_t("inputIndices",n[1].dataType,n[1].dims.length),de=Gt("output",n[0].dataType,d.length,k),we=he=>{let De=u.length,Ae=`var indicesIndices${he} = ${te.type.indices}(0);`;for(let Ie=0;Ie<De;Ie++)Ae+=`${De>1?`indicesIndices${he}[${Ie}]`:`indicesIndices${he}`} = ${d.length>1?`outputIndices${he}[uniforms.axis + ${Ie}]`:`outputIndices${he}`};`;Ae+=` var idx${he} = ${te.getByIndices(`indicesIndices${he}`)}; if (idx${he} < 0) { idx${he} = idx${he} + uniforms.axisDimLimit; } var dataIndices${he} : ${oe.type.indices}; `;for(let Ie=0,gt=0;Ie<c;Ie++)Ie===f?(Ae+=`${c>1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = u32(idx${he});`,gt+=De):(Ae+=`${c>1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = ${d.length>1?`outputIndices${he}[${gt}]`:`outputIndices${he}`};`,gt++);return Ae},be;if(n[0].dataType===9){let he=(De,Ae,Ie="")=>` let outputIndices${Ae} = ${de.offsetToIndices(`outputOffset + ${Ae}u`)}; ${we(Ae)}; let offset${Ae} = ${oe.indicesToOffset(`dataIndices${Ae}`)}; let index${Ae} = offset${Ae} / 4u; let component${Ae} = offset${Ae} % 4u; ${De}[${Ae}] = ${Ie}(${oe.getByOffset(`index${Ae}`)}[component${Ae}]); `;be=` let outputOffset = global_idx * ${k}; var value = vec4<u32>(0); ${he("value",0,"u32")} ${he("value",1,"u32")} ${he("value",2,"u32")} ${he("value",3,"u32")} ${de.setByOffset("global_idx","value")} `}else be=` let outputIndices = ${de.offsetToIndices("global_idx")}; ${we("")}; let value = ${oe.getByIndices("dataIndices")}; ${de.setByOffset("global_idx","value")}; `;return` ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(oe,te,de)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${be} }`};return{name:"Gather",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:H}),getShaderSource:q}},$d=n=>qt({axis:n.axis}),Ad=(n,i)=>{let s=n.inputs;Cd(s),n.compute(Pd(n.inputs,i))}}),Id,Fd,Od,zd,xf=h(()=>{Zt(),Jt(),_r(),ar(),Id=n=>{if(!n||n.length!==2)throw new Error("GatherElements requires 2 inputs.");if(n[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(n[0].dims.length!==n[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},Fd=(n,i)=>{let s=n[0].dims,u=n[0].dataType,c=s.length,f=n[1].dims,d=n[1].dataType,x=ct.normalizeAxis(i.axis,c),k=s[x],$=f.slice(0),H=ct.size($),q=_t("input",u,c),v=_t("indicesInput",d,f.length),oe=Gt("output",u,$.length),te=[{type:12,data:H},{type:6,data:k},{type:12,data:x}];return te.push(...At(s,f,$)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:$,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:te}),getShaderSource:de=>` ${de.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(q,v,oe)} ${de.mainStart()} ${de.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${oe.offsetToIndices("global_idx")}; var idx = ${v.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${q.type.indices}(outputIndices); ${q.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${q.getByIndices("inputIndices")}; ${oe.setByOffset("global_idx","value")}; }`}},Od=n=>qt({axis:n.axis}),zd=(n,i)=>{let s=n.inputs;Id(s),n.compute(Fd(n.inputs,i))}}),Dd,Ld,Rd,Mf,Bd=h(()=>{Zt(),Jt(),ar(),Dd=n=>{if(!n)throw new Error("Input is missing");if(n.length<2||n.length>3)throw new Error("Invaid input number.");if(n.length===3&&n[2].dims.length>2)throw new Error("Invalid input shape of C");if(n[0].dataType!==n[1].dataType||n.length===3&&n[0].dataType!==n[2].dataType)throw new Error("Input types are mismatched")},Ld=(n,i)=>{let s=n[0].dims.slice(),u=n[1].dims.slice(),[c,f,d]=Tr.getShapeOfGemmResult(s,i.transA,u,i.transB,n.length===3?n[2].dims:void 0),x=[c,f];if(!x)throw new Error("Can't use gemm on the given tensors");let k=ct.size(x),$=[{type:12,data:k},{type:12,data:c},{type:12,data:f},{type:12,data:d},{type:1,data:i.alpha},{type:1,data:i.beta}],H=["type","type"];n.length===3&&($.push(...At(n[2].dims)),H.push("rank")),$.push(...At(x));let q=v=>{let oe="";i.transA&&i.transB?oe="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":i.transA&&!i.transB?oe="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!i.transA&&i.transB?oe="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!i.transA&&!i.transB&&(oe="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let te=i.alpha===1?"":"value *= uniforms.alpha;",de=_t("a",n[0].dataType,n[0].dims),we=_t("b",n[1].dataType,n[1].dims),be=de.type.value,he=null,De=[de,we];n.length===3&&(he=_t("c",n[2].dataType,n[2].dims.length),De.push(he));let Ae=Gt("output",n[0].dataType,x.length);De.push(Ae);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(...De)} ${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++) { ${oe} } ${te} ${he!=null?`let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)",Ae)}; value += ${be}(uniforms.beta) * ${he.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:x,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:q}},Rd=n=>{let i=n.transA,s=n.transB,u=n.alpha,c=n.beta;return{transA:i,transB:s,alpha:u,beta:c,cacheKey:`${n.transA};${n.transB};${n.alpha===1}`}},Mf=(n,i)=>{Dd(n.inputs),n.compute(Ld(n.inputs,i))}}),Pn,Nd,jd,xl,Ud,Zo,Vd,Wd=h(()=>{Zt(),Jt(),_r(),pe(),zs(),ar(),yo(),Pn=(n,i)=>n.length>i&&n[i].dims.length>0&&ct.size(n[i].dims)>0?n[i]:void 0,Nd=(n,i)=>{let s=n[0],u=Pn(n,1),c=Pn(n,2),f=Pn(n,3),d=Pn(n,4),x=Pn(n,5),k=Pn(n,6),$=Pn(n,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let H=!1,q=s.dims[0],v=s.dims[1],oe=s.dims.length===3?H?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],te=v,de=0,we=0,be=Math.floor(oe/i.numHeads);if(k&&$){if(k.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(k.dims[0]!==q||k.dims[1]!==i.numHeads||k.dims[3]!==be)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if($.dims[0]!==q||$.dims[1]!==i.numHeads||$.dims[3]!==be)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(k.dims[2]!==$.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if($.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');de=k.dims[2],we=k.dims[2]}else if(k||$)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(u.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');he=2,te=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==be)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,te=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==be)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,te=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}if(f){if(f.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(c&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let De=0;if(d){De=8;let vt=d.dims;throw vt.length===1?vt[0]===q?De=1:vt[0]===3*q+2&&(De=3):vt.length===2&&vt[0]===q&&vt[1]===te&&(De=5),De===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let Ae=!1,Ie=oe;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(te!==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(te!==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],Ae=!0}}let gt=de+te,ut=!1;if(d)throw new Error("Key padding mask is not supported");if(x){if(x.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(x.dims[0]!==q&&x.dims[0]!==1||x.dims[1]!==i.numHeads||x.dims[2]!==v||x.dims[3]!==gt)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:q,sequenceLength:v,pastSequenceLength:de,kvSequenceLength:te,totalSequenceLength:gt,maxSequenceLength:we,inputHiddenSize:0,hiddenSize:oe,vHiddenSize:Ie,headSize:be,vHeadSize:Math.floor(Ie/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:De,scale:i.scale,broadcastResPosBias:ut,passPastInKv:Ae,qkvFormat:he}},jd=n=>qt({...n}),xl=qt({perm:[0,2,1,3]}),Ud=(n,i,s,u,c,f,d)=>{let x=[u,c,f],k=ct.size(x),$=[{type:12,data:k},{type:12,data:d},{type:12,data:f}],H=q=>{let v=Gt("qkv_with_bias",i.dataType,x),oe=_t("qkv",i.dataType,x),te=_t("bias",s.dataType,x),de=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${q.registerUniforms(de).declareVariables(oe,te,v)} ${q.mainStart()} ${q.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 n.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:x,dataType:i.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:H},{inputs:[i,s],outputs:[-1]})[0]},Zo=(n,i,s,u,c,f,d,x)=>{let k=f;if(d){if(u===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return k=Ud(n,f,d,i,u,s*c,x),k=k.reshape([i,u,s,c]),n.compute(hi(k,xl.perm),{inputs:[k],outputs:[-1]})[0]}else return f.dims.length===3&&(k=f.reshape([i,u,s,c])),n.compute(hi(k,xl.perm),{inputs:[k],outputs:[-1]})[0]},Vd=(n,i)=>{let s=Nd(n.inputs,i),u=n.inputs[0],c=Pn(n.inputs,1),f=Pn(n.inputs,2),d=Pn(n.inputs,3),x=Pn(n.inputs,4),k=Pn(n.inputs,5),$=Pn(n.inputs,6),H=Pn(n.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 q=c&&f&&c.dims.length===4&&f.dims.length===4,v=Zo(n,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,d,0);if(q)return vo(n,v,c,f,x,void 0,$,H,k,s,i);if(!c||!f)throw new Error("key and value must be provided");let oe=Zo(n,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,c,d,s.hiddenSize),te=Zo(n,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,f,d,2*s.hiddenSize);vo(n,v,oe,te,x,void 0,$,H,k,s,i)}}),Ml,Gd,Hd,Tl,qd,Kd=h(()=>{Zt(),Jt(),ar(),Ml=n=>Array.from(n.getBigInt64Array(),Number),Gd=n=>{if(!n||n.length!==2)throw new Error("Tile requires 2 inputs.");if(n[0].dataType!==1&&n[0].dataType!==10&&n[0].dataType!==6&&n[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(n[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(n[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ml(n[1]).length!==n[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Hd=(n,i)=>{let s=[];for(let u=0;u<n.length;++u)s.push(n[u]*i[u]);return s},Tl=(n,i)=>{let s=n[0].dims,u=i??Ml(n[1]),c=Hd(s,u),f=ct.size(c),d=n[0].dataType,x=_t("input",d,s.length),k=Gt("output",d,c.length),$=H=>` const inputShape = ${x.indices(...s)}; ${H.registerUniform("output_size","u32").declareVariables(x,k)} ${H.mainStart()} ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${k.offsetToIndices("global_idx")}; var input_indices: ${x.type.indices}; for (var i = 0; i < ${s.length}; i++) { let input_dim_i = ${x.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${k.indicesGet("output_indices","i")} % input_dim_i; ${x.indicesSet("input_indices","i","input_dim_value")} } ${k.setByOffset("global_idx",x.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${u}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:c,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...At(n[0].dims,c)]}),getShaderSource:$}},qd=n=>{Gd(n.inputs),n.compute(Tl(n.inputs),{inputs:[0]})}}),Xd,kl,Qd,Yd,Sl,Zd,Tf=h(()=>{Zt(),Jt(),_r(),zs(),ar(),Wd(),Kd(),yo(),Xd=(n,i)=>{let s=n[0],u=n[1],c=n[2],f=n[3],d=n[4];if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let x=!1,k=s.dims[0],$=s.dims[1],H=s.dims.length===3?x?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],q=$,v=0,oe=0,te=Math.floor(H/i.numHeads),de=f&&f.dims.length!==0,we=d&&d.dims.length!==0,be=!0;if(de&&we){if(f.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=f.dims[1],oe=f.dims[1]}else if(de||we)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,q=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==te)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,q=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==te)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,q=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 De=0,Ae=!1,Ie=H;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(q!==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(q!==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],Ae=!0}}let gt=v+q;return{batchSize:k,sequenceLength:$,pastSequenceLength:v,kvSequenceLength:q,totalSequenceLength:gt,maxSequenceLength:oe,inputHiddenSize:0,hiddenSize:H,vHiddenSize:Ie,headSize:te,vHeadSize:Math.floor(Ie/i.kvNumHeads),numHeads:i.numHeads,kvNumHeads:i.kvNumHeads,nReps:i.numHeads/i.kvNumHeads,pastPresentShareBuffer:!1,maskType:De,scale:i.scale,broadcastResPosBias:!1,passPastInKv:Ae,qkvFormat:he,isPastkvBSNH:be}},kl=(n,i,s,u)=>{let c=[u.batchSize,u.totalSequenceLength,u.kvNumHeads,u.headSize],f=4,d=ct.size(c)/f,x=u.totalSequenceLength,k=Gt("present_kv",s,c.length,f),$=_t("new_kv",n.dataType,n.dims.length,f),H=i?_t("past_kv",i.dataType,i.dims.length,f):void 0,q=Math.ceil(u.headSize/f),v={x,y:n.dims[0],z:1},oe=i?["rank","rank"]:["rank"],te=[{type:12,data:d},{type:12,data:u.pastSequenceLength},{type:12,data:u.kvSequenceLength},{type:12,data:u.totalSequenceLength}],de=[$];H?(te.push(...At(n.dims),...At(i.dims),...At(c)),de.push(H)):te.push(...At(n.dims),...At(c));let we=[{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];`,De=i?`if (s < past_seqlen) { ${be} } else if (s < past_seqlen + uniforms.new_seqlen) { ${he} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${he} }`,Ae=Ie=>` ${Ie.registerUniforms(we).declareVariables(...de,k)} ${Ie.mainStart([q,u.kvNumHeads,1])} ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${k.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 = ${q}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; ${De} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${u.kvNumHeads}${q}${!!i}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:c,dataType:s}],dispatchGroup:v,programUniforms:te}),getShaderSource:Ae}},Qd=n=>qt({...n}),Yd=qt({perm:[0,2,1,3]}),Sl=(n,i,s,u,c)=>{let f=i,d=u.kvNumHeads,x=u.nReps;return i.dims.length===3&&u.kvSequenceLength!==0&&(f=i.reshape([u.batchSize,u.kvSequenceLength,d,u.headSize])),s?f=n.compute(kl(f,s,f.dataType,u),{inputs:[f,s],outputs:[u.isPastkvBSNH?c:-1]})[0]:f=n.compute(kl(f,void 0,f.dataType,u),{inputs:[f],outputs:[u.isPastkvBSNH?c:-1]})[0],x!==1&&(f=n.compute(Tl([f],[1,1,1,x]),{inputs:[f],outputs:[-1]})[0],f=f.reshape([u.batchSize,u.totalSequenceLength,d*x,u.headSize])),n.compute(hi(f,Yd.perm),{inputs:[f],outputs:[-1]})[0]},Zd=(n,i)=>{var k;let s=Xd(n.inputs,i);if(n.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((k=n.inputs[1])==null?void 0:k.dims.length)===5)throw new Error("Packed KV is not implemented");let u=Zo(n,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n.inputs[0],void 0,0),c=n.inputs[3]&&n.inputs[3].dims.length!==0?n.inputs[3]:void 0,f=n.inputs[4]&&n.inputs[4].dims.length!==0?n.inputs[4]:void 0,d=Sl(n,n.inputs[1],c,s,1),x=Sl(n,n.inputs[2],f,s,2);vo(n,u,d,x,void 0,void 0,void 0,void 0,void 0,s,i)}}),Jd,ep,tp,rp,wm=h(()=>{Zt(),Jt(),ar(),Jd=(n,i)=>{let s=n[0].dims,u=s,c=2,f=ct.sizeToDimension(s,c),d=ct.sizeFromDimension(s,c),x=vr(d),k=d/x,$=[s[0],s[1],k],H=["rank","type","type"],q=[{type:12,data:d},{type:12,data:k}];q.push(...At($,$));let v=oe=>{let te=_t("x",n[0].dataType,$.length,x),de=_t("scale",n[1].dataType,n[1].dims),we=_t("bias",n[2].dataType,n[2].dims),be=Gt("output",n[0].dataType,$.length,x),he=[te,de,we,be],De=te.type.value,Ae=x===1?"f32":`vec${x}<f32>`,Ie=64,gt=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var<workgroup> meanShared : f32; var<workgroup> squaredNormShared : f32; var<workgroup> workgroupShared : array<${Ae}, ${Ie}>; const workgroupSize = ${Ie}u; ${oe.registerUniforms(gt).declareVariables(...he)} ${oe.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 = ${Ae}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${Ae}(${te.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 = ${Vn("workgroupShared[0]",x)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${Ae}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${Ae}(${te.get("batch","channel","h")}) - ${Ae}(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 = ${Vn("workgroupShared[0]",x)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${i.epsilon})); let channelScale = invStdDev * f32(${de.getByOffset("channel")}); let channelShift = f32(${we.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${te.get("batch","channel","h")} * ${De}(${Ae}(channelScale)) + ${De}(${Ae}(channelShift)); ${be.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${i.epsilon};${x}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:f},programUniforms:q}),getShaderSource:v}},ep=(n,i,s,u,c,f,d,x)=>{let k=vr(d),$=64,H=k===1?"vec2f":`mat2x${k}f`,q=k===1?"f32":`vec${k}f`,v=(gt,ut)=>`${H}(${gt}, ${ut})`,oe=c*d/k,te=Math.ceil(f/$),de=["type"],we=[{type:12,data:te},{type:12,data:f},{type:12,data:Math.floor(d/k)},{type:12,data:Math.floor(f*d/k)}],be=gt=>{let ut=_t("input",i.dataType,i.dims,k);return` ${gt.declareVariables(ut)} @group(0) @binding(1) var<storage, read_write> output : array<${H}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var<uniform> uniforms: Uniforms; ${gt.mainStart($)} let currentImageNumber = global_idx / ${$} / uniforms.C; let currentChannelNumber = (global_idx / ${$}) % 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 = ${Lr("f32",k)}; var squaredSum = ${Lr("f32",k)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${q}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${v("sum","squaredSum")}; }`},he=n.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${k}`,inputDependencies:de},getRunData:()=>({outputs:[{dims:[c,d,$,2],dataType:1}],dispatchGroup:{x:c*d/k},programUniforms:we}),getShaderSource:be},{inputs:[i],outputs:[-1]})[0],De=[{type:12,data:oe},{type:12,data:f},{type:12,data:Math.floor(d/k)},{type:12,data:Math.floor($*d/k)}],Ae=["type","type","type"],Ie=gt=>{let ut=_t("scale",s.dataType,s.dims,k),vt=_t("bias",u.dataType,u.dims,k);return` @group(0) @binding(0) var<storage, read> input : array<${H}>; @group(0) @binding(1) var<storage, read> scale : array<${ut.type.storage}>; @group(0) @binding(2) var<storage, read> bias : array<${vt.type.storage}>; @group(0) @binding(3) var<storage, read_write> output : array<${H}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var<uniform> uniforms: Uniforms; ${gt.mainStart()} ${gt.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 = ${Lr("f32",k)}; var squaredSum = ${Lr("f32",k)}; for (var i: u32 = 0; i < min(${$}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${$}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${x})); let channelScale = invStdDev * ${q}(scale[currentChannelNumber]); let channelShift = ${q}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${v("channelScale","channelShift")}; }`};return n.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${k};${x}`,inputDependencies:Ae},getRunData:()=>({outputs:[{dims:[c,d,2],dataType:1}],dispatchGroup:{x:Math.ceil(oe/64)},programUniforms:De}),getShaderSource:Ie},{inputs:[he,s,u],outputs:[-1]})[0]},tp=(n,i,s)=>{let u=i[0].dims,c=u,f=u[0],d=u[u.length-1],x=ct.sizeFromDimension(u,1)/d,k=vr(d),$=ct.size(c)/k,H=[{type:12,data:x},{type:12,data:Math.floor(d/k)}],q=["type","type"],v=ep(n,i[0],i[1],i[2],f,x,d,s.epsilon),oe=te=>{let de=Sr(i[0].dataType),we=k===1?"vec2f":`mat2x${k}f`,be=k===1?de:`vec${k}<${de}>`,he=_t("input",i[0].dataType,i[0].dims,k),De=Gt("output",i[0].dataType,c,k);return` @group(0) @binding(0) var<storage, read> input : array<${he.type.storage}>; @group(0) @binding(1) var<storage, read> scaleInput : array<${we}>; @group(0) @binding(2) var<storage, read_write> output : array<${De.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var<uniform> uniforms: Uniforms; ${te.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])); }`};n.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${k}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:c,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:H}),getShaderSource:oe},{inputs:[i[0],v]})},rp=(n,i)=>{i.format==="NHWC"?tp(n,n.inputs,i):n.compute(Jd(n.inputs,i))}}),ur,np,hn,bn=h(()=>{Zt(),Jt(),ar(),ur=n=>{if(!n||n.length<2)throw new Error("layerNorm requires at least 2 inputs.")},np=(n,i,s)=>{let u=i.simplified,c=n[0].dims,f=n[1],d=!u&&n[2],x=c,k=ct.normalizeAxis(i.axis,c.length),$=ct.sizeToDimension(c,k),H=ct.sizeFromDimension(c,k),q=ct.size(f.dims),v=d?ct.size(d.dims):0;if(q!==H||d&&v!==H)throw new Error(`Size of X.shape()[axis:] == ${H}. Size of scale and bias (if provided) must match this. Got scale size of ${q} and bias size of ${v}`);let oe=[];for(let Ie=0;Ie<c.length;++Ie)Ie<k?oe.push(c[Ie]):oe.push(1);let te=vr(H),de=["type","type"],we=[{type:12,data:$},{type:1,data:H},{type:12,data:Math.floor(H/te)},{type:1,data:i.epsilon}];d&&de.push("type");let be=s>1,he=s>2,De=Ie=>{let gt=Sr(n[0].dataType),ut=[_t("x",n[0].dataType,n[0].dims,te),_t("scale",f.dataType,f.dims,te)];d&&ut.push(_t("bias",d.dataType,d.dims,te)),ut.push(Gt("output",n[0].dataType,x,te)),be&&ut.push(Gt("mean_data_output",1,oe)),he&&ut.push(Gt("inv_std_output",1,oe));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(...ut)} ${Ie.mainStart()} ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Lr("f32",te)}; var mean_square_vector = ${Lr("f32",te)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Xr(gt,te,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Vn("mean_vector",te)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Vn("mean_square_vector",te)} / uniforms.norm_size ${u?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Xr(gt,te,"x[j + offset]")}; let f32scale = ${Xr(gt,te,"scale[j]")}; output[j + offset] = ${ut[0].type.value}((f32input ${u?"":"- mean"}) * inv_std_dev * f32scale ${d?`+ ${Xr(gt,te,"bias[j]")}`:""} ); } ${be?"mean_data_output[global_idx] = mean":""}; ${he?"inv_std_output[global_idx] = inv_std_dev":""}; }`},Ae=[{dims:x,dataType:n[0].dataType}];return be&&Ae.push({dims:oe,dataType:1}),he&&Ae.push({dims:oe,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${te};${s};${u}`,inputDependencies:de},getRunData:()=>({outputs:Ae,dispatchGroup:{x:Math.ceil($/64)},programUniforms:we}),getShaderSource:De}},hn=(n,i)=>{ur(n.inputs),n.compute(np(n.inputs,i,n.outputCount))}}),xn,to,kf,ip,Sf=h(()=>{Zt(),Jt(),_r(),ar(),xn=(n,i)=>{if(n.length<3||n.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=n[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),f=i.blockSize/8*i.bits,d=n[1];if(!ct.areEqual(d.dims,[i.n,c,f]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let x=n[2].dims;if(ct.size(x)!==i.n*c)throw new Error("scales input size error.");if(n.length===4){let k=n[3].dims,$=i.bits>4?i.n*c:i.n*Math.floor((c+1)/2);if(ct.size(k)!==$)throw new Error("zeroPoints input size error.")}},to=(n,i,s,u)=>{let c=n[0].dims,f=c.length,d=Math.floor((i.k+i.blockSize-1)/i.blockSize),x=c[f-2],k=i.k,$=i.n,H=c.slice(0,f-2),q=ct.size(H),v=i.blockSize/8*i.bits/4,oe=n[0].dataType,te=vr(x),de=vr(i.k),we=vr(v),be=ki(oe),he=x*d*be,De=Math.floor(u/he),Ae=d<=s[0]&&De>0,Ie=!Ae||De>=4?vr($):De>=2&&vr($)>=2?2:1,gt=H.concat([x,$]),ut=ct.size(gt)/Ie/te,vt=Ae?[]:[{type:12,data:ut},{type:12,data:i.blockSize}],Dt=[q,x,k/de],Rt=ct.convertShape(n[1].dims).slice();Rt.splice(-1,1,v/we),vt.push(...At(Dt)),vt.push(...At(Rt)),vt.push(...At(n[2].dims)),n.length===4&&vt.push(...At(ct.convertShape(n[3].dims)));let gr=[q,x,$/Ie];vt.push(...At(gr));let Mr=ir=>{let Fr=Dt.length,Zr=_t("a",n[0].dataType,Fr,de),hr=_t("b",12,Rt.length,we),Hr=_t("scales",n[2].dataType,n[2].dims.length),Nt=[Zr,hr,Hr],er=n.length===4?_t("zero_points",12,n[3].dims.length):void 0;er&&Nt.push(er);let yr=gr.length,ot=Gt("output",n[0].dataType,yr,Ie),Vt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],nr=Sr(n[0].dataType),Wr=(()=>{switch(de){case 1:return`array<${nr}, 8>`;case 2:return`mat4x2<${nr}>`;case 4:return`mat2x4<${nr}>`;default:throw new Error(`${de}-component is not supported.`)}})(),pn=` for (var word: u32 = 0; word < ${v}; word += ${we}) { ${hr.indicesSet("b_indices","2","word")}; let b_data = ${hr.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${we}; i++) { let b_value: u32 = ${we===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 = ${Wr}(${Array.from({length:4},(rs,si)=>`${nr}(b_value_lower[${si}]), ${nr}(b_value_upper[${si}])`).join(", ")}); let b_dequantized_values = ${de===1?`${Wr}(${Array.from({length:8},(rs,si)=>`(b_quantized_values[${si}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Wr}(${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 < ${Ae?x:te}u; m++) { ${Zr.indicesSet("a_indices",Fr-2,Ae?"m":`row * ${te} + m`)}; ${Zr.indicesSet("a_indices",Fr-1,"word_offset")}; var input_offset = ${Zr.indicesToOffset("a_indices")}; var a_data: ${Wr}; for (var j: u32 = 0; j < ${8/de}; j++) { a_data[j] = ${Zr.getByOffset("input_offset")}; input_offset++; } ${Ae?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${Ie>1?"[c]":""} += ${Array.from({length:8/de},(rs,si)=>`${de===1?`a_data[${si}] * b_dequantized_values[${si}]`:`dot(a_data[${si}], b_dequantized_values[${si}])`}`).join(" + ")}; } word_offset += ${8/de}; } }`,kn=er?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${er.getByOffset("zero_point_index")}; }`:"";return Ae?` var<workgroup> workgroup_shared: array<${ot.type.value}, ${x*d}>; ${ir.declareVariables(...Nt,ot)} ${ir.mainStart([d,1,1])} var a_indices: ${Zr.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${Zr.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${Ie}; c++) { let col_times_components_plus_c = col * ${Ie} + c; ${er?` 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 = ${er.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${hr.type.indices}; ${hr.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 = ${Hr.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${nr}(${er?"(zero_point_word) & 0xFu":8}); ${hr.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${i.blockSize/de}; var workgroup_shared_offset: u32 = block * ${x}; ${pn} } workgroupBarrier(); var output_indices: ${ot.type.indices}; var elements_per_thread: u32 = ${Math.ceil(x/d)}; ${ot.indicesSet("output_indices","0","batch")}; ${ot.indicesSet("output_indices",yr-1,"col")}; ${ot.indicesSet("output_indices",yr-2,"local_id.x * elements_per_thread")}; var output_offset = ${ot.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < elements_per_thread; m++) { var row = m + local_id.x * elements_per_thread; if (row < ${x}) { var output_value: ${ot.type.value} = ${ot.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 += ${x}; } ${ot.setByOffset("output_offset","output_value")}; output_offset += ${$/Ie}; } } }`:` ${ir.registerUniforms(Vt).declareVariables(...Nt,ot)} ${ir.mainStart()} ${ir.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${ot.type.value}, ${te}>; var output_indices = ${ot.offsetToIndices("global_idx")}; var col = ${ot.indicesGet("output_indices",yr-1)}; var row = ${ot.indicesGet("output_indices",yr-2)}; var a_indices: ${Zr.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 ${er?` var zero_point_abs_offset = col * ${Ie} * ((${d} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${er.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${d*Ie}; var b_indices: ${hr.type.indices}; for (var c: u32 = 0; c < ${Ie}; c++) { ${hr.indicesSet("b_indices","0",`col * ${Ie} + 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 = ${Hr.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${nr}(${er?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${hr.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${pn} scale_index++; ${kn} block_offset += uniforms.block_size / ${de}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${er?`if (zero_point_offset % 8 > 0) { ${kn} }`:""} } for (var k: u32 = 0u; k < ${te}u; k++) { ${ot.indicesSet("output_indices",yr-2,`${te} * row + k`)}; ${ot.setByIndices("output_indices","output_values[k]")} } }`};return{name:Ae?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${i.cacheKey};${x};${oe};${n.length}`,inputDependencies:Array(n.length).fill("rank")},getRunData:()=>({outputs:[{dims:gt,dataType:oe}],name:Ae?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:Ae?{x:1,y:Math.ceil($/Ie),z:q}:{x:Math.ceil(ut/64)},programUniforms:vt}),getShaderSource:Mr}},kf=(n,i)=>{xn(n.inputs,i);let s=n.getMaxComputeWorkgroupSizes(),u=n.getMaxComputeWorkgroupStoragesize();n.compute(to(n.inputs,i,s,u))},ip=n=>qt(n)}),V,G,ne,Ee,Ze,it,wt,Ct,Wt,cr=h(()=>{Zt(),Jt(),ar(),V=n=>{if(!n||n.length<1)throw new Error("Too few inputs");if(n[0].dataType!==1&&n[0].dataType!==10)throw new Error("Input type must be float or float16.");if(n.length>=2){let i=n[0].dims.length*2===n[1].dims[0];if(n.length===4&&(i=n[3].dims[0]*2===n[1].dims[0]),!i)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},G=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; if (k < 0) { break; } if (k >= i32(${zt("uniforms.x_shape",c,i)})) { break; } offset += k * i32(${zt("uniforms.x_strides",c,i)}); `;return` value = ${n.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${u} value = x[offset]; } `},ne=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${zt("uniforms.x_shape",c,i)}) - 1); k = k % _2n_1; if(k >= i32(${zt("uniforms.x_shape",c,i)})) { k = _2n_1 - k; } } offset += k * i32(${zt("uniforms.x_strides",c,i)}); `;return` var offset = 0; var k = 0; ${u} value = x[offset]; `},Ee=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; if (k < 0) { k = 0; } if (k >= i32(${zt("uniforms.x_shape",c,i)})) { k = i32(${zt("uniforms.x_shape",c,i)}) - 1; } offset += k * i32(${zt("uniforms.x_strides",c,i)}); `;return` var offset = 0; var k = 0; ${u} value = x[offset]; `},Ze=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; if (k < 0) { k += i32(${zt("uniforms.x_shape",c,i)}]); } if (k >= i32(${zt("uniforms.x_shape",c,i)})) { k -= i32(${zt("uniforms.x_shape",c,i)}); } offset += k * i32(${zt("uniforms.x_strides",c,i)}); `;return` var offset = 0; var k = 0; ${u} value = x[offset]; `},it=(n,i,s)=>{switch(s.mode){case 0:return G(n,i,s.pads.length);case 1:return ne(n,i,s.pads.length);case 2:return Ee(n,i,s.pads.length);case 3:return Ze(n,i,s.pads.length);default:throw new Error("Invalid mode")}},wt=(n,i)=>{let s=ct.padShape(n[0].dims.slice(),i.pads),u=n[0].dims,c=ct.size(s),f=[{type:12,data:c},{type:6,data:i.pads}];i.mode===0&&f.push({type:n[0].dataType,data:i.value}),f.push(...At(n[0].dims,s));let d=["rank"],x=k=>{let $=Gt("output",n[0].dataType,s.length),H=_t("x",n[0].dataType,u.length),q=H.type.value,v=it($,u.length,i),oe=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:i.pads.length}];return i.mode===0&&oe.push({name:"constant_value",type:q}),` ${k.registerUniforms(oe).declareVariables(H,$)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${$.offsetToIndices("global_idx")}; var value = ${q}(0); ${v} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${i.mode}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(ct.size(s)/64)},programUniforms:f}),getShaderSource:x}},Ct=(n,i)=>{if(n.length>1){let s=n[1].getBigInt64Array(),u=n.length>=3&&n[2].data?n[2].getFloat32Array()[0]:0,c=n[0].dims.length,f=new Int32Array(2*c).fill(0);if(n.length>=4){let x=n[3].getBigInt64Array();for(let k=0;k<x.length;k++)f[Number(x[k])]=Number(s[k]),f[Number(x[k])+c]=Number(s[k+x.length])}else s.forEach((x,k)=>f[Number(k)]=Number(x));let d=[];return f.forEach(x=>d.push(x)),{mode:i.mode,value:u,pads:d}}else return i},Wt=(n,i)=>{V(n.inputs);let s=Ct(n.inputs,i);n.compute(wt(n.inputs,s),{inputs:[0]})}}),lr,Ir,dr,wr,pr,mr,xr,Nr,$n,zn,Pi,Mn,dn,Tn,qs,Ks,El,ym,mi,Jo=h(()=>{Z(),Zt(),Jt(),ar(),lr=n=>{if(N.webgpu.validateInputContent&&(!n||n.length!==1))throw new Error("Pool ops requires 1 input.")},Ir=(n,i,s)=>{let u=i.format==="NHWC",c=n.dims.slice();u&&c.splice(1,0,c.pop());let f=Object.hasOwnProperty.call(i,"dilations"),d=i.kernelShape.slice(),x=i.strides.slice(),k=f?i.dilations.slice():[],$=i.pads.slice();Kn.adjustPoolAttributes(s,c,d,x,k,$);let H=Kn.computePoolOutputShape(s,c,x,k,d,$,i.autoPad),q=Object.assign({},i);f?Object.assign(q,{kernelShape:d,strides:x,pads:$,dilations:k,cacheKey:i.cacheKey}):Object.assign(q,{kernelShape:d,strides:x,pads:$,cacheKey:i.cacheKey});let v=H.slice();return v.push(v.splice(1,1)[0]),[q,u?v:H]},dr=(n,i)=>{let s=i.format==="NHWC",u=ct.size(n),c=ct.size(i.kernelShape),f=[{type:12,data:u},{type:12,data:c}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(i.kernelShape.length<=2){let x=i.kernelShape[i.kernelShape.length-1],k=i.strides[i.strides.length-1],$=i.pads[i.pads.length/2-1],H=i.pads[i.pads.length-1],q=!!($+H);f.push({type:12,data:x},{type:12,data:k},{type:12,data:$},{type:12,data:H}),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 oe=i.kernelShape[i.kernelShape.length-2],te=i.strides[i.strides.length-2],de=i.pads[i.pads.length/2-2],we=i.pads[i.pads.length-2];v=!!(de+we),f.push({type:12,data:oe},{type:12,data:te},{type:12,data:de},{type:12,data:we}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[f,d,!0,q,v]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=ct.computeStrides(i.kernelShape);f.push({type:12,data:x},{type:12,data:i.pads},{type:12,data:i.strides}),d.push({name:"kernelStrides",type:"u32",length:x.length},{name:"pads",type:"u32",length:i.pads.length},{name:"strides",type:"u32",length:i.strides.length});let k=i.pads.reduce(($,H)=>$+H);return[f,d,!!k,!1,!1]}},wr=(n,i,s,u,c,f,d,x,k,$,H,q)=>{let v=c.format==="NHWC",oe=i.type.value,te=Gt("output",i.type.tensor,u);if(c.kernelShape.length<=2){let de="",we="",be="",he=s-(v?2:1);if(H?de=` 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")}]; ${f} }`:de=` 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")}]; ${f} }`,c.kernelShape.length===2){let De=s-(v?3:2);q?we=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${De}] = indices[${De}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${De}] < 0 || xIndices[${De}] >= uniforms.x_shape[${De}]) { pad += i32(uniforms.kw); continue; } `:we=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${De}] = indices[${De}] * uniforms.sh - uniforms.phStart + j; `,be=` } `}return` ${n.registerUniforms(k).declareVariables(i,te)} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${te.offsetToIndices("global_idx")}; var xIndices = ${te.offsetToIndices("global_idx")}; var value = ${oe}(${x}); var pad = 0; ${we} ${de} ${be} ${d} output[global_idx] = value; }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let de=c.kernelShape.length,we=c.pads.length,be="";return $?be=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${i.indicesToOffset("xIndices")}]; ${f} }`:be=` } let x_val = x[${i.indicesToOffset("xIndices")}]; ${f} `,` ${n.registerUniforms(k).declareVariables(i,te)} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${te.offsetToIndices("global_idx")}; var xIndices = ${te.offsetToIndices("global_idx")}; var offsets: array<u32, ${de}>; var value = ${oe}(${x}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${de-1}u; j++) { offsets[j] = offset / ${zt("uniforms.kernelStrides","j",de)}; offset -= offsets[j] * ${zt("uniforms.kernelStrides","j",de)}; } offsets[${de-1}] = offset; isPad = false; for (var j = ${s-de}u; j < ${s}u; j++) { xIndices[j] = indices[j] * ${zt("uniforms.strides",`j - ${s-de}u`,de)} + offsets[j - ${s-de}u] - ${zt("uniforms.pads","j - 2u",we)}; ${be} } ${d} output[global_idx] = value; }`}},pr=n=>`${n.format};${n.ceilMode};${n.autoPad};${n.kernelShape.length}`,mr=n=>`${pr(n)};${n.countIncludePad}`,xr=n=>`${pr(n)};${n.storageOrder};${n.dilations}`,Nr=n=>({format:n.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],ceilMode:n.ceil_mode,kernelShape:n.kernel_shape,strides:n.strides,pads:n.pads}),$n=(n,i,s,u)=>{let[c,f]=Ir(i,u,s),d=_t("x",i.dataType,i.dims.length),x=d.type.value,k="value += x_val;",$="";c.countIncludePad?$+=`value /= ${x}(uniforms.kernelSize);`:$+=`value /= ${x}(i32(uniforms.kernelSize) - pad);`;let[H,q,v,oe,te]=dr(f,c);H.push(...At(i.dims,f));let de=["rank"];return{name:n,shaderCache:{hint:`${u.cacheKey};${v};${oe};${te}`,inputDependencies:de},getRunData:()=>({outputs:[{dims:f,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ct.size(f)/64)},programUniforms:H}),getShaderSource:we=>wr(we,d,i.dims.length,f.length,c,k,$,0,q,v,oe,te)}},zn=n=>{let i=n.count_include_pad!==0,s=Nr(n);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:mr(u)}},Pi=(n,i)=>{lr(n.inputs),n.compute($n("AveragePool",n.inputs[0],!1,i))},Mn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},dn=n=>{let i=n.format;return{format:i,...Mn,cacheKey:i}},Tn=(n,i)=>{lr(n.inputs),n.compute($n("GlobalAveragePool",n.inputs[0],!0,i))},qs=(n,i,s,u)=>{let[c,f]=Ir(i,u,s),d=` value = max(x_val, value); `,x="",k=_t("x",i.dataType,i.dims.length),$=["rank"],[H,q,v,oe,te]=dr(f,c);return H.push(...At(i.dims,f)),{name:n,shaderCache:{hint:`${u.cacheKey};${v};${oe};${te}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:f,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ct.size(f)/64)},programUniforms:H}),getShaderSource:de=>wr(de,k,i.dims.length,f.length,c,d,x,i.dataType===10?-65504:-1e5,q,v,oe,te)}},Ks=(n,i)=>{lr(n.inputs),n.compute(qs("MaxPool",n.inputs[0],!1,i))},El=n=>{let i=n.storage_order,s=n.dilations,u=Nr(n);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:xr(c)}},ym=n=>{let i=n.format;return{format:i,...Mn,cacheKey:i}},mi=(n,i)=>{lr(n.inputs),n.compute(qs("GlobalMaxPool",n.inputs[0],!0,i))}}),Ef,Cf,Pf,$f=h(()=>{Z(),Zt(),ar(),Ef=(n,i,s)=>{let u=n===i,c=n<i&&s<0,f=n>i&&s>0;if(u||c||f)throw new Error("Range these inputs' contents are invalid.")},Cf=(n,i,s,u)=>{let c=Math.abs(Math.ceil((i-n)/s)),f=[c],d=c,x=[{type:12,data:d},{type:u,data:n},{type:u,data:s},...At(f)],k=$=>{let H=Gt("output",u,f.length),q=H.type.value,v=[{name:"outputSize",type:"u32"},{name:"start",type:q},{name:"delta",type:q}];return` ${$.registerUniforms(v).declareVariables(H)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${q}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${u}`},getShaderSource:k,getRunData:()=>({outputs:[{dims:f,dataType:u}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:x})}},Pf=n=>{let i=0,s=0,u=0;n.inputs[0].dataType===6?(i=n.inputs[0].getInt32Array()[0],s=n.inputs[1].getInt32Array()[0],u=n.inputs[2].getInt32Array()[0]):n.inputs[0].dataType===1&&(i=n.inputs[0].getFloat32Array()[0],s=n.inputs[1].getFloat32Array()[0],u=n.inputs[2].getFloat32Array()[0]),N.webgpu.validateInputContent&&Ef(i,s,u),n.compute(Cf(i,s,u,n.inputs[0].dataType),{inputs:[]})}}),b0,x0,M0,T0,k0,S0,E0,C0,P0,$0,A0,vm,I0,F0,O0,z0,D0,L0,R0,nx=h(()=>{Zt(),Jt(),_r(),ar(),b0=(n,i)=>{if(n.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),n.length>0){if(i.mode==="linear"){if(!(n.length===2||n.length===3||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1||n.length===5&&n[0]===1&&n[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"&&!(n.length===2||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},x0=(n,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,f)=>u[c]=n[f]),u},M0=(n,i,s,u,c,f)=>{let[d,x,k]=s>10?[1,2,3]:[-1,n.length>1?1:-1,-1],$=n[0].dims.length;if(d>0&&n.length>d&&n[d].dims.length>0)n[d].getFloat32Array().forEach(H=>f.push(H));else if(i.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(x>0&&n.length>x&&n[x].dims.length>0){if(n[x].getFloat32Array().forEach(H=>u.push(H)),u.length!==0&&u.length!==$&&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");b0(u,i),i.axes.length>0&&x0(u,i.axes,$).forEach((H,q)=>u[q]=H)}if(k>0&&n.length>k&&(n[k].getBigInt64Array().forEach(H=>c.push(Number(H))),c.length!==$||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>$)throw new Error("Resize requires only of scales or sizes to be specified")},T0=(n,i)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${i} { `+(()=>{switch(n){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 ${n} is not supported`)}})()+"}",k0=(n,i,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(n){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 ${n} is not supported`)}})()+"}",S0=(n,i,s)=>{let u=new Array(s).fill(0).concat(new Array(s).fill(1)),c=n.length===0?u:n.slice();return i.length>0?(i.forEach((f,d)=>{u[f]=c[d],u[d+s]=c[i.length+d]}),u):c},E0=(n,i,s,u)=>{let c=[];if(s.length>0)if(u.length>0){if(n.forEach(f=>c.push(f)),Math.max(...u)>n.length)throw new Error("axes is out of bound");u.forEach((f,d)=>c[f]=s[d])}else s.forEach(f=>c.push(f));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");c=n.map((f,d)=>Math.round(f*i[d]))}return c},C0=(n,i,s)=>{let u=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(f=>i[f]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(f=>i[f]),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=n.slice();return s.axes.length>0?(s.axes.forEach(f=>i[f]=u),s.axes.forEach(f=>c[f]=Math.round(n[f]*i[f]))):(i.fill(u,0,i.length),c.forEach((f,d)=>c[d]=Math.round(f*i[d]))),c},P0=(n,i,s,u,c)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${n.type.indices}) -> array<${n.type.value}, ${s.length}> { var original_indices: array<${n.type.value}, ${s.length}>; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${n.indicesGet("output_indices","i")}; var scale = ${zt("uniforms.scales","i",u)}; var roi_low = ${zt("uniforms.roi","i",c)}; var roi_hi = ${zt("uniforms.roi",`i + ${i.length}`,c)}; if (scale == 1.0) { original_indices[i] = ${n.type.value}(output_index); } else { var input_shape_i = ${zt("uniforms.input_shape","i",i.length)}; var output_shape_i = ${zt("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; }`,$0=(n,i,s,u,c,f,d)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${i.type.indices}) -> ${n.type.indices} { var input_indices: ${n.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 = ${zt("uniforms.scales","i",c)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${zt("uniforms.roi","i",f)}; var roi_hi = ${zt("uniforms.roi",`i + ${s.length}`,f)}; var input_shape_i = ${zt("uniforms.input_shape","i",s.length)}; var output_shape_i = ${zt("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); } } ${n.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,A0=(n,i)=>` fn checkInputIndices(input_indices: ${n.type.indices}) -> bool { for (var i:u32 = 0; i < ${i.length}; i++) { var input_index = ${n.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${zt("uniforms.input_shape","i",i.length)}) { return false; } } return true; }`,vm=(n,i,s,u)=>n.rank>u?` ${n.indicesSet("input_indices",i,"channel")}; ${n.indicesSet("input_indices",s,"batch")}; `:"",I0=(n,i,s,u,c)=>{let[f,d,x,k]=s.length===2?[-1,0,1,-1]:[0,2,3,1],$=n.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${$} { var input_indices: ${n.type.indices}; ${n.indicesSet("input_indices",d,`max(0, min(row, ${s[d]} - 1))`)}; ${n.indicesSet("input_indices",x,`max(0, min(col, ${s[x]} - 1))`)}; ${vm(n,k,f,2)} return ${n.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${i.type.indices}) -> ${$} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${$} = originalIndices[${d}]; var col:${$} = originalIndices[${x}]; ${u?`if (row < 0 || row > (${s[d]} - 1) || col < 0 || col > (${s[x]} - 1)) { return ${c}; }`:""}; row = max(0, min(row, ${s[d]} - 1)); col = max(0, min(col, ${s[x]} - 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[${k}])`:"0"}; var batch: u32 = ${s.length>2?`u32(originalIndices[${f}])`:"0"}; var x11: ${$} = getInputValue(batch, channel, row1, col1); var x12: ${$} = getInputValue(batch, channel, row1, col2); var x21: ${$} = getInputValue(batch, channel, row2, col1); var x22: ${$} = getInputValue(batch, channel, row2, col2); var dx1: ${$} = abs(row - ${$}(row1)); var dx2: ${$} = abs(${$}(row2) - row); var dy1: ${$} = abs(col - ${$}(col1)); var dy2: ${$} = abs(${$}(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); }`},F0=(n,i,s,u,c,f,d,x,k,$)=>{let H=s.length===2,[q,v]=H?[0,1]:[2,3],oe=n.type.value,te=de=>{let we=de===q?"row":"col";return` fn ${we}CubicInterpolation(input_indices: ${n.type.indices}, output_indices: ${i.type.indices}) -> ${oe} { var output_index = ${i.indicesGet("output_indices",de)}; var originalIdx: ${oe} = getOriginalCoordinateFromResizedCoordinate(output_index, ${c[de]}, ${u[de]}, ${s[de]}, ${f[de]}, ${f[de]} + ${s.length}); var fractOriginalIdx: ${oe} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${x} && (originalIdx < 0 || originalIdx > (${s[de]} - 1))) { return ${k}; } var data: array<${oe}, 4> = array<${oe}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${we}: ${oe} = originalIdx + ${oe}(i); if (${we} < 0 || ${we} >= ${s[de]}) { ${$?`coefs[i + 1] = 0.0; continue;`:x?`return ${k};`:`${we} = max(0, min(${we}, ${s[de]} - 1));`}; } var input_indices_copy: ${n.type.indices} = input_indices; ${n.indicesSet("input_indices_copy",de,`u32(${we})`)}; data[i + 1] = ${de===q?n.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${te(q)}; ${te(v)}; fn getCubicInterpolationCoefs(s: ${oe}) -> array<${oe}, 4> { var absS = abs(s); var coeffs: array<${oe}, 4> = array<${oe}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${oe} = 1.0 - absS; var twoMinusAbsS: ${oe} = 2.0 - absS; var onePlusAbsS: ${oe} = 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<${oe}, 4>, coefs: array<${oe}, 4>) -> ${oe} { var coefsSum: ${oe} = 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}) -> ${oe} { var input_indices: ${n.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},O0=(n,i,s,u,c)=>{let[f,d,x,k,$]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],H=n.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${H} { var input_indices: ${n.type.indices}; ${n.indicesSet("input_indices",d,`max(0, min(depth, ${s[d]} - 1))`)}; ${n.indicesSet("input_indices",x,`max(0, min(height, ${s[x]} - 1))`)}; ${n.indicesSet("input_indices",k,`max(0, min(width, ${s[k]} - 1))`)}; ${vm(n,$,f,3)} return ${n.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${i.type.indices}) -> ${H} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${H} = originalIndices[${d}]; var height:${H} = originalIndices[${x}]; var width:${H} = originalIndices[${k}]; ${u?`if (depth < 0 || depth > (${s[d]} - 1) || height < 0 || height > (${s[x]} - 1) || width < 0 || (width > ${s[k]} - 1)) { return ${c}; }`:""}; depth = max(0, min(depth, ${s[d]} - 1)); height = max(0, min(height, ${s[x]} - 1)); width = max(0, min(width, ${s[k]} - 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[${$}])`:"0"}; var batch: u32 = ${s.length>3?`u32(originalIndices[${f}])`:"0"}; var x111: ${H} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${H} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${H} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${H} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${H} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${H} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${H} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${H} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${H} = abs(depth - ${H}(depth1)); var dx2: ${H} = abs(${H}(depth2) - depth); var dy1: ${H} = abs(height - ${H}(height1)); var dy2: ${H} = abs(${H}(height2) - height); var dz1: ${H} = abs(width - ${H}(width1)); var dz2: ${H} = abs(${H}(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=(n,i,s,u,c,f)=>{let d=n.dims,x=S0(f,i.axes,d.length),k=E0(d,u,c,i.axes),$=u.slice();u.length===0&&($=d.map((he,De)=>he===0?1:k[De]/he),i.keepAspectRatioPolicy!=="stretch"&&(k=C0(d,$,i)));let H=Gt("output",n.dataType,k.length),q=_t("input",n.dataType,d.length),v=ct.size(k),oe=d.length===k.length&&d.every((he,De)=>he===k[De]),te=i.coordinateTransformMode==="tf_crop_and_resize",de=i.extrapolationValue,we=q.type.value,be=he=>` ${oe?"":` ${T0(i.coordinateTransformMode,we)}; ${(()=>{switch(i.mode){case"nearest":return` ${A0(q,d)}; ${k0(i.nearestMode,s,we)}; ${$0(q,H,d,k,$.length,x.length,te)}; `;case"linear":return` ${P0(H,d,k,$.length,x.length)}; ${(()=>{if(d.length===2||d.length===4)return`${I0(q,H,d,te,de)}`;if(d.length===3||d.length===5)return`${O0(q,H,d,te,de)}`;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`${F0(q,H,d,k,$,x,i.cubicCoeffA,te,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",$.length).registerUniform("roi","f32",x.length).declareVariables(q,H)} ${he.mainStart()} ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${oe?"output[global_idx] = input[global_idx];":` let output_indices = ${H.offsetToIndices("global_idx")}; var input_indices: ${q.type.indices}; ${(()=>{switch(i.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${q.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}|${$.length>0?$:""}|${c.length>0?c:""}|${x.length>0?x:""}|${oe}|${d}`,inputDependencies:["rank"]},getShaderSource:be,getRunData:()=>({outputs:[{dims:k,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},{type:1,data:$},{type:1,data:x},...At(d,k)]})}},D0=n=>{let i=n.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},L0=(n,i)=>{let s=[],u=[],c=[],f=D0(n);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");M0(n.inputs,i,f,s,u,c),n.compute(z0(n.inputs[0],i,f,s,u,c),{inputs:[0]})},R0=n=>{let i=n.antialias,s=n.axes,u=n.coordinateTransformMode,c=n.cubicCoeffA,f=n.excludeOutside!==0,d=n.extrapolationValue,x=n.keepAspectRatioPolicy,k=n.mode,$=n.nearestMode===""?"simple":n.nearestMode;return qt({antialias:i,axes:s,coordinateTransformMode:u,cubicCoeffA:c,excludeOutside:f,extrapolationValue:d,keepAspectRatioPolicy:x,mode:k,nearestMode:$})}}),B0,N0,j0,ix=h(()=>{Zt(),Jt(),_r(),ar(),B0=(n,i)=>{let[s,u,c,f]=n,{numHeads:d,rotaryEmbeddingDim:x}=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(!ct.areEqual(u.dims,[])&&!ct.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(f.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${f.dims.length}`);if(!ct.areEqual(c.dims,f.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(x>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let k=s.dims[0],$=s.dims[s.dims.length-2],H=c.dims[0],q=ct.sizeFromDimension(s.dims,1)/$,v=x===0?c.dims[1]*2:q/d;if(x>v)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(u.dims.length===2){if(k!==u.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${u.dims[0]}`);if($!==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]&&x/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($>H)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},N0=(n,i)=>{let{interleaved:s,numHeads:u,rotaryEmbeddingDim:c,scale:f}=i,d=n[0].dims[0],x=ct.sizeFromDimension(n[0].dims,1),k=n[0].dims[n[0].dims.length-2],$=x/k,H=n[2].dims[1],q=c===0?H*2:$/u,v=new Array(d,k,$/q,q-H),oe=ct.computeStrides(v),te=[{type:1,data:f},{type:12,data:v},{type:12,data:oe},...n[0].dims.length===3?new Array({type:12,data:[x,$,q,1]}):[],...n[0].dims.length===4?new Array({type:12,data:[x,q,k*q,1]}):[],...At(n[0].dims,n[1].dims,n[2].dims,n[3].dims,n[0].dims)],de=we=>{let be=_t("input",n[0].dataType,n[0].dims.length),he=_t("position_ids",n[1].dataType,n[1].dims.length),De=_t("cos_cache",n[2].dataType,n[2].dims.length),Ae=_t("sin_cache",n[3].dataType,n[3].dims.length),Ie=Gt("output",n[0].dataType,n[0].dims.length);return we.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:v.length},{name:"global_strides",type:"u32",length:oe.length},{name:"input_output_strides",type:"u32",length:oe.length}]),` ${we.declareVariables(be,he,De,Ae,Ie)} ${we.mainStart(Un)} let half_rotary_emb_dim = uniforms.${De.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${we.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${he.broadcastedIndicesToOffset("bsnh.xy",Gt("",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")} * ${De.get("position_id","bsnh[3]")} - ${be.getByOffset("j")} * ${Ae.get("position_id","bsnh[3]")}; ${Ie.setByOffset("i","re")} let im = ${be.getByOffset("i")} * ${Ae.get("position_id","bsnh[3]")} + ${be.getByOffset("j")} * ${De.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:qt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:de,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(ct.size(v)/Un)},programUniforms:te})}},j0=(n,i)=>{B0(n.inputs,i),n.compute(N0(n.inputs,i))}}),U0,V0,W0,ox=h(()=>{Zt(),Jt(),ar(),U0=n=>{if(!n||n.length<3)throw new Error("layerNorm requires at least 3 inputs.");let i=n[0],s=n[1],u=n[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],f=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]!==f)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(n.length>3){let d=n[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(n.length>4){let d=n[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")}},V0=(n,i,s,u)=>{let c=i.simplified,f=n[0].dims,d=ct.size(f),x=f,k=d,$=f.slice(-1)[0],H=u?f.slice(0,-1).concat(1):[],q=!c&&n.length>3,v=n.length>4,oe=u&&s>1,te=u&&s>2,de=s>3,we=64,be=vr($),he=[{type:12,data:k},{type:12,data:be},{type:12,data:$},{type:1,data:i.epsilon}],De=Ie=>{let gt=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],ut=[_t("x",n[0].dataType,n[0].dims,be),_t("skip",n[1].dataType,n[1].dims,be),_t("gamma",n[2].dataType,n[2].dims,be)];q&&ut.push(_t("beta",n[3].dataType,n[3].dims,be)),v&&ut.push(_t("bias",n[4].dataType,n[4].dims,be)),ut.push(Gt("output",n[0].dataType,x,be)),oe&&ut.push(Gt("mean_output",1,H)),te&&ut.push(Gt("inv_std_output",1,H)),de&&ut.push(Gt("input_skip_bias_sum",n[0].dataType,x,be));let vt=Sr(n[0].dataType),Dt=Sr(1,be);return` ${Ie.registerUniforms(gt).declareVariables(...ut)} var<workgroup> sum_shared : array<${Dt}, ${we}>; var<workgroup> sum_squared_shared : array<${Dt}, ${we}>; ${Ie.mainStart([we,1,1])} let ix = local_id.x; let iy = global_id.x / ${we}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${we}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${we-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; ${de?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Xr(vt,be,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${we}; 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 = ${Vn("sum",be)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Vn("square_sum",be)} / f32(uniforms.hidden_size) ${c?"":"- mean * mean"} + uniforms.epsilon); ${oe?"mean_output[global_idx] = mean;":""} ${te?"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] ${q?"+ beta[offset1d + i]":""}; } }`},Ae=[{dims:x,dataType:n[0].dataType}];return s>1&&Ae.push({dims:H,dataType:1}),s>2&&Ae.push({dims:H,dataType:1}),s>3&&Ae.push({dims:f,dataType:n[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${be};${oe};${te};${de}`,inputDependencies:n.map((Ie,gt)=>"type")},getShaderSource:De,getRunData:()=>({outputs:Ae,dispatchGroup:{x:Math.ceil(k/$)},programUniforms:he})}},W0=(n,i)=>{U0(n.inputs);let s=[0];n.outputCount>1&&s.push(-3),n.outputCount>2&&s.push(-3),n.outputCount>3&&s.push(3),n.compute(V0(n.inputs,i,n.outputCount,!1),{outputs:s})}}),G0,op,H0,bm,q0,K0,X0,Q0,sx=h(()=>{Zt(),Jt(),_r(),ar(),G0=(n,i)=>{if(!n||n.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");n.slice(1).forEach((s,u)=>{if(n[u+1].dataType!==6&&n[u+1].dataType!==7)throw new Error(`Input ${u} must be an array of int32 or int64`)})},op=(n,i)=>{let s=[];if(n.length>i)if(n[i].dataType===7)n[i].getBigInt64Array().forEach(u=>s.push(Number(u)));else if(n[i].dataType===6)n[i].getInt32Array().forEach(u=>s.push(Number(u)));else throw new Error(`Input ${i} must be an array of int32 or int64`);return s},H0=(n,i)=>{if(n.length>1){let s=op(n,1),u=op(n,2),c=op(n,3);return c.length===0&&(c=[...Array(n[0].dims.length).keys()]),qt({starts:s,ends:u,axes:c})}else return i},bm=(n,i,s,u,c)=>{let f=n;return n<0&&(f+=s[u[i]]),c[i]<0?Math.max(0,Math.min(f,s[u[i]]-1)):Math.max(0,Math.min(f,s[u[i]]))},q0=(n,i,s)=>`fn calculateInputIndices(output_indices: ${i.type.indices}) -> ${n.type.indices} { var input_indices: ${n.type.indices}; var carry = 0u; for (var i = ${s.length}; i >= 0; i--) { let input_shape_i = ${zt("uniforms.input_shape","i",s.length)}; let steps_i = ${zt("uniforms.steps","i",s.length)}; let signs_i = ${zt("uniforms.signs","i",s.length)}; let starts_i = ${zt("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; } ${n.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,K0=(n,i)=>{let s=n[0].dims,u=ct.size(s),c=i.axes.length>0?ct.normalizeAxes(i.axes,s.length):[...Array(s.length).keys()],f=op(n,4);f.forEach(be=>be!==0||(()=>{throw new Error("step cannot be 0")})),f.length===0&&(f=Array(c.length).fill(1));let d=i.starts.map((be,he)=>bm(be,he,s,c,f)),x=i.ends.map((be,he)=>bm(be,he,s,c,f));if(c.length!==d.length||c.length!==x.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),x.splice(be,0,s[be]),f.splice(be,0,1));let k=f.map(be=>Math.sign(be));f.forEach((be,he,De)=>{if(be<0){let Ae=(x[he]-d[he])/be,Ie=d[he],gt=Ie+Ae*f[he];d[he]=gt,x[he]=Ie,De[he]=-be}});let $=s.slice(0);c.forEach((be,he)=>{$[be]=Math.ceil((x[be]-d[be])/f[be])});let H={dims:$,dataType:n[0].dataType},q=Gt("output",n[0].dataType,$.length),v=_t("input",n[0].dataType,n[0].dims.length),oe=ct.size($),te=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:k.length},{name:"steps",type:"u32",length:f.length}],de=[{type:12,data:oe},{type:12,data:d},{type:6,data:k},{type:12,data:f},...At(n[0].dims,$)],we=be=>` ${be.registerUniforms(te).declareVariables(v,q)} ${q0(v,q,s)} ${be.mainStart()} ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${q.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${q.setByOffset("global_idx",v.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${k.length}_${d.length}_${f.length}`,inputDependencies:["rank"]},getShaderSource:we,getRunData:()=>({outputs:[H],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:de})}},X0=(n,i)=>{G0(n.inputs,i);let s=H0(n.inputs,i);n.compute(K0(n.inputs,s),{inputs:[0]})},Q0=n=>{let i=n.starts,s=n.ends,u=n.axes;return qt({starts:i,ends:s,axes:u})}}),Y0,Z0,J0,ew,ax=h(()=>{Zt(),Jt(),_r(),ar(),Y0=n=>{if(!n||n.length!==1)throw new Error("Softmax op requires 1 input.")},Z0=(n,i)=>{let s=n.dims,u=ct.size(s),c=64,f=i.axis;if(f<0&&(f=s.length+f),f<s.length-1)throw new Error("softmax only supports last axis for now.");let d=s[f],x=u/d,k=vr(d),$=d/k,H=(we,be)=>be===4?`max(max(${we}.x, ${we}.y), max(${we}.z, ${we}.w))`:be===2?`max(${we}.x, ${we}.y)`:be===3?`max(max(${we}.x, ${we}.y), ${we}.z)`:we,q=_t("x",n.dataType,n.dims,k),v=Gt("result",n.dataType,n.dims,k),oe=q.type.value,te=Sr(n.dataType)==="f32"?`var threadMax = ${oe}(-3.402823e+38f);`:`var threadMax = ${oe}(-65504.0h);`,de=we=>` var<workgroup> rowMaxShared : ${oe}; var<workgroup> rowSumShared : ${oe}; var<workgroup> threadShared : array<${oe}, ${c}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${oe} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${oe}) { let index = row * row_stride + col; result[index] = value; } ${we.registerUniform("packedCols","i32").declareVariables(q,v)} ${we.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 ${te} 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 = ${oe}(${H("threadShared[0]",k)}); } workgroupBarrier(); // find the rows sum var threadSum = ${oe}(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 = ${oe}(${Vn("threadShared[0]",k)}); } 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:`${k}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:s,dataType:n.dataType}],dispatchGroup:{x},programUniforms:[{type:6,data:$}]}),getShaderSource:de}},J0=(n,i)=>{Y0(n.inputs),n.compute(Z0(n.inputs[0],i))},ew=n=>qt({axis:n.axis})}),tw,rw,nw,iw,ow,sw,aw,lx=h(()=>{Zt(),Jt(),_r(),ar(),tw=n=>{if(!n||n.length<1)throw new Error("too few inputs")},rw=(n,i)=>{let s=[],u=i.numOutputs;return n[1].dims[0]>0&&(n[1].getBigInt64Array().forEach(c=>s.push(Number(c))),u=s.length),qt({numOutputs:u,axis:i.axis,splitSizes:s})},nw=n=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${n}u; i += 1u ) { if (index < ${zt("uniforms.size_in_split_axis","i",n)}) { return i; } } return ${n}u; }`,iw=n=>{let i=n.length,s=[];for(let u=0;u<i;++u){let c=n[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: ${n[0].type.indices}, global_idx: u32) { ${s.join(` `)} }`},ow=(n,i)=>{let s=n[0].dims,u=ct.size(s),c=n[0].dataType,f=ct.normalizeAxis(i.axis,s.length),d=new Array(i.numOutputs),x=_t("input",c,s.length),k=new Array(i.numOutputs),$=[],H=[],q=0,v=[{type:12,data:u}];for(let te=0;te<i.numOutputs;te++){q+=i.splitSizes[te],k[te]=q;let de=s.slice();de[i.axis]=i.splitSizes[te],H.push(de),d[te]=Gt(`output${te}`,c,de.length),$.push({dims:H[te],dataType:n[0].dataType})}v.push({type:12,data:k},...At(s,...H));let oe=te=>` ${te.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",k.length).declareVariables(x,...d)} ${nw(k.length)} ${iw(d)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${x.offsetToIndices("global_idx")}; var index = ${x.indicesGet("indices",f)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${zt("uniforms.size_in_split_axis","output_number - 1u",k.length)}; ${x.indicesSet("indices",f,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getShaderSource:oe,getRunData:()=>({outputs:$,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:v})}},sw=(n,i)=>{tw(n.inputs);let s=n.inputs.length===1?i:rw(n.inputs,i);n.compute(ow(n.inputs,s),{inputs:[0]})},aw=n=>{let i=n.axis,s=n.splitSizes,u=n.numOutputs<0?s.length:n.numOutputs;if(u!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qt({axis:i,numOutputs:u,splitSizes:s})}}),lw,uw,cw,ux=h(()=>{Zt(),Jt(),ar(),lw=(n,i,s,u,c)=>{let f=Gt("output_data",c,s.length,4),d=_t("a_data",i[1].dataType,i[1].dims.length,4),x=_t("b_data",i[2].dataType,i[2].dims.length,4),k=_t("c_data",i[0].dataType,i[0].dims.length,4),$,H=(q,v,oe)=>`select(${v}, ${q}, ${oe})`;if(!u)$=f.setByOffset("global_idx",H(d.getByOffset("global_idx"),x.getByOffset("global_idx"),k.getByOffset("global_idx")));else{let q=(v,oe,te="")=>{let de=`a_data[index_a${oe}][component_a${oe}]`,we=`b_data[index_b${oe}][component_b${oe}]`,be=`bool(c_data[index_c${oe}] & (0xffu << (component_c${oe} * 8)))`;return` let output_indices${oe} = ${f.offsetToIndices(`global_idx * 4u + ${oe}u`)}; let offset_a${oe} = ${d.broadcastedIndicesToOffset(`output_indices${oe}`,f)}; let offset_b${oe} = ${x.broadcastedIndicesToOffset(`output_indices${oe}`,f)}; let offset_c${oe} = ${k.broadcastedIndicesToOffset(`output_indices${oe}`,f)}; let index_a${oe} = offset_a${oe} / 4u; let index_b${oe} = offset_b${oe} / 4u; let index_c${oe} = offset_c${oe} / 4u; let component_a${oe} = offset_a${oe} % 4u; let component_b${oe} = offset_b${oe} % 4u; let component_c${oe} = offset_c${oe} % 4u; ${v}[${oe}] = ${te}(${H(de,we,be)}); `};c===9?$=` var data = vec4<u32>(0); ${q("data",0,"u32")} ${q("data",1,"u32")} ${q("data",2,"u32")} ${q("data",3,"u32")} output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:$=` ${q("output_data[global_idx]",0)} ${q("output_data[global_idx]",1)} ${q("output_data[global_idx]",2)} ${q("output_data[global_idx]",3)} `}return` ${n.registerUniform("vec_size","u32").declareVariables(k,d,x,f)} ${n.mainStart()} ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${$} }`},uw=n=>{let i=n[1].dims,s=n[2].dims,u=n[0].dims,c=n[1].dataType,f=!(ct.areEqual(i,s)&&ct.areEqual(s,u)),d=i,x=ct.size(i);if(f){let $=gn.calcShape(gn.calcShape(i,s,!1),u,!1);if(!$)throw new Error("Can't perform where op on the given tensors");d=$,x=ct.size(d)}let k=Math.ceil(x/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:$=>lw($,n,d,f,c),getRunData:()=>({outputs:[{dims:d,dataType:c}],dispatchGroup:{x:Math.ceil(x/64/4)},programUniforms:[{type:12,data:k},...At(u,i,s,d)]})}},cw=n=>{n.compute(uw(n.inputs))}}),dw,cx=h(()=>{nf(),zs(),tc(),of(),Oc(),sf(),af(),cd(),gm(),ff(),hf(),wf(),_m(),vf(),bf(),xf(),Bd(),Tf(),wm(),bn(),sl(),Sf(),Wd(),cr(),Jo(),$f(),$a(),nx(),ix(),ox(),sx(),ax(),lx(),Kd(),yo(),Ha(),ux(),dw=new Map([["Abs",[oc]],["Acos",[sc]],["Acosh",[Fa]],["Add",[Lc]],["ArgMax",[Gu,Os]],["ArgMin",[Wu,Os]],["Asin",[ac]],["Asinh",[lc]],["Atan",[Oa]],["Atanh",[uc]],["Attention",[Qu]],["AveragePool",[Pi,zn]],["BatchNormalization",[ec]],["BiasAdd",[Ia]],["BiasSplitGelu",[Fc]],["Cast",[Ds,cc]],["Ceil",[fc]],["Clip",[pc]],["Concat",[Ui,Kc]],["Conv",[Ko,ll]],["ConvTranspose",[pf,md]],["Cos",[za]],["Cosh",[hc]],["CumSum",[gl,wd]],["DepthToSpace",[wl,bd]],["Div",[Rc]],["Einsum",[Md,Td]],["Elu",[mc,bo]],["Equal",[Ka]],["Erf",[gc]],["Exp",[Da]],["Expand",[bl]],["FastGelu",[Ed]],["Floor",[_c]],["FusedConv",[Ko,ll]],["Gather",[Ad,$d]],["GatherElements",[zd,Od]],["Gelu",[wc]],["Gemm",[Mf,Rd]],["GlobalAveragePool",[Tn,dn]],["GlobalMaxPool",[mi,ym]],["Greater",[Uc]],["GreaterOrEqual",[Wc]],["GroupQueryAttention",[Zd,Qd]],["HardSigmoid",[Ba,Mc]],["InstanceNormalization",[rp]],["LayerNormalization",[hn]],["LeakyRelu",[yc,bo]],["Less",[Vc]],["LessOrEqual",[Xa]],["Log",[Ga]],["MatMul",[ad]],["MatMulNBits",[kf,ip]],["MaxPool",[Ks,El]],["Mul",[Bc]],["MultiHeadAttention",[Vd,jd]],["Neg",[vc]],["Not",[La]],["Pad",[Wt]],["Pow",[Nc]],["QuickGelu",[Ac,bo]],["Range",[Pf]],["Reciprocal",[bc]],["ReduceMin",[Ca]],["ReduceMean",[Lu]],["ReduceMax",[Nu]],["ReduceSum",[Uu]],["ReduceProd",[ju]],["ReduceL1",[Ru]],["ReduceL2",[Ea]],["ReduceLogSum",[Vu]],["ReduceLogSumExp",[Bu]],["ReduceSumSquare",[Pa]],["Relu",[Ra]],["Resize",[L0,R0]],["RotaryEmbedding",[j0]],["Sigmoid",[xc]],["Sin",[Tc]],["Sinh",[kc]],["Slice",[X0,Q0]],["SkipLayerNormalization",[W0]],["Split",[sw,aw]],["Sqrt",[Na]],["Softmax",[J0,ew]],["Sub",[jc]],["Tan",[Sc]],["Tanh",[Ua]],["ThresholdedRelu",[Cc,bo]],["Tile",[qd]],["Transpose",[fu,wa]],["Where",[cw]]])}),pw,dx=h(()=>{Z(),jn(),ar(),pw=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,i){this.repo.set(n,i)}run(n,i,s,u,c){et(n.programInfo.name);let f=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let x=[];for(let $ of i)x.push({binding:x.length,resource:{buffer:$.buffer}});for(let $ of s)x.push({binding:x.length,resource:{buffer:$.buffer}});c&&x.push({binding:x.length,resource:c});let k=f.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:x,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let $={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:k,dispatchGroup:u};this.backend.capturedCommandList.get(this.backend.currentSessionId).push($)}d.setPipeline(n.computePipeline),d.setBindGroup(0,k),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(n.programInfo.name)}dispose(){}build(n,i){et(n.name);let s=this.backend.device,u=[];s.features.has("shader-f16")&&u.push("enable f16;");let c=cu(i,this.backend.device.limits),f=n.getShaderSource(c),d=`${u.join(` `)} ${c.additionalImplementations} ${f}`,x=s.createShaderModule({code:d,label:n.name});Vr("verbose",()=>`[WebGPU] ${n.name} shader code: ${d}`);let k=s.createComputePipeline({compute:{module:x,entryPoint:"main"},layout:"auto",label:n.name});return A(n.name),{programInfo:n,computePipeline:k,uniformVariablesInfo:c.variablesInfo}}normalizeDispatchGroupSize(n){let i=typeof n=="number"?n:n.x,s=typeof n=="number"?1:n.y||1,u=typeof n=="number"?1:n.z||1,c=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(i<=c&&s<=c&&u<=c)return[i,s,u];let f=i*s*u,d=Math.ceil(Math.sqrt(f));if(d>c){if(d=Math.ceil(Math.cbrt(f)),d>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),fw,hw,mw,gw,px=h(()=>{Z(),Zt(),jn(),W(),Ar(),cx(),dx(),fw=(n,i)=>{if(i.length!==n.length)throw new Error(`inputDependencies length ${i.length} is not equal to inputTensors length ${n.length}.`);let s=[];for(let u=0;u<n.length;++u){let c=n[u].dataType;switch(i[u]){case"none":{s.push("");break}case"type":{s.push(`${c}`);break}case"rank":{let f=n[u].dims.length;s.push(`${c};${f}`);break}case"dims":{let f=n[u].dims.join(",");s.push(`${c};${f}`);break}default:throw new Error(`unsupported input dependency: ${i[u]}`)}}return s.join("|")},hw=(n,i,s)=>{var c,f;let u=n.name;return(c=n.shaderCache)!=null&&c.hint&&(u+="["+n.shaderCache.hint+"]"),u+=":"+s+`:${fw(i,((f=n.shaderCache)==null?void 0:f.inputDependencies)??new Array(i.length).fill("dims"))}`,u},mw=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},gw=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 n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,i){this.env=n;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 mw(i.info||await i.requestAdapterInfo()),this.gpuDataManager=tr(this),this.programManager=new pw(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,_o(n.logLevel,!!n.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 n=this.getCommandEncoder(),i={};this.queryType==="at-passes"&&(i.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(i)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;et(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{var u;let i=new BigUint64Array(n.getMappedRange()),s=this.pendingQueries.get(n);for(let c=0;c<i.length/2;c++){let f=s[c],d=f.kernelId,x=this.kernels.get(d),k=x.kernelType,$=x.kernelName,H=f.programName,q=f.inputTensorViews,v=f.outputTensorViews,oe=i[c*2],te=i[c*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=oe);let de=Number(oe-this.queryTimeBase),we=Number(te-this.queryTimeBase);if(!Number.isSafeInteger(de)||!Number.isSafeInteger(we))throw new RangeError("incorrect timestamp range");if((u=this.env.webgpu.profiling)!=null&&u.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:q.map(be=>({dims:be.dims,dataType:fi(be.dataType)})),outputsMetadata:v.map(be=>({dims:be.dims,dataType:fi(be.dataType)})),kernelId:d,kernelType:k,kernelName:$,programName:H,startTime:de,endTime:we});else{let be="";q.forEach((De,Ae)=>{be+=`input[${Ae}]: [${De.dims}] | ${fi(De.dataType)}, `});let he="";v.forEach((De,Ae)=>{he+=`output[${Ae}]: [${De.dims}] | ${fi(De.dataType)}, `}),console.log(`[profiling] kernel "${d}|${k}|${$}|${H}" ${be}${he}execution time: ${we-de} ns`)}je("GPU",`${H}::${oe}::${te}`)}n.unmap(),this.pendingQueries.delete(n)}),A()}run(n,i,s,u,c,f){et(n.name);let d=[];for(let he=0;he<i.length;++he){let De=i[he].data;if(De===0)continue;let Ae=this.gpuDataManager.get(De);if(!Ae)throw new Error(`no GPU data for input: ${De}`);d.push(Ae)}let{outputs:x,dispatchGroup:k,programUniforms:$}=n.getRunData(i),H=s.length===0?x.map((he,De)=>De):s;if(H.length!==x.length)throw new Error(`Output size ${H.length} must be equal to ${x.length}.`);let q=[],v=[];for(let he=0;he<x.length;++he){if(!Number.isInteger(H[he])||H[he]<-3||H[he]>=f)throw new Error(`Invalid output index: ${H[he]}`);if(H[he]===-3)continue;let De=H[he]===-1,Ae=H[he]===-2,Ie=De||Ae?c(x[he].dataType,x[he].dims):u(H[he],x[he].dataType,x[he].dims);if(q.push(Ie),Ie.data===0)continue;let gt=this.gpuDataManager.get(Ie.data);if(!gt)throw new Error(`no GPU data for output: ${Ie.data}`);if(De&&this.temporaryData.push(gt),Ae){let ut=this.kernelPersistentData.get(this.currentKernelId);ut||(ut=[],this.kernelPersistentData.set(this.currentKernelId,ut)),ut.push(gt)}v.push(gt)}if(d.length!==i.length||v.length!==q.length){if(v.length===0)return A(n.name),q;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let oe;if($){let he=0,De=[];$.forEach(ut=>{let vt=typeof ut.data=="number"?[ut.data]:ut.data;if(vt.length===0)return;let Dt=ut.type===10?2:4,Rt,gr;ut.type===10?(gr=vt.length>4?16:vt.length>2?8:vt.length*Dt,Rt=vt.length>4?16:Dt*vt.length):(gr=vt.length<=2?vt.length*Dt:16,Rt=16),he=Math.ceil(he/gr)*gr,De.push(he);let Mr=ut.type===10?8:4;he+=vt.length>4?Math.ceil(vt.length/Mr)*Rt:vt.length*Dt});let Ae=16;he=Math.ceil(he/Ae)*Ae;let Ie=new ArrayBuffer(he);$.forEach((ut,vt)=>{let Dt=De[vt],Rt=typeof ut.data=="number"?[ut.data]:ut.data;if(ut.type===6)new Int32Array(Ie,Dt,Rt.length).set(Rt);else if(ut.type===12)new Uint32Array(Ie,Dt,Rt.length).set(Rt);else if(ut.type===10)new Uint16Array(Ie,Dt,Rt.length).set(Rt);else if(ut.type===1)new Float32Array(Ie,Dt,Rt.length).set(Rt);else throw new Error(`Unsupported uniform type: ${fi(ut.type)}`)});let gt=this.gpuDataManager.create(he,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(gt.buffer,0,Ie,0,he),this.gpuDataManager.release(gt.id),oe={offset:0,size:he,buffer:gt.buffer}}let te=this.programManager.normalizeDispatchGroupSize(k),de=te[1]===1&&te[2]===1,we=hw(n,i,de),be=this.programManager.getArtifact(we);if(be||(be=this.programManager.build(n,te),this.programManager.setArtifact(we,be),Vr("info",()=>`[artifact] key: ${we}, programName: ${n.name}`)),$&&be.uniformVariablesInfo){if($.length!==be.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${be.uniformVariablesInfo.length}, got ${$.length} in program "${be.programInfo.name}".`);for(let he=0;he<$.length;he++){let De=$[he],Ae=De.type,Ie=typeof De.data=="number"?1:De.data.length,[gt,ut]=be.uniformVariablesInfo[he];if(Ae!==gt||Ie!==ut)throw new Error(`Uniform variable ${he} mismatch: expect type ${gt} with size ${ut}, got type ${Ae} with size ${Ie} in program "${be.programInfo.name}".`)}}if(Vr("info",()=>`[ProgramManager] run "${n.name}" (key=${we}) with ${te[0]}x${te[1]}x${te[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let he={kernelId:this.currentKernelId,programName:be.programInfo.name,inputTensorViews:i,outputTensorViews:q};this.pendingKernels.push(he),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(he)}return this.programManager.run(be,d,v,te,oe),A(n.name),q}upload(n,i){this.gpuDataManager.upload(n,i)}memcpy(n,i){this.gpuDataManager.memcpy(n,i)}async download(n,i){await this.gpuDataManager.download(n,i)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,i,s,u){let c=dw.get(n);if(!c)throw new Error(`kernel not implemented: ${n}`);let f={kernelType:n,kernelName:u,kernelEntry:c[0],attributes:[c[1],s]};this.kernels.set(i,f)}releaseKernel(n){let i=this.kernelPersistentData.get(n);if(i){for(let s of i)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,i,s){let u=this.kernels.get(n);if(!u)throw new Error(`kernel not created: ${n}`);let c=u.kernelType,f=u.kernelName,d=u.kernelEntry,x=u.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${f}" is not allowed to be called recursively`);this.currentKernelId=n,x[0]&&(x[1]=x[0](x[1]),x[0]=void 0),Vr("info",()=>`[WebGPU] Start to run kernel "[${c}] ${f}"...`);let k=this.env.debug;this.temporaryData=[];try{return k&&this.device.pushErrorScope("validation"),d(i,x[1]),0}catch($){return s.push(Promise.resolve(`[WebGPU] Kernel "[${c}] ${f}" failed. ${$}`)),1}finally{k&&s.push(this.device.popErrorScope().then($=>$?`GPU validation error for kernel "[${c}] ${f}": ${$.message}`:null));for(let $ of this.temporaryData)this.gpuDataManager.release($.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,i,s,u){let c=this.sessionExternalDataMapping.get(n);c||(c=new Map,this.sessionExternalDataMapping.set(n,c));let f=c.get(i),d=this.gpuDataManager.registerExternalBuffer(s,u,f==null?void 0:f[1]);return c.set(i,[d,s]),d}unregisterBuffers(n){let i=this.sessionExternalDataMapping.get(n);i&&(i.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[1])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let i=this.gpuDataManager.get(n);if(!i)throw new Error(`no GPU data for buffer: ${n}`);return i.buffer}createDownloader(n,i,s){return async()=>{let u=await kt(this,n,i);return Ue(u.buffer,s)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){var n;this.queryType="none",(((n=this.env.webgpu.profiling)==null?void 0:n.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(){Vr("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(){Vr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Vr("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),i=this.capturedPendingKernels.get(this.currentSessionId),s=n.length;this.pendingKernels=[];for(let u=0;u<s;u++){let c=this.getComputePassEncoder(),f=n[u];this.writeTimestamp(this.pendingDispatchNumber*2),c.setPipeline(f.computePipeline),c.setBindGroup(0,f.bindGroup),c.dispatchWorkgroups(...f.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(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),_w={};g(_w,{init:()=>yw});var Af,ww,yw,fx=h(()=>{Zt(),px(),jn(),Jt(),Af=class ex{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=ct.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=ct.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=ct.size(this.dims);return i===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,i)}reshape(i){if(ct.size(i)!==ct.size(this.dims))throw new Error("Invalid new shape");return new ex(this.module,this.dataType,this.data,i)}},ww=class{constructor(n,i,s){this.module=n,this.backend=i,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=i.adapterInfo;let u=n.HEAPU32,c=s>>>2;this.opKernelContext=u[c++];let f=u[c++];this.outputCount=u[c++],this.customDataOffset=u[c++],this.customDataSize=u[c++];let d=[];for(let x=0;x<f;x++){let k=u[c++],$=u[c++],H=u[c++],q=[];for(let v=0;v<H;v++)q.push(u[c++]);d.push(new Af(n,k,$,q))}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(n,i){var d;let s=((d=i==null?void 0:i.inputs)==null?void 0:d.map(x=>typeof x=="number"?this.inputs[x]:x))??this.inputs,u=(i==null?void 0:i.outputs)??[],c=(x,k,$)=>new Af(this.module,k,this.output(x,$),$),f=(x,k)=>{let $=ki(x);if(!$)throw new Error(`Unsupported data type: ${x}`);let H=$*ct.size(k),q=H>0?this.backend.gpuDataManager.create(H).id:0;return new Af(this.module,x,q,k)};return this.backend.run(n,s,u,c,f,this.outputCount)}output(n,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 f=0;f<i.length;f++)this.module.HEAPU32[c++]=i[f];return this.module._JsepOutput(this.opKernelContext,n,u)}catch(u){throw new Error(`Failed to generate kernel's output[${n}] 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)}}},yw=async(n,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(n==="webgpu"){let f=new gw;await f.initialize(s,u),c("webgpu",[f,d=>f.alloc(d),d=>f.free(d),(d,x,k,$=!1)=>{if($)Vr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${x}, size=${k}`),f.memcpy(d,x);else{Vr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${x}, size=${k}`);let H=i.HEAPU8.subarray(d>>>0,(d>>>0)+k);f.upload(x,H)}},async(d,x,k)=>{Vr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${x}, size=${k}`),await f.download(d,()=>i.HEAPU8.subarray(x>>>0,(x>>>0)+k))},(d,x,k)=>f.createKernel(d,x,k,i.UTF8ToString(i._JsepGetNodeName(x))),d=>f.releaseKernel(d),(d,x,k,$)=>{Vr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${k}, kernel=${d}, contextDataOffset=${x}`);let H=new ww(i,f,x);return f.computeKernel(d,H,$)},()=>f.captureBegin(),()=>f.captureEnd(),()=>f.replay()])}else c("webnn")}}),vw,xm,Mm,es,bw,If,Tm,km,Sm,Em,Cm,Pm,xw=h(()=>{Cs(),Ps(),Zt(),wn(),Ni(),jo(),vw=(n,i)=>{Gr()._OrtInit(n,i)!==0&&Dr("Can't initialize onnxruntime.")},xm=async n=>{vw(n.wasm.numThreads,Ji(n.logLevel))},Mm=async(n,i)=>{{let s=(fx(),y(_w)).init;if(i==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let u=n.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=n.webgpu.powerPreference;if(c!==void 0&&c!=="low-power"&&c!=="high-performance")throw new Error(`Invalid powerPreference setting: "${c}"`);let f=n.webgpu.forceFallbackAdapter;if(f!==void 0&&typeof f!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${f}"`);if(u=await navigator.gpu.requestAdapter({powerPreference:c,forceFallbackAdapter:f}),!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",Gr(),n,u)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Gr(),n)}}},es=new Map,bw=n=>{let i=Gr(),s=i.stackSave();try{let u=i.stackAlloc(8);return i._OrtGetInputOutputCount(n,u,u+4)!==0&&Dr("Can't get session input/output count."),[i.HEAP32[u/4],i.HEAP32[u/4+1]]}finally{i.stackRestore(s)}},If=n=>{let i=Gr(),s=i._malloc(n.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return i.HEAPU8.set(n,s),[s,n.byteLength]},Tm=async(n,i)=>{var q,v;let s,u,c=Gr();Array.isArray(n)?[s,u]=n:n.buffer===c.HEAPU8.buffer?[s,u]=[n.byteOffset,n.byteLength]:[s,u]=If(n);let f=0,d=0,x=0,k=[],$=[],H=[];try{if([d,k]=ji(i),(i==null?void 0:i.externalData)&&c.mountExternalData){let Ae=[];for(let Ie of i.externalData){let gt=typeof Ie=="string"?Ie:Ie.path;Ae.push(eo(typeof Ie=="string"?Ie:Ie.data).then(ut=>{c.mountExternalData(gt,ut)}))}await Promise.all(Ae)}for(let Ae of(i==null?void 0:i.executionProviders)??[])if((typeof Ae=="string"?Ae:Ae.name)==="webnn"){if(c.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Ae!="string"){let Ie=Ae,gt=Ie==null?void 0:Ie.context,ut=Ie==null?void 0:Ie.gpuDevice,vt=Ie==null?void 0:Ie.deviceType,Dt=Ie==null?void 0:Ie.numThreads,Rt=Ie==null?void 0:Ie.powerPreference;gt?c.currentContext=gt:ut?c.currentContext=await navigator.ml.createContext(ut):c.currentContext=await navigator.ml.createContext({deviceType:vt,numThreads:Dt,powerPreference:Rt})}else c.currentContext=await navigator.ml.createContext();break}f=await c._OrtCreateSession(s,u,d),f===0&&Dr("Can't create a session."),c.currentContext&&(c.currentContext=void 0);let[oe,te]=bw(f),de=!!(i!=null&&i.enableGraphCapture),we=[],be=[],he=[];for(let Ae=0;Ae<oe;Ae++){let Ie=c._OrtGetInputName(f,Ae);Ie===0&&Dr("Can't get an input name."),$.push(Ie),we.push(c.UTF8ToString(Ie))}for(let Ae=0;Ae<te;Ae++){let Ie=c._OrtGetOutputName(f,Ae);Ie===0&&Dr("Can't get an output name."),H.push(Ie);let gt=c.UTF8ToString(Ie);be.push(gt);{if(de&&(i==null?void 0:i.preferredOutputLocation)===void 0){he.push("gpu-buffer");continue}let ut=typeof(i==null?void 0:i.preferredOutputLocation)=="string"?i.preferredOutputLocation:((q=i==null?void 0:i.preferredOutputLocation)==null?void 0:q[gt])??"cpu";if(ut!=="cpu"&&ut!=="cpu-pinned"&&ut!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ut}.`);if(de&&ut!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ut}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);he.push(ut)}}let De=null;return he.some(Ae=>Ae==="gpu-buffer")&&(x=c._OrtCreateBinding(f),x===0&&Dr("Can't create IO binding."),De={handle:x,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(Ae=>mo(Ae))}),es.set(f,[f,$,H,De,de,!1]),[f,we,be]}catch(oe){throw $.forEach(te=>c._OrtFree(te)),H.forEach(te=>c._OrtFree(te)),x!==0&&c._OrtReleaseBinding(x),f!==0&&c._OrtReleaseSession(f),oe}finally{c._free(s),d!==0&&c._OrtReleaseSessionOptions(d),k.forEach(oe=>c._free(oe)),(v=c.unmountExternalData)==null||v.call(c)}},km=n=>{var k;let i=Gr(),s=es.get(n);if(!s)throw new Error(`cannot release session. invalid session id: ${n}`);let[u,c,f,d,x]=s;d&&(x&&i._OrtClearBoundOutputs(d.handle),i._OrtReleaseBinding(d.handle)),(k=i.jsepOnReleaseSession)==null||k.call(i,n),c.forEach($=>i._OrtFree($)),f.forEach($=>i._OrtFree($)),i._OrtReleaseSession(u),es.delete(n)},Sm=(n,i,s,u,c,f=!1)=>{if(!n){i.push(0);return}let d=Gr(),x=n[0],k=n[1],$=n[3],H,q;if(x==="string"&&$==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(f&&$!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${c} when enableGraphCapture is true.`);if($==="gpu-buffer"){let te=n[2].gpuBuffer,de=ki(fo(x));q=k.reduce((be,he)=>be*he,1)*de;let we=d.jsepRegisterBuffer;if(!we)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');H=we(u,c,te,q)}else{let te=n[2];if(Array.isArray(te)){q=4*te.length,H=d._malloc(q),s.push(H);let de=H/4;for(let we=0;we<te.length;we++){if(typeof te[we]!="string")throw new TypeError(`tensor data at index ${we} is not a string`);d.HEAPU32[de++]=Kr(te[we],s)}}else q=te.byteLength,H=d._malloc(q),s.push(H),d.HEAPU8.set(new Uint8Array(te.buffer,te.byteOffset,q),H)}let v=d.stackSave(),oe=d.stackAlloc(4*k.length);try{let te=oe/4;k.forEach(we=>d.HEAP32[te++]=we);let de=d._OrtCreateTensor(fo(x),H,q,oe,k.length,mo($));de===0&&Dr(`Can't create tensor for input/output. session=${u}, index=${c}.`),i.push(de)}finally{d.stackRestore(v)}},Em=async(n,i,s,u,c,f)=>{var Rt,gr;let d=Gr(),x=es.get(n);if(!x)throw new Error(`cannot run inference. invalid session id: ${n}`);let k=x[0],$=x[1],H=x[2],q=x[3],v=x[4],oe=x[5],te=i.length,de=u.length,we=0,be=[],he=[],De=[],Ae=[],Ie=d.stackSave(),gt=d.stackAlloc(te*4),ut=d.stackAlloc(te*4),vt=d.stackAlloc(de*4),Dt=d.stackAlloc(de*4);try{[we,be]=Ti(f);for(let Nt=0;Nt<te;Nt++)Sm(s[Nt],he,Ae,n,i[Nt],v);for(let Nt=0;Nt<de;Nt++)Sm(c[Nt],De,Ae,n,te+u[Nt],v);let Mr=gt/4,ir=ut/4,Fr=vt/4,Zr=Dt/4;for(let Nt=0;Nt<te;Nt++)d.HEAPU32[Mr++]=he[Nt],d.HEAPU32[ir++]=$[i[Nt]];for(let Nt=0;Nt<de;Nt++)d.HEAPU32[Fr++]=De[Nt],d.HEAPU32[Zr++]=H[u[Nt]];if(q&&!oe){let{handle:Nt,outputPreferredLocations:er,outputPreferredLocationsEncoded:yr}=q;if($.length!==te)throw new Error(`input count from feeds (${te}) is expected to be always equal to model's input count (${$.length}).`);for(let ot=0;ot<te;ot++){let Vt=i[ot];await d._OrtBindInput(Nt,$[Vt],he[ot])!==0&&Dr(`Can't bind input[${ot}] for session=${n}.`)}for(let ot=0;ot<de;ot++){let Vt=u[ot];(Rt=c[ot])!=null&&Rt[3]?d._OrtBindOutput(Nt,H[Vt],De[ot],0)!==0&&Dr(`Can't bind pre-allocated output[${ot}] for session=${n}.`):d._OrtBindOutput(Nt,H[Vt],0,yr[Vt])!==0&&Dr(`Can't bind output[${ot}] to ${er[ot]} for session=${n}.`)}es.set(n,[k,$,H,q,v,!0])}(gr=d.jsepOnRunStart)==null||gr.call(d,k);let hr;q?hr=await d._OrtRunWithBinding(k,q.handle,de,vt,we):hr=await d._OrtRun(k,ut,gt,te,Dt,de,vt,we),hr!==0&&Dr("failed to call OrtRun().");let Hr=[];for(let Nt=0;Nt<de;Nt++){let er=d.HEAPU32[vt/4+Nt];if(er===De[Nt]){Hr.push(c[Nt]);continue}let yr=d.stackSave(),ot=d.stackAlloc(4*4),Vt=!1,nr,Wr=0;try{d._OrtGetTensorData(er,ot,ot+4,ot+8,ot+12)!==0&&Dr(`Can't access output tensor data on index ${Nt}.`);let pn=ot/4,kn=d.HEAPU32[pn++];Wr=d.HEAPU32[pn++];let rs=d.HEAPU32[pn++],si=d.HEAPU32[pn++],gi=[];for(let Ln=0;Ln<si;Ln++)gi.push(d.HEAPU32[rs/4+Ln]);d._OrtFree(rs);let Dn=gi.reduce((Ln,Jn)=>Ln*Jn,1);nr=fi(kn);let lp=q==null?void 0:q.outputPreferredLocations[u[Nt]];if(nr==="string"){if(lp==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ln=[],Jn=Wr/4;for(let $i=0;$i<Dn;$i++){let ns=d.HEAPU32[Jn++],zf=$i===Dn-1?void 0:d.HEAPU32[Jn]-ns;Ln.push(d.UTF8ToString(ns,zf))}Hr.push([nr,gi,Ln,"cpu"])}else if(lp==="gpu-buffer"&&Dn>0){let Ln=d.jsepGetBuffer;if(!Ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Jn=Ln(Wr),$i=ki(kn);if($i===void 0||!ho(nr))throw new Error(`Unsupported data type: ${nr}`);Vt=!0,Hr.push([nr,gi,{gpuBuffer:Jn,download:d.jsepCreateDownloader(Jn,Dn*$i,nr),dispose:()=>{d._OrtReleaseTensor(er)}},"gpu-buffer"])}else{let Ln=Si(nr),Jn=new Ln(Dn);new Uint8Array(Jn.buffer,Jn.byteOffset,Jn.byteLength).set(d.HEAPU8.subarray(Wr,Wr+Jn.byteLength)),Hr.push([nr,gi,Jn,"cpu"])}}finally{d.stackRestore(yr),nr==="string"&&Wr&&d._free(Wr),Vt||d._OrtReleaseTensor(er)}}return q&&!v&&(d._OrtClearBoundOutputs(q.handle),es.set(n,[k,$,H,q,v,!1])),Hr}finally{d.stackRestore(Ie),he.forEach(Mr=>d._OrtReleaseTensor(Mr)),De.forEach(Mr=>d._OrtReleaseTensor(Mr)),Ae.forEach(Mr=>d._free(Mr)),we!==0&&d._OrtReleaseRunOptions(we),be.forEach(Mr=>d._free(Mr))}},Cm=n=>{let i=Gr(),s=es.get(n);if(!s)throw new Error("invalid session id");let u=s[0],c=i._OrtEndProfiling(u);c===0&&Dr("Can't get an profile file name."),i._OrtFree(c)},Pm=n=>{let i=[];for(let s of n){let u=s[2];!Array.isArray(u)&&"buffer"in u&&i.push(u.buffer)}return i}}),ts,oi,Cl,sp,ap,Ff,$m,Of,Xs,Qs,Mw,Tw,kw,Sw,Ew,Cw,Pw,$w,Aw=h(()=>{Z(),xw(),wn(),Yr(),ts=()=>!!N.wasm.proxy&&typeof document<"u",Cl=!1,sp=!1,ap=!1,Of=new Map,Xs=(n,i)=>{let s=Of.get(n);s?s.push(i):Of.set(n,[i])},Qs=()=>{if(Cl||!sp||ap||!oi)throw new Error("worker not ready")},Mw=n=>{switch(n.data.type){case"init-wasm":Cl=!1,n.data.err?(ap=!0,$m[1](n.data.err)):(sp=!0,$m[0]()),Ff&&(URL.revokeObjectURL(Ff),Ff=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=Of.get(n.data.type);n.data.err?i.shift()[1](n.data.err):i.shift()[0](n.data.out);break}}},Tw=async()=>{if(!sp){if(Cl)throw new Error("multiple calls to 'initWasm()' detected.");if(ap)throw new Error("previous call to 'initWasm()' failed.");if(Cl=!0,ts())return new Promise((n,i)=>{oi==null||oi.terminate(),rr().then(([s,u])=>{try{oi=u,oi.onerror=f=>i(f),oi.onmessage=Mw,$m=[n,i];let c={type:"init-wasm",in:N};oi.postMessage(c),Ff=s}catch(c){i(c)}},i)});try{await Mi(N.wasm),await xm(N),sp=!0}catch(n){throw ap=!0,n}finally{Cl=!1}}},kw=async n=>{if(ts())return Qs(),new Promise((i,s)=>{Xs("init-ep",[i,s]);let u={type:"init-ep",in:{epName:n,env:N}};oi.postMessage(u)});await Mm(N,n)},Sw=async n=>ts()?(Qs(),new Promise((i,s)=>{Xs("copy-from",[i,s]);let u={type:"copy-from",in:{buffer:n}};oi.postMessage(u,[n.buffer])})):If(n),Ew=async(n,i)=>{if(ts()){if(i!=null&&i.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Qs(),new Promise((s,u)=>{Xs("create",[s,u]);let c={type:"create",in:{model:n,options:{...i}}},f=[];n instanceof Uint8Array&&f.push(n.buffer),oi.postMessage(c,f)})}else return Tm(n,i)},Cw=async n=>{if(ts())return Qs(),new Promise((i,s)=>{Xs("release",[i,s]);let u={type:"release",in:n};oi.postMessage(u)});km(n)},Pw=async(n,i,s,u,c,f)=>{if(ts()){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 Qs(),new Promise((d,x)=>{Xs("run",[d,x]);let k=s,$={type:"run",in:{sessionId:n,inputIndices:i,inputs:k,outputIndices:u,options:f}};oi.postMessage($,Pm(k))})}else return Em(n,i,s,u,c,f)},$w=async n=>{if(ts())return Qs(),new Promise((i,s)=>{Xs("end-profiling",[i,s]);let u={type:"end-profiling",in:n};oi.postMessage(u)});Cm(n)}}),Am,Iw,Fw,hx=h(()=>{Z(),Aw(),Zt(),ve(),jo(),Am=(n,i)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${n.location} for ${i()}`)}},Iw=n=>{switch(n[3]){case"cpu":return new Ge(n[0],n[2],n[1]);case"gpu-buffer":{let i=n[0];if(!ho(i))throw new Error(`not supported data type: ${i} for deserializing GPU tensor`);let{gpuBuffer:s,download:u,dispose:c}=n[2];return Ge.fromGpuBuffer(s,{dataType:i,dims:n[1],download:u,dispose:c})}default:throw new Error(`invalid data location: ${n[3]}`)}},Fw=class{async fetchModelAndCopyToWasmMemory(n){return Sw(await eo(n))}async loadModel(n,i){et();let s;typeof n=="string"?s=await this.fetchModelAndCopyToWasmMemory(n):s=n,[this.sessionId,this.inputNames,this.outputNames]=await Ew(s,i),A()}async dispose(){return Cw(this.sessionId)}async run(n,i,s){et();let u=[],c=[];Object.entries(n).forEach(q=>{let v=q[0],oe=q[1],te=this.inputNames.indexOf(v);if(te===-1)throw new Error(`invalid input '${v}'`);u.push(oe),c.push(te)});let f=[],d=[];Object.entries(i).forEach(q=>{let v=q[0],oe=q[1],te=this.outputNames.indexOf(v);if(te===-1)throw new Error(`invalid output '${v}'`);f.push(oe),d.push(te)});let x=u.map((q,v)=>Am(q,()=>`input "${this.inputNames[c[v]]}"`)),k=f.map((q,v)=>q?Am(q,()=>`output "${this.outputNames[d[v]]}"`):null),$=await Pw(this.sessionId,c,x,d,k,s),H={};for(let q=0;q<$.length;q++)H[this.outputNames[d[q]]]=f[q]??Iw($[q]);return A(),H}startProfiling(){}endProfiling(){$w(this.sessionId)}}}),Ow,zw,mx=h(()=>{Z(),Aw(),hx(),Yr(),Ow=()=>{if((typeof N.wasm.initTimeout!="number"||N.wasm.initTimeout<0)&&(N.wasm.initTimeout=0),N.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 N.wasm.proxy!="boolean"&&(N.wasm.proxy=!1),typeof N.wasm.trace!="boolean"&&(N.wasm.trace=!1),typeof N.wasm.numThreads!="number"||!Number.isInteger(N.wasm.numThreads)||N.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)N.wasm.numThreads=1;else{let n=typeof navigator>"u"?_("node:os").cpus().length:navigator.hardwareConcurrency;N.wasm.numThreads=Math.min(4,Math.ceil((n||1)/2))}},zw=class{async init(n){Ow(),await Tw(),await kw(n)}async createInferenceSessionHandler(n,i){let s=new Fw;return await s.loadModel(n,i),Promise.resolve(s)}}}),Dw={};g(Dw,{wasmBackend:()=>Lw});var Lw,gx=h(()=>{mx(),Lw=new zw});Z(),Z(),Z();var _x="1.19.0",wx=Ve;{let n=(gx(),y(Dw)).wasmBackend;O("webgpu",n,5),O("webnn",n,5),O("cpu",n,10),O("wasm",n,10)}Object.defineProperty(N.versions,"web",{value:_x,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,r)=>{var o;r.r(t),r.d(t,{Tensor:()=>_.Tensor,createInferenceSession:()=>S,deviceToExecutionProviders:()=>T,isONNXProxy:()=>b,isONNXTensor:()=>C});var a=r("./src/env.js"),l=r("?2ce3"),p=r("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),_=r("./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,y;if(a.apis.IS_NODE_ENV){switch(y=l??(o||(o=r.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 y=p,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 E=y.InferenceSession;function T(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 O=null;async function S(I,U){O&&await O;const z=E.create(I,U);return O??(O=z),await z}function C(I){return I instanceof y.Tensor}const w=y==null?void 0:y.env;w!=null&&w.wasm&&(w.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${a.env.version}/dist/`,w.wasm.proxy=!a.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(w.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(w.wasm.simd=!1)),w!=null&&w.webgpu&&(w.webgpu.powerPreference="high-performance");function b(){var I;return(I=w==null?void 0:w.wasm)==null?void 0:I.proxy}a.env.backends.onnx=w},"./src/configs.js":(e,t,r)=>{r.r(t),r.d(t,{AutoConfig:()=>g,PretrainedConfig:()=>h,getKeyValueShapes:()=>_});var o=r("./src/utils/core.js"),a=r("./src/utils/hub.js");async function l(M,y){return await(0,a.getModelJSON)(M,"config.json",!0,y)}function p(M){const y={};let E={};switch(M.model_type){case"llava":case"paligemma":case"florence2":E=p(M.text_config);break;case"moondream1":E=p(M.phi_config);break;case"musicgen":E=p(M.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":y.num_heads="num_attention_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size",y.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.dim_kv="head_dim";break;case"openelm":y.num_heads="num_kv_heads",y.num_layers="num_transformer_layers",y.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":y.num_heads="num_heads",y.num_layers="num_layers",y.hidden_size="hidden_size";break;case"bloom":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="hidden_size";break;case"mpt":y.num_heads="n_heads",y.num_layers="n_layers",y.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":y.num_decoder_layers="num_decoder_layers",y.num_decoder_heads="num_heads",y.decoder_dim_kv="d_kv",y.num_encoder_layers="num_layers",y.num_encoder_heads="num_heads",y.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":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="d_model",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="d_model";break;case"speecht5":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="hidden_size",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="hidden_size";break;case"trocr":y.num_encoder_layers=y.num_decoder_layers="decoder_layers",y.num_encoder_heads=y.num_decoder_heads="decoder_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="d_model";break;case"musicgen_decoder":y.num_encoder_layers=y.num_decoder_layers="num_hidden_layers",y.num_encoder_heads=y.num_decoder_heads="num_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const O=p(M.decoder),S="num_decoder_layers"in O,C=(0,o.pick)(M,["model_type","is_encoder_decoder"]);return S?(C.num_decoder_layers=O.num_decoder_layers,C.num_decoder_heads=O.num_decoder_heads,C.decoder_hidden_size=O.decoder_hidden_size,C.num_encoder_layers=O.num_encoder_layers,C.num_encoder_heads=O.num_encoder_heads,C.encoder_hidden_size=O.encoder_hidden_size):(C.num_layers=O.num_layers,C.num_heads=O.num_heads,C.hidden_size=O.hidden_size),C}const T={...E,...(0,o.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const O in y)T[O]=M[y[O]];return T}function _(M,{prefix:y="past_key_values"}={}){const E={},T=M.normalized_config,O=1;if(T.is_encoder_decoder&&"num_encoder_heads"in T&&"num_decoder_heads"in T){const S=T.encoder_dim_kv??T.encoder_hidden_size/T.num_encoder_heads,C=T.decoder_dim_kv??T.decoder_hidden_size/T.num_decoder_heads,w=[O,T.num_encoder_heads,0,S],b=[O,T.num_decoder_heads,0,C];for(let I=0;I<T.num_decoder_layers;++I)E[`${y}.${I}.encoder.key`]=w,E[`${y}.${I}.encoder.value`]=w,E[`${y}.${I}.decoder.key`]=b,E[`${y}.${I}.decoder.value`]=b}else{const S=T.num_heads,C=T.num_layers,w=T.dim_kv??T.hidden_size/(T.num_attention_heads??S);if(T.model_type==="falcon"){const b=[O*S,0,w];for(let I=0;I<C;++I)E[`${y}.${I}.key`]=b,E[`${y}.${I}.value`]=b}else if(T.multi_query){const b=[O*S,0,2*w];for(let I=0;I<C;++I)E[`${y}.${I}.key_value`]=b}else if(T.model_type==="bloom"){const b=[O*S,w,0],I=[O*S,0,w];for(let U=0;U<C;++U)E[`${y}.${U}.key`]=b,E[`${y}.${U}.value`]=I}else if(T.model_type==="openelm")for(let b=0;b<C;++b){const I=[O,S[b],0,w];E[`${y}.${b}.key`]=I,E[`${y}.${b}.value`]=I}else{const b=[O,S,0,w];for(let I=0;I<C;++I)E[`${y}.${I}.key`]=b,E[`${y}.${I}.value`]=b}}return E}class h{constructor(y){He(this,"max_position_embeddings");this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,y),this.normalized_config=p(this)}static async from_pretrained(y,{progress_callback:E=null,config:T=null,cache_dir:O=null,local_files_only:S=!1,revision:C="main"}={}){T&&!(T instanceof h)&&(T=new h(T));const w=T??await l(y,{progress_callback:E,config:T,cache_dir:O,local_files_only:S,revision:C});return new this(w)}}class g{static async from_pretrained(...y){return h.from_pretrained(...y)}}},"./src/env.js":(e,t,r)=>{var N;r.r(t),r.d(t,{apis:()=>C,env:()=>B});var o=r("?569f"),a=r("?3f59"),l=r("?154a");const p="3.0.0-alpha.7",_=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope",g=_&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,y=typeof navigator<"u"&&"ml"in navigator,E=typeof process<"u",T=E&&((N=process==null?void 0:process.release)==null?void 0:N.name)==="node",O=!j(o),S=!j(a),C=Object.freeze({IS_BROWSER_ENV:_,IS_WEBWORKER_ENV:h,IS_WEB_CACHE_AVAILABLE:g,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:y,IS_PROCESS_AVAILABLE:E,IS_NODE_ENV:T,IS_FS_AVAILABLE:O,IS_PATH_AVAILABLE:S}),w=O&&S,b=w?a.dirname(a.dirname(l.fileURLToPath(import.meta.url))):"./",I=w?a.join(b,"/.cache/"):null,U="/models/",z=w?a.join(b,U):U,B={version:p,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!_,localModelPath:z,useFS:O,useBrowserCache:g,useFSCache:O,cacheDir:I,useCustomCache:!1,customCache:null};function j(ae){return Object.keys(ae).length===0}},"./src/generation/configuration_utils.js":(e,t,r)=>{r.r(t),r.d(t,{GenerationConfig:()=>a});var o=r("./src/utils/core.js");class a{constructor(p){He(this,"max_length",20);He(this,"max_new_tokens",null);He(this,"min_length",0);He(this,"min_new_tokens",null);He(this,"early_stopping",!1);He(this,"max_time",null);He(this,"do_sample",!1);He(this,"num_beams",1);He(this,"num_beam_groups",1);He(this,"penalty_alpha",null);He(this,"use_cache",!0);He(this,"temperature",1);He(this,"top_k",50);He(this,"top_p",1);He(this,"typical_p",1);He(this,"epsilon_cutoff",0);He(this,"eta_cutoff",0);He(this,"diversity_penalty",0);He(this,"repetition_penalty",1);He(this,"encoder_repetition_penalty",1);He(this,"length_penalty",1);He(this,"no_repeat_ngram_size",0);He(this,"bad_words_ids",null);He(this,"force_words_ids",null);He(this,"renormalize_logits",!1);He(this,"constraints",null);He(this,"forced_bos_token_id",null);He(this,"forced_eos_token_id",null);He(this,"remove_invalid_values",!1);He(this,"exponential_decay_length_penalty",null);He(this,"suppress_tokens",null);He(this,"begin_suppress_tokens",null);He(this,"forced_decoder_ids",null);He(this,"guidance_scale",null);He(this,"num_return_sequences",1);He(this,"output_attentions",!1);He(this,"output_hidden_states",!1);He(this,"output_scores",!1);He(this,"return_dict_in_generate",!1);He(this,"pad_token_id",null);He(this,"bos_token_id",null);He(this,"eos_token_id",null);He(this,"encoder_no_repeat_ngram_size",0);He(this,"decoder_start_token_id",null);He(this,"generation_kwargs",{});Object.assign(this,(0,o.pick)(p,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,r)=>{r.r(t),r.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>h,ForcedEOSTokenLogitsProcessor:()=>g,LogitsProcessor:()=>l,LogitsProcessorList:()=>_,LogitsWarper:()=>p,MinLengthLogitsProcessor:()=>O,MinNewTokensLengthLogitsProcessor:()=>S,NoBadWordsLogitsProcessor:()=>C,NoRepeatNGramLogitsProcessor:()=>E,RepetitionPenaltyLogitsProcessor:()=>T,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>b,TopKLogitsWarper:()=>U,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>y});var o=r("./src/utils/generic.js");r("./src/utils/tensor.js");var a=r("./src/utils/maths.js");class l extends o.Callable{_call(B,j){throw Error("`_call` should be implemented in a subclass")}}class p extends o.Callable{_call(B,j){throw Error("`_call` should be implemented in a subclass")}}class _ extends o.Callable{constructor(){super(),this.processors=[]}push(B){this.processors.push(B)}extend(B){this.processors.push(...B)}_call(B,j){let N=j;for(const ae of this.processors)N=ae(B,N);return N}[Symbol.iterator](){return this.processors.values()}}class h extends l{constructor(B){super(),this.bos_token_id=B}_call(B,j){for(let N=0;N<B.length;++N)if(B[N].length===1){const ae=j[N];ae.data.fill(-1/0),ae.data[this.bos_token_id]=0}return j}}class g extends l{constructor(B,j){super(),this.max_length=B,this.eos_token_id=Array.isArray(j)?j:[j]}_call(B,j){for(let N=0;N<B.length;++N)if(B[N].length===this.max_length-1){const ae=j[N];ae.data.fill(-1/0);for(const ce of this.eos_token_id)ae.data[ce]=0}return j}}class M extends l{constructor(B,j){super(),this.begin_suppress_tokens=B,this.begin_index=j}_call(B,j){for(let N=0;N<B.length;++N)if(B[N].length===this.begin_index){const ae=j[N];for(const ce of this.begin_suppress_tokens)ae.data[ce]=-1/0}return j}}class y extends l{constructor(B,j){super(),this.eos_token_id=Array.isArray(B.eos_token_id)?B.eos_token_id[0]:B.eos_token_id,this.no_timestamps_token_id=B.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=B.max_initial_timestamp_index}_call(B,j){for(let N=0;N<B.length;++N){const ce=j[N].data;if(ce[this.no_timestamps_token_id]=-1/0,B[N].length===this.begin_index-1){ce.fill(-1/0),ce[this.timestamp_begin]=0;continue}const xe=B[N].slice(this.begin_index),Y=xe.length>=1&&xe[xe.length-1]>=this.timestamp_begin,_e=xe.length<2||xe[xe.length-2]>=this.timestamp_begin;if(Y&&(_e?ce.subarray(this.timestamp_begin).fill(-1/0):ce.subarray(0,this.eos_token_id).fill(-1/0)),B[N].length===this.begin_index&&this.max_initial_timestamp_index!==null){const me=this.timestamp_begin+this.max_initial_timestamp_index;ce.subarray(me+1).fill(-1/0)}const L=(0,a.log_softmax)(ce),Se=Math.log(L.subarray(this.timestamp_begin).map(Math.exp).reduce((me,X)=>me+X)),Xe=(0,a.max)(L.subarray(0,this.timestamp_begin))[0];Se>Xe&&ce.subarray(0,this.timestamp_begin).fill(-1/0)}return j}}class E extends l{constructor(B){super(),this.no_repeat_ngram_size=B}getNgrams(B){const j=B.length,N=[];for(let ce=0;ce<j+1-this.no_repeat_ngram_size;++ce){const xe=[];for(let Y=0;Y<this.no_repeat_ngram_size;++Y)xe.push(B[ce+Y]);N.push(xe.map(Number))}const ae=new Map;for(const ce of N){const xe=ce.slice(0,ce.length-1),Y=JSON.stringify(xe),_e=ae.get(Y)??[];_e.push(ce[ce.length-1]),ae.set(Y,_e)}return ae}getGeneratedNgrams(B,j){const N=j.slice(j.length+1-this.no_repeat_ngram_size,j.length);return B.get(JSON.stringify(N.map(Number)))??[]}calcBannedNgramTokens(B){const j=[];if(B.length+1<this.no_repeat_ngram_size)return j;{const N=this.getNgrams(B);return this.getGeneratedNgrams(N,B)}}_call(B,j){for(let N=0;N<B.length;++N){const ae=j[N],ce=this.calcBannedNgramTokens(B[N]);for(const xe of ce)ae.data[xe]=-1/0}return j}}class T extends l{constructor(B){super(),this.penalty=B}_call(B,j){for(let N=0;N<B.length;++N){const ae=j[N];for(const ce of B[N])ae.data[ce]<0?ae.data[ce]*=this.penalty:ae.data[ce]/=this.penalty}return j}}class O extends l{constructor(B,j){super(),this.min_length=B,this.eos_token_id=Array.isArray(j)?j:[j]}_call(B,j){for(let N=0;N<B.length;++N)if(B[N].length<this.min_length){const ae=j[N];for(const ce of this.eos_token_id)ae.data[ce]=-1/0}return j}}class S extends l{constructor(B,j,N){super(),this.prompt_length_to_skip=B,this.min_new_tokens=j,this.eos_token_id=Array.isArray(N)?N:[N]}_call(B,j){for(let N=0;N<B.length;++N)if(B[N].length-this.prompt_length_to_skip<this.min_new_tokens){const ce=j[N];for(const xe of this.eos_token_id)ce[xe]=-1/0}return j}}class C extends l{constructor(B,j){super(),this.bad_words_ids=B,this.eos_token_id=Array.isArray(j)?j:[j]}_call(B,j){for(let N=0;N<B.length;++N){const ae=j[N];for(const ce of this.bad_words_ids){let xe=!0;for(let Y=1;Y<=ce.length-1&&ce.length<B[Y].length;++Y)if(ce.at(-Y-1)!==Number(B[Y].at(-Y))){xe=!1;break}xe&&(ae[ce.at(-1)]=-1/0)}}return j}}class w extends l{constructor(B){if(super(),B<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${B}.`);this.guidance_scale=B}_call(B,j){if(j.dims[0]!==2*B.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 ${B.length} for the input ids.`);const N=B.length,ae=j.slice([0,N],null),ce=j.slice([N,j.dims[0]],null);for(let xe=0;xe<ce.data.length;++xe)ce.data[xe]+=(ae.data[xe]-ce.data[xe])*this.guidance_scale;return ce}}class b extends p{constructor(B){super(),this.temperature=B}_call(B,j){const N=j.data;for(let ae=0;ae<N.length;++ae)N[ae]/=this.temperature;return j}}class I extends p{constructor(B,{filter_value:j=-1/0,min_tokens_to_keep:N=1}={}){if(super(),B<0||B>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${B}`);if(!Number.isInteger(N)||N<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${N}`);this.top_p=B,this.filter_value=j,this.min_tokens_to_keep=N}}class U extends p{constructor(B,{filter_value:j=-1/0,min_tokens_to_keep:N=1}={}){if(super(),!Number.isInteger(B)||B<0)throw new Error(`\`top_k\` must be a positive integer, but is ${B}`);this.top_k=Math.max(B,N),this.filter_value=j}}},"./src/generation/logits_sampler.js":(e,t,r)=>{r.r(t),r.d(t,{LogitsSampler:()=>p});var o=r("./src/utils/generic.js"),a=r("./src/utils/tensor.js"),l=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class p extends o.Callable{constructor(y){super(),this.generation_config=y}async _call(y){return this.sample(y)}async sample(y){throw Error("sample should be implemented in subclasses.")}getLogits(y,E){let T=y.dims.at(-1),O=y.data;if(E===-1)O=O.slice(-T);else{let S=E*T;O=O.slice(S,S+T)}return O}randomSelect(y){let E=0;for(let O=0;O<y.length;++O)E+=y[O];let T=Math.random()*E;for(let O=0;O<y.length;++O)if(T-=y[O],T<=0)return O;return 0}static getSampler(y){if(y.do_sample)return new h(y);if(y.num_beams>1)return new g(y);if(y.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${y.num_return_sequences}.`);return new _(y)}}class _ extends p{async sample(y){const E=(0,l.max)(y.data)[1];return[[BigInt(E),0]]}}class h extends p{async sample(y){let E=y.dims.at(-1);this.generation_config.top_k>0&&(E=Math.min(this.generation_config.top_k,E));const[T,O]=await(0,a.topk)(y,E),S=(0,l.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},()=>{const C=this.randomSelect(S);return[O.data[C],Math.log(S[C])]})}}class g extends p{async sample(y){let E=y.dims.at(-1);this.generation_config.top_k>0&&(E=Math.min(this.generation_config.top_k,E));const[T,O]=await(0,a.topk)(y,E),S=(0,l.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},(C,w)=>[O.data[w],Math.log(S[w])])}}},"./src/generation/stopping_criteria.js":(e,t,r)=>{r.r(t),r.d(t,{EosTokenCriteria:()=>_,InterruptableStoppingCriteria:()=>h,MaxLengthCriteria:()=>p,StoppingCriteria:()=>a,StoppingCriteriaList:()=>l});var o=r("./src/utils/generic.js");class a extends o.Callable{_call(M,y){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,y){const E=new Array(M.length).fill(!1);for(const T of this.criteria){const O=T(M,y);for(let S=0;S<E.length;++S)E[S]||(E[S]=O[S])}return E}[Symbol.iterator](){return this.criteria.values()}}class p extends a{constructor(M,y=null){super(),this.max_length=M,this.max_position_embeddings=y}_call(M){return M.map(y=>y.length>=this.max_length)}}class _ extends a{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,y){return M.map(E=>{const T=E.at(-1);return this.eos_token_id.some(O=>T==O)})}}class h extends a{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,y){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,r)=>{r.r(t),r.d(t,{BaseStreamer:()=>p,TextStreamer:()=>h,WhisperTextStreamer:()=>g});var o=r("./src/utils/core.js"),a=r("./src/tokenizers.js"),l=r("./src/env.js");class p{put(y){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 p{constructor(y,{skip_prompt:E=!1,callback_function:T=null,token_callback_function:O=null,decode_kwargs:S={},...C}={}){super(),this.tokenizer=y,this.skip_prompt=E,this.callback_function=T??_,this.token_callback_function=O,this.decode_kwargs={...S,...C},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(y){var S;if(y.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 E=y[0];(S=this.token_callback_function)==null||S.call(this,E),this.token_cache=(0,o.mergeArrays)(this.token_cache,E);const T=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let O;T.endsWith(` `)?(O=T.slice(this.print_len),this.token_cache=[],this.print_len=0):T.length>0&&(0,a.is_chinese_char)(T.charCodeAt(T.length-1))?(O=T.slice(this.print_len),this.print_len+=O.length):(O=T.slice(this.print_len,T.lastIndexOf(" ")+1),this.print_len+=O.length),this.on_finalized_text(O,!1)}end(){let y;this.token_cache.length>0?(y=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):y="",this.next_tokens_are_prompt=!0,this.on_finalized_text(y,!0)}on_finalized_text(y,E){var T,O;y.length>0&&((T=this.callback_function)==null||T.call(this,y)),E&&this.callback_function===_&&l.apis.IS_PROCESS_AVAILABLE&&((O=this.callback_function)==null||O.call(this,` `))}}class g extends h{constructor(y,{skip_prompt:E=!1,callback_function:T=null,token_callback_function:O=null,on_chunk_start:S=null,on_chunk_end:C=null,on_finalize:w=null,time_precision:b=.02,skip_special_tokens:I=!0,decode_kwargs:U={}}={}){super(y,{skip_prompt:E,callback_function:T,token_callback_function:O,decode_kwargs:{skip_special_tokens:I,...U}}),this.timestamp_begin=y.timestamp_begin,this.on_chunk_start=S,this.on_chunk_end=C,this.on_finalize=w,this.time_precision=b,this.waiting_for_timestamp=!1}put(y){var T,O;if(y.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const E=y[0];if(E.length===1){const S=Number(E[0])-this.timestamp_begin;if(S>=0){const C=S*this.time_precision;this.waiting_for_timestamp?(T=this.on_chunk_end)==null||T.call(this,C):(O=this.on_chunk_start)==null||O.call(this,C),this.waiting_for_timestamp=!this.waiting_for_timestamp,y=[[]]}}return super.put(y)}end(){var y;super.end(),(y=this.on_finalize)==null||y.call(this)}}},"./src/models.js":(e,t,r)=>{r.r(t),r.d(t,{ASTForAudioClassification:()=>$s,ASTModel:()=>zt,ASTPreTrainedModel:()=>Vn,AlbertForMaskedLM:()=>Zt,AlbertForQuestionAnswering:()=>mo,AlbertForSequenceClassification:()=>ho,AlbertModel:()=>Ji,AlbertPreTrainedModel:()=>Si,AutoModel:()=>Bd,AutoModelForAudioClassification:()=>Yd,AutoModelForAudioFrameClassification:()=>Zd,AutoModelForCTC:()=>Qd,AutoModelForCausalLM:()=>Vd,AutoModelForDepthEstimation:()=>tp,AutoModelForDocumentQuestionAnswering:()=>Tf,AutoModelForImageClassification:()=>Hd,AutoModelForImageFeatureExtraction:()=>rp,AutoModelForImageMatting:()=>Jd,AutoModelForImageSegmentation:()=>Tl,AutoModelForImageToImage:()=>ep,AutoModelForMaskGeneration:()=>kl,AutoModelForMaskedLM:()=>Wd,AutoModelForObjectDetection:()=>Kd,AutoModelForQuestionAnswering:()=>Ml,AutoModelForSemanticSegmentation:()=>qd,AutoModelForSeq2SeqLM:()=>jd,AutoModelForSequenceClassification:()=>Pn,AutoModelForSpeechSeq2Seq:()=>xl,AutoModelForTextToSpectrogram:()=>Ud,AutoModelForTextToWaveform:()=>Zo,AutoModelForTokenClassification:()=>Nd,AutoModelForVision2Seq:()=>Gd,AutoModelForXVector:()=>Sl,AutoModelForZeroShotObjectDetection:()=>Xd,BartForConditionalGeneration:()=>W,BartForSequenceClassification:()=>pe,BartModel:()=>Ue,BartPretrainedModel:()=>jn,BaseModelOutput:()=>Ke,BeitForImageClassification:()=>cc,BeitModel:()=>uc,BeitPreTrainedModel:()=>Oa,BertForMaskedLM:()=>We,BertForQuestionAnswering:()=>Ge,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>pt,BertModel:()=>Be,BertPreTrainedModel:()=>Le,BlenderbotForConditionalGeneration:()=>It,BlenderbotModel:()=>kt,BlenderbotPreTrainedModel:()=>St,BlenderbotSmallForConditionalGeneration:()=>or,BlenderbotSmallModel:()=>Ar,BlenderbotSmallPreTrainedModel:()=>tr,BloomForCausalLM:()=>Gu,BloomModel:()=>Wu,BloomPreTrainedModel:()=>Fs,CLIPModel:()=>pu,CLIPPreTrainedModel:()=>Ho,CLIPSegForImageSegmentation:()=>yu,CLIPSegModel:()=>wu,CLIPSegPreTrainedModel:()=>ya,CLIPTextModelWithProjection:()=>hi,CLIPVisionModelWithProjection:()=>fu,CamembertForMaskedLM:()=>Re,CamembertForQuestionAnswering:()=>tt,CamembertForSequenceClassification:()=>qe,CamembertForTokenClassification:()=>Qe,CamembertModel:()=>ve,CamembertPreTrainedModel:()=>Z,CausalLMOutput:()=>to,CausalLMOutputWithPast:()=>kf,ChineseCLIPModel:()=>_u,ChineseCLIPPreTrainedModel:()=>gu,ClapAudioModelWithProjection:()=>pd,ClapModel:()=>cd,ClapPreTrainedModel:()=>Ko,ClapTextModelWithProjection:()=>dd,CodeGenForCausalLM:()=>As,CodeGenModel:()=>Pu,CodeGenPreTrainedModel:()=>Qn,CohereForCausalLM:()=>Iu,CohereModel:()=>Au,CoherePreTrainedModel:()=>Ta,ConvBertForMaskedLM:()=>R,ConvBertForQuestionAnswering:()=>ue,ConvBertForSequenceClassification:()=>ee,ConvBertForTokenClassification:()=>D,ConvBertModel:()=>ye,ConvBertPreTrainedModel:()=>re,ConvNextForImageClassification:()=>Fc,ConvNextModel:()=>Ic,ConvNextPreTrainedModel:()=>qa,ConvNextV2ForImageClassification:()=>Dc,ConvNextV2Model:()=>zc,ConvNextV2PreTrainedModel:()=>Oc,DPTForDepthEstimation:()=>Wa,DPTModel:()=>Va,DPTPreTrainedModel:()=>Ua,DebertaForMaskedLM:()=>Tt,DebertaForQuestionAnswering:()=>Lt,DebertaForSequenceClassification:()=>bt,DebertaForTokenClassification:()=>Et,DebertaModel:()=>ht,DebertaPreTrainedModel:()=>ft,DebertaV2ForMaskedLM:()=>Ut,DebertaV2ForQuestionAnswering:()=>rr,DebertaV2ForSequenceClassification:()=>Xt,DebertaV2ForTokenClassification:()=>Yt,DebertaV2Model:()=>Ot,DebertaV2PreTrainedModel:()=>at,DeiTForImageClassification:()=>bc,DeiTModel:()=>vc,DeiTPreTrainedModel:()=>La,DepthAnythingForDepthEstimation:()=>Cc,DepthAnythingPreTrainedModel:()=>Ec,DetrForObjectDetection:()=>pc,DetrForSegmentation:()=>fc,DetrModel:()=>dc,DetrObjectDetectionOutput:()=>za,DetrPreTrainedModel:()=>Ds,DetrSegmentationOutput:()=>hc,Dinov2ForImageClassification:()=>Rc,Dinov2Model:()=>Lc,Dinov2PreTrainedModel:()=>Zn,DistilBertForMaskedLM:()=>$t,DistilBertForQuestionAnswering:()=>mt,DistilBertForSequenceClassification:()=>Yr,DistilBertForTokenClassification:()=>$r,DistilBertModel:()=>Pr,DistilBertPreTrainedModel:()=>Ht,DonutSwinModel:()=>Ha,DonutSwinPreTrainedModel:()=>Ac,EfficientNetForImageClassification:()=>_d,EfficientNetModel:()=>gd,EfficientNetPreTrainedModel:()=>fl,ElectraForMaskedLM:()=>Ne,ElectraForQuestionAnswering:()=>Ve,ElectraForSequenceClassification:()=>dt,ElectraForTokenClassification:()=>Je,ElectraModel:()=>ke,ElectraPreTrainedModel:()=>le,EsmForMaskedLM:()=>Bi,EsmForSequenceClassification:()=>Mi,EsmForTokenClassification:()=>Gr,EsmModel:()=>un,EsmPreTrainedModel:()=>Bt,FalconForCausalLM:()=>ud,FalconModel:()=>ld,FalconPreTrainedModel:()=>ul,FastViTForImageClassification:()=>Zu,FastViTModel:()=>Yu,FastViTPreTrainedModel:()=>zs,Florence2ForConditionalGeneration:()=>_a,Florence2PreTrainedModel:()=>du,GLPNForDepthEstimation:()=>$c,GLPNModel:()=>Pc,GLPNPreTrainedModel:()=>Ga,GPT2LMHeadModel:()=>bu,GPT2Model:()=>vu,GPT2PreTrainedModel:()=>va,GPTBigCodeForCausalLM:()=>rf,GPTBigCodeModel:()=>Cu,GPTBigCodePreTrainedModel:()=>Ma,GPTJForCausalLM:()=>Eu,GPTJModel:()=>Su,GPTJPreTrainedModel:()=>xa,GPTNeoForCausalLM:()=>Mu,GPTNeoModel:()=>xu,GPTNeoPreTrainedModel:()=>Xn,GPTNeoXForCausalLM:()=>ku,GPTNeoXModel:()=>Tu,GPTNeoXPreTrainedModel:()=>ba,Gemma2ForCausalLM:()=>Du,Gemma2Model:()=>zu,Gemma2PreTrainedModel:()=>Sa,GemmaForCausalLM:()=>Ou,GemmaModel:()=>Fu,GemmaPreTrainedModel:()=>ka,HubertForCTC:()=>Jc,HubertForSequenceClassification:()=>rl,HubertModel:()=>uf,HubertPreTrainedModel:()=>lf,ImageMattingOutput:()=>ip,LlamaForCausalLM:()=>$u,LlamaModel:()=>ii,LlamaPreTrainedModel:()=>Is,LlavaForConditionalGeneration:()=>wo,LlavaPreTrainedModel:()=>cu,LongT5ForConditionalGeneration:()=>Wo,LongT5Model:()=>Vo,LongT5PreTrainedModel:()=>go,M2M100ForConditionalGeneration:()=>qc,M2M100Model:()=>Hc,M2M100PreTrainedModel:()=>Qa,MBartForCausalLM:()=>Mt,MBartForConditionalGeneration:()=>Oe,MBartForSequenceClassification:()=>rt,MBartModel:()=>Fe,MBartPreTrainedModel:()=>Ce,MPNetForMaskedLM:()=>Lo,MPNetForQuestionAnswering:()=>No,MPNetForSequenceClassification:()=>Ro,MPNetForTokenClassification:()=>Bo,MPNetModel:()=>Cs,MPNetPreTrainedModel:()=>Ti,MT5ForConditionalGeneration:()=>Vr,MT5Model:()=>Go,MT5PreTrainedModel:()=>_o,MarianMTModel:()=>Gc,MarianModel:()=>sf,MarianPreTrainedModel:()=>Xa,MaskedLMOutput:()=>bn,MistralForCausalLM:()=>Vs,MistralModel:()=>Us,MistralPreTrainedModel:()=>sl,MobileBertForMaskedLM:()=>pi,MobileBertForQuestionAnswering:()=>Ni,MobileBertForSequenceClassification:()=>Dr,MobileBertModel:()=>Kr,MobileBertPreTrainedModel:()=>wn,MobileNetV1ForImageClassification:()=>ff,MobileNetV1Model:()=>wd,MobileNetV1PreTrainedModel:()=>gl,MobileNetV2ForImageClassification:()=>vd,MobileNetV2Model:()=>yd,MobileNetV2PreTrainedModel:()=>_l,MobileNetV3ForImageClassification:()=>hf,MobileNetV3Model:()=>bd,MobileNetV3PreTrainedModel:()=>wl,MobileNetV4ForImageClassification:()=>yl,MobileNetV4Model:()=>Yo,MobileNetV4PreTrainedModel:()=>Qo,MobileViTForImageClassification:()=>nc,MobileViTModel:()=>rc,MobileViTPreTrainedModel:()=>tc,MobileViTV2ForImageClassification:()=>ic,MobileViTV2Model:()=>of,MobileViTV2PreTrainedModel:()=>Ia,ModelOutput:()=>ge,Moondream1ForConditionalGeneration:()=>ar,MptForCausalLM:()=>Hu,MptModel:()=>nf,MptPreTrainedModel:()=>Os,MusicgenForCausalLM:()=>gm,MusicgenForConditionalGeneration:()=>ml,MusicgenModel:()=>pf,MusicgenPreTrainedModel:()=>hl,NomicBertModel:()=>je,NomicBertPreTrainedModel:()=>Te,OPTForCausalLM:()=>Ku,OPTModel:()=>qu,OPTPreTrainedModel:()=>Aa,OpenELMForCausalLM:()=>Ru,OpenELMModel:()=>Lu,OpenELMPreTrainedModel:()=>Yn,OwlViTForObjectDetection:()=>sc,OwlViTModel:()=>oc,OwlViTPreTrainedModel:()=>br,Owlv2ForObjectDetection:()=>lc,Owlv2Model:()=>ac,Owlv2PreTrainedModel:()=>Fa,Phi3ForCausalLM:()=>$a,Phi3Model:()=>Vu,Phi3PreTrainedModel:()=>Pa,PhiForCausalLM:()=>Uu,PhiModel:()=>ju,PhiPreTrainedModel:()=>Ca,PreTrainedModel:()=>Q,PretrainedMixin:()=>Rr,PyAnnoteForAudioFrameClassification:()=>Gi,PyAnnoteModel:()=>Ya,PyAnnotePreTrainedModel:()=>Ei,QuestionAnsweringModelOutput:()=>xn,Qwen2ForCausalLM:()=>Nu,Qwen2Model:()=>Bu,Qwen2PreTrainedModel:()=>Ea,RTDetrForObjectDetection:()=>Ls,RTDetrModel:()=>mc,RTDetrObjectDetectionOutput:()=>gc,RTDetrPreTrainedModel:()=>bo,ResNetForImageClassification:()=>Mc,ResNetModel:()=>xc,ResNetPreTrainedModel:()=>Ra,RoFormerForMaskedLM:()=>A,RoFormerForQuestionAnswering:()=>se,RoFormerForSequenceClassification:()=>$e,RoFormerForTokenClassification:()=>Pe,RoFormerModel:()=>et,RoFormerPreTrainedModel:()=>Ye,RobertaForMaskedLM:()=>Cn,RobertaForQuestionAnswering:()=>Kn,RobertaForSequenceClassification:()=>gn,RobertaForTokenClassification:()=>ct,RobertaModel:()=>_r,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Wc,SamModel:()=>Vc,SamPreTrainedModel:()=>Uc,SegformerForImageClassification:()=>fd,SegformerForSemanticSegmentation:()=>hd,SegformerModel:()=>mm,SegformerPreTrainedModel:()=>Xo,Seq2SeqLMOutput:()=>wm,SequenceClassifierOutput:()=>ur,SiglipModel:()=>yo,SiglipPreTrainedModel:()=>wa,SiglipTextModel:()=>hu,SiglipVisionModel:()=>mu,SpeechT5ForSpeechToText:()=>od,SpeechT5ForTextToSpeech:()=>cf,SpeechT5HifiGan:()=>ol,SpeechT5Model:()=>id,SpeechT5PreTrainedModel:()=>il,SqueezeBertForMaskedLM:()=>fo,SqueezeBertForQuestionAnswering:()=>ki,SqueezeBertForSequenceClassification:()=>fi,SqueezeBertModel:()=>Ps,SqueezeBertPreTrainedModel:()=>ji,StableLmForCausalLM:()=>md,StableLmModel:()=>pl,StableLmPreTrainedModel:()=>dl,Starcoder2ForCausalLM:()=>ll,Starcoder2Model:()=>Ws,Starcoder2PreTrainedModel:()=>al,Swin2SRForImageSuperResolution:()=>ja,Swin2SRModel:()=>Sc,Swin2SRPreTrainedModel:()=>Na,SwinForImageClassification:()=>kc,SwinModel:()=>Tc,SwinPreTrainedModel:()=>Ba,T5ForConditionalGeneration:()=>Uo,T5Model:()=>jo,T5PreTrainedModel:()=>eo,TableTransformerForObjectDetection:()=>wc,TableTransformerModel:()=>_c,TableTransformerObjectDetectionOutput:()=>yc,TableTransformerPreTrainedModel:()=>Da,TokenClassifierOutput:()=>hn,TrOCRForCausalLM:()=>ad,TrOCRPreTrainedModel:()=>sd,UniSpeechForCTC:()=>Xc,UniSpeechForSequenceClassification:()=>Qc,UniSpeechModel:()=>Ja,UniSpeechPreTrainedModel:()=>xo,UniSpeechSatForAudioFrameClassification:()=>Bs,UniSpeechSatForCTC:()=>el,UniSpeechSatForSequenceClassification:()=>Yc,UniSpeechSatModel:()=>Rs,UniSpeechSatPreTrainedModel:()=>qo,ViTForImageClassification:()=>Qu,ViTModel:()=>Xu,ViTPreTrainedModel:()=>vo,VisionEncoderDecoderModel:()=>ga,VitMatteForImageMatting:()=>ec,VitMattePreTrainedModel:()=>Ju,VitsModel:()=>cl,VitsModelOutput:()=>Sf,VitsPreTrainedModel:()=>df,Wav2Vec2BertForCTC:()=>js,Wav2Vec2BertForSequenceClassification:()=>Zc,Wav2Vec2BertModel:()=>tl,Wav2Vec2BertPreTrainedModel:()=>Ns,Wav2Vec2ForAudioFrameClassification:()=>Wi,Wav2Vec2ForCTC:()=>af,Wav2Vec2ForSequenceClassification:()=>Vi,Wav2Vec2Model:()=>Kc,Wav2Vec2PreTrainedModel:()=>Ui,WavLMForAudioFrameClassification:()=>nd,WavLMForCTC:()=>nl,WavLMForSequenceClassification:()=>td,WavLMForXVector:()=>rd,WavLMModel:()=>ed,WavLMPreTrainedModel:()=>Ci,WeSpeakerResNetModel:()=>Za,WeSpeakerResNetPreTrainedModel:()=>vn,WhisperForConditionalGeneration:()=>ma,WhisperModel:()=>Gt,WhisperPreTrainedModel:()=>_t,XLMForQuestionAnswering:()=>yn,XLMForSequenceClassification:()=>Jt,XLMForTokenClassification:()=>Un,XLMModel:()=>cn,XLMPreTrainedModel:()=>Tr,XLMRobertaForMaskedLM:()=>At,XLMRobertaForQuestionAnswering:()=>Xr,XLMRobertaForSequenceClassification:()=>vr,XLMRobertaForTokenClassification:()=>Lr,XLMRobertaModel:()=>Er,XLMRobertaPreTrainedModel:()=>Sr,XLMWithLMHeadModel:()=>On,XVectorOutput:()=>np,YolosForObjectDetection:()=>Nc,YolosModel:()=>Bc,YolosObjectDetectionOutput:()=>jc,YolosPreTrainedModel:()=>Ka});var o=r("./src/configs.js"),a=r("./src/backends/onnx.js"),l=r("./src/utils/dtypes.js"),p=r("./src/utils/generic.js"),_=r("./src/utils/core.js"),h=r("./src/utils/hub.js"),g=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),y=r("./src/utils/tensor.js"),E=r("./src/utils/maths.js"),T=r("./src/generation/stopping_criteria.js"),O=r("./src/generation/logits_sampler.js"),S=r("./src/env.js"),C=r("./src/models/whisper/generation_whisper.js"),w=r("./src/models/whisper/common_whisper.js");const b={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},I=new Map,U=new Map,z=new Map;async function B(V,G,ne){let Ee=ne.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 wt=ne.dtype;typeof wt!="string"&&(wt&&wt.hasOwnProperty(G)?wt=wt[G]:(wt=l.DEFAULT_DEVICE_DTYPE_MAPPING[Ze]??l.DATA_TYPES.fp32,console.warn(`dtype not specified for "${G}". Using the default dtype (${wt}) for this device (${Ze}).`)));const Ct=wt;if(l.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ct)){if(Ct===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: ${Ct}. Should be one of: ${Object.keys(l.DATA_TYPES).join(", ")}`);const Wt=l.DEFAULT_DTYPE_SUFFIX_MAPPING[Ct],cr=`${ne.subfolder??""}/${G}${Wt}.onnx`,lr={...ne.session_options};lr.executionProviders??(lr.executionProviders=it);const Ir=(0,h.getModelFile)(V,cr,!0,ne);let dr=[];if(ne.use_external_data_format&&(ne.use_external_data_format===!0||typeof ne.use_external_data_format=="object"&&ne.use_external_data_format.hasOwnProperty(G)&&ne.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 pr=`${G}${Wt}.onnx_data`,mr=`${ne.subfolder??""}/${pr}`;dr.push(new Promise(async(xr,Nr)=>{const $n=await(0,h.getModelFile)(V,mr,!0,ne);xr({path:pr,data:$n})}))}else lr.externalData!==void 0&&(dr=lr.externalData.map(async pr=>{if(typeof pr.data=="string"){const mr=await(0,h.getModelFile)(V,pr.data,!0,ne);return{...pr,data:mr}}return pr}));if(dr.length>0&&(lr.externalData=await Promise.all(dr)),Ze==="webgpu"){const pr=(0,o.getKeyValueShapes)(ne.config,{prefix:"present"});if(Object.keys(pr).length>0&&!(0,a.isONNXProxy)()){const mr={};for(const xr in pr)mr[xr]="gpu-buffer";lr.preferredOutputLocation=mr}}return{buffer:await Ir,session_options:lr}}async function j(V,G,ne){return Object.fromEntries(await Promise.all(Object.keys(G).map(async Ee=>{const{buffer:Ze,session_options:it}=await B(V,G[Ee],ne),wt=await(0,a.createInferenceSession)(Ze,it);return[Ee,wt]})))}function N(V,G){const ne=Object.create(null),Ee=[];for(const wt of V.inputNames){const Ct=G[wt];if(!(Ct instanceof y.Tensor)){Ee.push(wt);continue}ne[wt]=(0,a.isONNXProxy)()?Ct.clone():Ct}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 wt=Object.keys(G).filter(Ct=>!V.inputNames.includes(Ct));console.warn(`WARNING: Too many inputs were provided (${Ze} > ${it}). The following inputs will be ignored: "${wt.join(", ")}".`)}return ne}async function ae(V,G){const ne=N(V,G);try{const Ee=Object.fromEntries(Object.entries(ne).map(([it,wt])=>[it,wt.ort_tensor]));let Ze=await V.run(Ee);return Ze=ce(Ze),Ze}catch(Ee){throw console.error(`An error occurred during model execution: "${Ee}".`),console.error("Inputs given to model:",ne),Ee}}function ce(V){for(let G in V)(0,a.isONNXTensor)(V[G])?V[G]=new y.Tensor(V[G]):typeof V[G]=="object"&&ce(V[G]);return V}function xe(V){if(V instanceof y.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 y.Tensor("int64",BigInt64Array.from(V.flat().map(G=>BigInt(G))),[V.length,V[0].length])}else return new y.Tensor("int64",BigInt64Array.from(V.map(G=>BigInt(G))),[1,V.length])}function Y(V){return new y.Tensor("bool",[V],[1])}async function _e(V,G){let{encoder_outputs:ne,input_ids:Ee,decoder_input_ids:Ze,...it}=G;if(!ne){const Ct=(0,_.pick)(G,V.sessions.model.inputNames);ne=(await L(V,Ct)).last_hidden_state}return it.input_ids=Ze,it.encoder_hidden_states=ne,V.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(it.encoder_attention_mask=G.attention_mask),await Se(V,it,!0)}async function L(V,G){const ne=V.sessions.model,Ee=(0,_.pick)(G,ne.inputNames);if(ne.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 ne.inputNames.includes("token_type_ids")&&!Ee.token_type_ids&&(Ee.token_type_ids=new y.Tensor("int64",new BigInt64Array(Ee.input_ids.data.length),Ee.input_ids.dims)),await ae(ne,Ee)}async function Se(V,G,ne=!1){const Ee=V.sessions[ne?"decoder_model_merged":"model"],{past_key_values:Ze,...it}=G;Ee.inputNames.includes("use_cache_branch")&&(it.use_cache_branch=Y(!!Ze)),Ee.inputNames.includes("position_ids")&&it.attention_mask&&!it.position_ids&&(it.position_ids=me(it,Ze)),V.addPastKeyValues(it,Ze);const wt=(0,_.pick)(it,Ee.inputNames);return await ae(Ee,wt)}async function Xe(V,{input_ids:G=null,attention_mask:ne=null,pixel_values:Ee=null,position_ids:Ze=null,inputs_embeds:it=null,past_key_values:wt=null,generation_config:Ct=null,logits_processor:Wt=null,...cr}){if(!it){if(it=await V.encode_text({input_ids:G}),Ee&&G.dims[1]!==1){const Ir=await V.encode_image({pixel_values:Ee});({inputs_embeds:it,attention_mask:ne}=V._merge_input_ids_with_image_features({image_features:Ir,inputs_embeds:it,input_ids:G,attention_mask:ne}))}else if(wt&&Ee&&G.dims[1]===1){const Ir=G.dims[1],dr=Object.values(wt)[0].dims.at(-2);ne=(0,y.cat)([(0,y.ones)([G.dims[0],dr]),ne.slice(null,[ne.dims[1]-Ir,ne.dims[1]])],1)}}return await Se(V,{inputs_embeds:it,past_key_values:wt,attention_mask:ne,position_ids:Ze,generation_config:Ct,logits_processor:Wt},!0)}function me(V,G=null){const{input_ids:ne,inputs_embeds:Ee,attention_mask:Ze}=V,[it,wt]=Ze.dims,Ct=new BigInt64Array(Ze.data.length);for(let cr=0;cr<it;++cr){const lr=cr*wt;let Ir=BigInt(0);for(let dr=0;dr<wt;++dr){const wr=lr+dr;Ze.data[wr]===0n?Ct[wr]=BigInt(1):(Ct[wr]=Ir,Ir+=Ze.data[wr])}}let Wt=new y.Tensor("int64",Ct,Ze.dims);if(G){const cr=-(ne??Ee).dims.at(1);Wt=Wt.slice(null,[cr,null])}return Wt}function X(V,G,ne,Ee){if(ne.past_key_values){const Ze=Object.values(ne.past_key_values)[0].dims.at(-2),{input_ids:it,attention_mask:wt}=ne;if(!(wt&&wt.dims[1]>it.dims[1])){if(Ze<it.dims[1])ne.input_ids=it.slice(null,[Ze,null]);else if(V.config.image_token_index!=null&&it.data.some(Ct=>Ct==V.config.image_token_index)){const Ct=V.config.num_image_tokens;if(!Ct)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=it.dims[1]-(Ze-Ct);ne.input_ids=it.slice(null,[-Wt,null]),ne.attention_mask=(0,y.ones)([1,Ze+Wt])}}}return ne}function ie(V,G,ne,Ee){return ne.past_key_values&&(G=G.map(Ze=>[Ze.at(-1)])),{...ne,decoder_input_ids:xe(G)}}function Me(V,...G){return V.config.is_encoder_decoder?ie(V,...G):X(V,...G)}class Q extends p.Callable{constructor(ne,Ee){super();He(this,"main_input_name","input_ids");He(this,"forward_params",["input_ids","attention_mask"]);this.config=ne,this.sessions=Ee;const Ze=z.get(this.constructor),it=I.get(Ze);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,it){case b.DecoderOnly:this.can_generate=!0,this._forward=Se,this._prepare_inputs_for_generation=X;break;case b.Seq2Seq:case b.Vision2Seq:case b.Musicgen:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=ie;break;case b.EncoderDecoder:this._forward=_e;break;case b.ImageTextToText:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=Me;break;default:this._forward=L;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Ee;const ne=[];for(const Ze of Object.values(this.sessions))(Ee=Ze==null?void 0:Ze.handler)!=null&&Ee.dispose&&ne.push(Ze.handler.dispose());return await Promise.all(ne)}static async from_pretrained(ne,{progress_callback:Ee=null,config:Ze=null,cache_dir:it=null,local_files_only:wt=!1,revision:Ct="main",model_file_name:Wt=null,subfolder:cr="onnx",device:lr=null,dtype:Ir=null,use_external_data_format:dr=null,session_options:wr={}}={}){let pr={progress_callback:Ee,config:Ze,cache_dir:it,local_files_only:wt,revision:Ct,model_file_name:Wt,subfolder:cr,device:lr,dtype:Ir,use_external_data_format:dr,session_options:wr};const mr=z.get(this),xr=I.get(mr);Ze=pr.config=await o.AutoConfig.from_pretrained(ne,pr);let Nr;if(xr===b.DecoderOnly)Nr=await Promise.all([j(ne,{model:pr.model_file_name??"model"},pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)]);else if(xr===b.Seq2Seq||xr===b.Vision2Seq)Nr=await Promise.all([j(ne,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)]);else if(xr===b.MaskGeneration)Nr=await Promise.all([j(ne,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},pr)]);else if(xr===b.EncoderDecoder)Nr=await Promise.all([j(ne,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},pr)]);else if(xr===b.ImageTextToText){const $n={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ze.is_encoder_decoder&&($n.model="encoder_model"),Nr=await Promise.all([j(ne,$n,pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)])}else xr===b.Musicgen?Nr=await Promise.all([j(ne,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)]):(xr!==b.EncoderOnly&&console.warn(`Model type for '${mr??(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.`),Nr=await Promise.all([j(ne,{model:pr.model_file_name??"model"},pr)]));return new this(Ze,...Nr)}async _call(ne){return await this.forward(ne)}async forward(ne){return await this._forward(this,ne)}_get_logits_warper(ne){const Ee=new g.LogitsProcessorList;return ne.temperature!==null&&ne.temperature!==1&&Ee.push(new g.TemperatureLogitsWarper(ne.temperature)),ne.top_k!==null&&ne.top_k!==0&&Ee.push(new g.TopKLogitsWarper(ne.top_k)),ne.top_p!==null&&ne.top_p<1&&Ee.push(new g.TopPLogitsWarper(ne.top_p)),Ee}_get_logits_processor(ne,Ee,Ze=null){const it=new g.LogitsProcessorList;if(ne.repetition_penalty!==null&&ne.repetition_penalty!==1&&it.push(new g.RepetitionPenaltyLogitsProcessor(ne.repetition_penalty)),ne.no_repeat_ngram_size!==null&&ne.no_repeat_ngram_size>0&&it.push(new g.NoRepeatNGramLogitsProcessor(ne.no_repeat_ngram_size)),ne.bad_words_ids!==null&&it.push(new g.NoBadWordsLogitsProcessor(ne.bad_words_ids,ne.eos_token_id)),ne.min_length!==null&&ne.eos_token_id!==null&&ne.min_length>0&&it.push(new g.MinLengthLogitsProcessor(ne.min_length,ne.eos_token_id)),ne.min_new_tokens!==null&&ne.eos_token_id!==null&&ne.min_new_tokens>0&&it.push(new g.MinNewTokensLengthLogitsProcessor(Ee,ne.min_new_tokens,ne.eos_token_id)),ne.forced_bos_token_id!==null&&it.push(new g.ForcedBOSTokenLogitsProcessor(ne.forced_bos_token_id)),ne.forced_eos_token_id!==null&&it.push(new g.ForcedEOSTokenLogitsProcessor(ne.max_length,ne.forced_eos_token_id)),ne.begin_suppress_tokens!==null){const wt=Ee>1||ne.forced_bos_token_id===null?Ee:Ee+1;it.push(new g.SuppressTokensAtBeginLogitsProcessor(ne.begin_suppress_tokens,wt))}return ne.guidance_scale!==null&&ne.guidance_scale>1&&it.push(new g.ClassifierFreeGuidanceLogitsProcessor(ne.guidance_scale)),Ze!==null&&it.extend(Ze),it}_prepare_generation_config(ne,Ee,Ze=M.GenerationConfig){const it={...this.config};for(const Ct of["decoder","generator","text_config"])Ct in it&&Object.assign(it,it[Ct]);const wt=new Ze(it);return"generation_config"in this&&Object.assign(wt,this.generation_config),ne&&Object.assign(wt,ne),Ee&&Object.assign(wt,(0,_.pick)(Ee,Object.getOwnPropertyNames(wt))),wt}_get_stopping_criteria(ne,Ee=null){const Ze=new T.StoppingCriteriaList;return ne.max_length!==null&&Ze.push(new T.MaxLengthCriteria(ne.max_length,this.config.max_position_embeddings??null)),ne.eos_token_id!==null&&Ze.push(new T.EosTokenCriteria(ne.eos_token_id)),Ee&&Ze.extend(Ee),Ze}_validate_model_class(){if(!this.can_generate){const ne=[Hs,bl,vl,Gs],Ee=z.get(this.constructor),Ze=new Set,it=this.config.model_type;for(const Ct of ne){const Wt=Ct.get(it);Wt&&Ze.add(Wt[0])}let wt=`The current model class (${Ee}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ze.size>0&&(wt+=` Please use the following class instead: ${[...Ze].join(", ")}`),Error(wt)}}prepare_inputs_for_generation(...ne){return this._prepare_inputs_for_generation(this,...ne)}_update_model_kwargs_for_generation({generated_input_ids:ne,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 y.Tensor("int64",ne.flat(),[ne.length,1]),it||(Ze.attention_mask=(0,y.cat)([Ze.attention_mask,(0,y.ones)([Ze.attention_mask.dims[0],1])],1)),Ze.position_ids=null,Ze}_prepare_model_inputs({inputs:ne,bos_token_id:Ee,model_kwargs:Ze}){const it=(0,_.pick)(Ze,this.forward_params),wt=this.main_input_name;if(wt in it){if(ne)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[wt]=ne;return{inputs_tensor:it[wt],model_inputs:it,model_input_name:wt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ne,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:Ct,pixel_values:Wt,attention_mask:cr,...lr}=Ee,Ir=await this._prepare_inputs_embeds(Ee);Ee={...lr,...(0,_.pick)(Ir,["inputs_embeds","attention_mask"])}}let{last_hidden_state:wt}=await L(this,Ee);if(it.guidance_scale!==null&&it.guidance_scale>1)wt=(0,y.cat)([wt,(0,y.full_like)(wt,0)],0),"attention_mask"in Ee&&(Ee.attention_mask=(0,y.cat)([Ee.attention_mask,(0,y.zeros_like)(Ee.attention_mask)],0));else if(Ee.decoder_input_ids){const Ct=xe(Ee.decoder_input_ids).dims[0];if(Ct!==wt.dims[0]){if(wt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${wt.dims[0]}) than the decoder inputs (${Ct}).`);wt=(0,y.cat)(Array.from({length:Ct},()=>wt),0)}}return Ee.encoder_outputs=wt,Ee}_prepare_decoder_input_ids_for_generation({batch_size:ne,model_input_name:Ee,model_kwargs:Ze,decoder_start_token_id:it,bos_token_id:wt,generation_config:Ct}){let{decoder_input_ids:Wt,...cr}=Ze;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:ne},()=>Wt));else if(it??(it=wt),this.config.model_type==="musicgen")Wt=Array.from({length:ne*this.config.decoder.num_codebooks},()=>[it]);else if(Array.isArray(it)){if(it.length!==ne)throw new Error(`\`decoder_start_token_id\` expcted to have length ${ne} but got ${it.length}`);Wt=it}else Wt=Array.from({length:ne},()=>[it]);return Wt=xe(Wt),Ze.decoder_attention_mask=(0,y.ones_like)(Wt),{input_ids:Wt,model_inputs:cr}}async generate({inputs:ne=null,generation_config:Ee=null,logits_processor:Ze=null,stopping_criteria:it=null,streamer:wt=null,...Ct}){this._validate_model_class(),Ee=this._prepare_generation_config(Ee,Ct);let{inputs_tensor:Wt,model_inputs:cr,model_input_name:lr}=this._prepare_model_inputs({inputs:ne,model_kwargs:Ct});const Ir=this.config.is_encoder_decoder;Ir&&("encoder_outputs"in cr||(cr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:cr,model_input_name:lr,generation_config:Ee})));let dr;Ir?{input_ids:dr,model_inputs:cr}=this._prepare_decoder_input_ids_for_generation({batch_size:cr[lr].dims.at(0),model_input_name:lr,model_kwargs:cr,decoder_start_token_id:Ee.decoder_start_token_id,bos_token_id:Ee.bos_token_id,generation_config:Ee}):dr=cr[lr];let wr=dr.dims.at(-1);Ee.max_new_tokens!==null&&(Ee.max_length=wr+Ee.max_new_tokens);const pr=this._get_logits_processor(Ee,wr,Ze),mr=this._get_stopping_criteria(Ee,it),xr=cr[lr].dims.at(0),Nr=O.LogitsSampler.getSampler(Ee),$n=new Array(xr).fill(0),zn=dr.tolist();wt&&wt.put(zn);let Pi=null,Mn={};for(;;){cr=this.prepare_inputs_for_generation(zn,cr,Ee);const Tn=await this.forward(cr);if(Ee.output_attentions&&Ee.return_dict_in_generate){const mi=this.getAttentions(Tn);for(const Jo in mi)Jo in Mn||(Mn[Jo]=[]),Mn[Jo].push(mi[Jo])}const qs=Tn.logits.slice(null,-1,null),Ks=pr(zn,qs),El=[];for(let mi=0;mi<Ks.dims.at(0);++mi){const Jo=Ks[mi],Ef=await Nr(Jo);for(const[Cf,Pf]of Ef){const $f=BigInt(Cf);$n[mi]+=Pf,zn[mi].push($f),El.push([$f]);break}}if(wt&&wt.put(El),mr(zn).every(mi=>mi)){Ee.return_dict_in_generate&&(Pi=this.getPastKeyValues(Tn,cr.past_key_values,!1));break}cr=this._update_model_kwargs_for_generation({generated_input_ids:El,outputs:Tn,model_inputs:cr,is_encoder_decoder:Ir})}wt&&wt.end();const dn=new y.Tensor("int64",zn.flat(),[zn.length,zn[0].length]);return Ee.return_dict_in_generate?{sequences:dn,past_key_values:Pi,...Mn}:dn}getPastKeyValues(ne,Ee,Ze=!0){const it=Object.create(null);for(const wt in ne)if(wt.startsWith("present")){const Ct=wt.replace("present","past_key_values");if(Ee&&wt.includes("encoder"))it[Ct]=Ee[Ct];else{if(Ze&&Ee){const Wt=Ee[Ct];Wt.location==="gpu-buffer"&&Wt.dispose()}it[Ct]=ne[wt]}}return it}getAttentions(ne){const Ee={};for(const Ze of["cross_attentions","encoder_attentions","decoder_attentions"])for(const it in ne)it.startsWith(Ze)&&(Ze in Ee||(Ee[Ze]=[]),Ee[Ze].push(ne[it]));return Ee}addPastKeyValues(ne,Ee){if(Ee)Object.assign(ne,Ee);else{const Ze=this.custom_config.kv_cache_dtype??"float32",it=Ze==="float16"?new Uint16Array:[],wt=(0,o.getKeyValueShapes)(this.config);for(const Ct in wt)ne[Ct]=new y.Tensor(Ze,it,wt[Ct])}}async encode_image({pixel_values:ne}){const Ee=(await ae(this.sessions.vision_encoder,{pixel_values:ne})).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:ne}){return(await ae(this.sessions.embed_tokens,{input_ids:ne})).inputs_embeds}}class ge{}class Ke extends ge{constructor({last_hidden_state:G,hidden_states:ne=null,attentions:Ee=null}){super(),this.last_hidden_state=G,this.hidden_states=ne,this.attentions=Ee}}class Le extends Q{}class Be extends Le{}class We extends Le{async _call(G){return new bn(await super._call(G))}}class st extends Le{async _call(G){return new ur(await super._call(G))}}class pt extends Le{async _call(G){return new hn(await super._call(G))}}class Ge extends Le{async _call(G){return new xn(await super._call(G))}}class Te extends Q{}class je extends Te{}class Ye extends Q{}class et extends Ye{}class A extends Ye{async _call(G){return new bn(await super._call(G))}}class $e extends Ye{async _call(G){return new ur(await super._call(G))}}class Pe extends Ye{async _call(G){return new hn(await super._call(G))}}class se extends Ye{async _call(G){return new xn(await super._call(G))}}class re extends Q{}class ye extends re{}class R extends re{async _call(G){return new bn(await super._call(G))}}class ee extends re{async _call(G){return new ur(await super._call(G))}}class D extends re{async _call(G){return new hn(await super._call(G))}}class ue extends re{async _call(G){return new xn(await super._call(G))}}class le extends Q{}class ke extends le{}class Ne extends le{async _call(G){return new bn(await super._call(G))}}class dt extends le{async _call(G){return new ur(await super._call(G))}}class Je extends le{async _call(G){return new hn(await super._call(G))}}class Ve extends le{async _call(G){return new xn(await super._call(G))}}class Z extends Q{}class ve extends Z{}class Re extends Z{async _call(G){return new bn(await super._call(G))}}class qe extends Z{async _call(G){return new ur(await super._call(G))}}class Qe extends Z{async _call(G){return new hn(await super._call(G))}}class tt extends Z{async _call(G){return new xn(await super._call(G))}}class ft extends Q{}class ht extends ft{}class Tt extends ft{async _call(G){return new bn(await super._call(G))}}class bt extends ft{async _call(G){return new ur(await super._call(G))}}class Et extends ft{async _call(G){return new hn(await super._call(G))}}class Lt extends ft{async _call(G){return new xn(await super._call(G))}}class at extends Q{}class Ot extends at{}class Ut extends at{async _call(G){return new bn(await super._call(G))}}class Xt extends at{async _call(G){return new ur(await super._call(G))}}class Yt extends at{async _call(G){return new hn(await super._call(G))}}class rr extends at{async _call(G){return new xn(await super._call(G))}}class Ht extends Q{}class Pr extends Ht{}class Yr extends Ht{async _call(G){return new ur(await super._call(G))}}class $r extends Ht{async _call(G){return new hn(await super._call(G))}}class mt extends Ht{async _call(G){return new xn(await super._call(G))}}class $t extends Ht{async _call(G){return new bn(await super._call(G))}}class Bt extends Q{}class un extends Bt{}class Bi extends Bt{async _call(G){return new bn(await super._call(G))}}class Mi extends Bt{async _call(G){return new ur(await super._call(G))}}class Gr extends Bt{async _call(G){return new hn(await super._call(G))}}class wn extends Q{}class Kr extends wn{}class pi extends wn{async _call(G){return new bn(await super._call(G))}}class Dr extends wn{async _call(G){return new ur(await super._call(G))}}class Ni extends wn{async _call(G){return new xn(await super._call(G))}}class Ti extends Q{}class Cs extends Ti{}class Lo extends Ti{async _call(G){return new bn(await super._call(G))}}class Ro extends Ti{async _call(G){return new ur(await super._call(G))}}class Bo extends Ti{async _call(G){return new hn(await super._call(G))}}class No extends Ti{async _call(G){return new xn(await super._call(G))}}class ji extends Q{}class Ps extends ji{}class fo extends ji{async _call(G){return new bn(await super._call(G))}}class fi extends ji{async _call(G){return new ur(await super._call(G))}}class ki extends ji{async _call(G){return new xn(await super._call(G))}}class Si extends Q{}class Ji extends Si{}class ho extends Si{async _call(G){return new ur(await super._call(G))}}class mo extends Si{async _call(G){return new xn(await super._call(G))}}class Zt extends Si{async _call(G){return new bn(await super._call(G))}}class eo extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class jo extends eo{}class Uo extends eo{}class go extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Vo extends go{}class Wo extends go{}class _o extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Go extends _o{}class Vr extends _o{}class jn extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Ue extends jn{}class W extends jn{}class pe extends jn{async _call(G){return new ur(await super._call(G))}}class Ce extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Fe extends Ce{}class Oe extends Ce{}class rt extends Ce{async _call(G){return new ur(await super._call(G))}}class Mt extends Ce{}class St extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class kt extends St{}class It extends St{}class tr extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Ar extends tr{}class or extends tr{}class qt extends Q{}class _r extends qt{}class Cn extends qt{async _call(G){return new bn(await super._call(G))}}class gn extends qt{async _call(G){return new ur(await super._call(G))}}class ct extends qt{async _call(G){return new hn(await super._call(G))}}class Kn extends qt{async _call(G){return new xn(await super._call(G))}}class Tr extends Q{}class cn extends Tr{}class On extends Tr{async _call(G){return new bn(await super._call(G))}}class Jt extends Tr{async _call(G){return new ur(await super._call(G))}}class Un extends Tr{async _call(G){return new hn(await super._call(G))}}class yn extends Tr{async _call(G){return new xn(await super._call(G))}}class Sr extends Q{}class Er extends Sr{}class At extends Sr{async _call(G){return new bn(await super._call(G))}}class vr extends Sr{async _call(G){return new ur(await super._call(G))}}class Lr extends Sr{async _call(G){return new hn(await super._call(G))}}class Xr extends Sr{async _call(G){return new xn(await super._call(G))}}class Vn extends Q{}class zt extends Vn{}class $s extends Vn{}class _t extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(this,"requires_attention_mask",!1);He(this,"main_input_name","input_features");He(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class Gt extends _t{}class ma extends _t{_prepare_generation_config(G,ne){return super._prepare_generation_config(G,ne,C.WhisperGenerationConfig)}_retrieve_init_tokens(G){const ne=[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 wt=`<|${(0,w.whisper_language_to_code)(Ee)}|>`;ne.push(G.lang_to_id[wt]),ne.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&&ne.at(-1)!==G.no_timestamps_token_id?ne.push(G.no_timestamps_token_id):G.return_timestamps&&ne.at(-1)===G.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),ne.pop()),ne.filter(it=>it!=null)}async generate({inputs:G=null,generation_config:ne=null,logits_processor:Ee=null,stopping_criteria:Ze=null,...it}){ne=this._prepare_generation_config(ne,it);const wt=it.decoder_input_ids??this._retrieve_init_tokens(ne);if(ne.return_timestamps&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.WhisperTimeStampLogitsProcessor(ne,wt))),ne.begin_suppress_tokens&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.SuppressTokensAtBeginLogitsProcessor(ne.begin_suppress_tokens,wt.length))),ne.return_token_timestamps){if(!ne.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.");ne.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),ne.output_attentions=!0,ne.return_dict_in_generate=!0}const Ct=await super.generate({inputs:G,generation_config:ne,logits_processor:Ee,decoder_input_ids:wt,...it});return ne.return_token_timestamps&&(Ct.token_timestamps=this._extract_token_timestamps(Ct,ne.alignment_heads,ne.num_frames)),Ct}_extract_token_timestamps(G,ne,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 wt=G.cross_attentions,Ct=Array.from({length:this.config.decoder_layers},(mr,xr)=>(0,y.cat)(wt.map(Nr=>Nr[xr]),2)),Wt=(0,y.stack)(ne.map(([mr,xr])=>{if(mr>=Ct.length)throw new Error(`Layer index ${mr} is out of bounds for cross attentions (length ${Ct.length}).`);return Ee?Ct[mr].slice(null,xr,null,[0,Ee]):Ct[mr].slice(null,xr)})).transpose(1,0,2,3),[cr,lr]=(0,y.std_mean)(Wt,-2,0,!0),Ir=Wt.clone();for(let mr=0;mr<Ir.dims[0];++mr){const xr=Ir[mr];for(let Nr=0;Nr<xr.dims[0];++Nr){const $n=xr[Nr],zn=cr[mr][Nr][0].data,Pi=lr[mr][Nr][0].data;for(let Mn=0;Mn<$n.dims[0];++Mn){let dn=$n[Mn].data;for(let Tn=0;Tn<dn.length;++Tn)dn[Tn]=(dn[Tn]-Pi[Tn])/zn[Tn];dn.set((0,E.medianFilter)(dn,it))}}}const dr=[(0,y.mean)(Ir,1)],wr=G.sequences.dims,pr=new y.Tensor("float32",new Float32Array(wr[0]*wr[1]),wr);for(let mr=0;mr<wr[0];++mr){const xr=dr[mr].neg().squeeze_(0),[Nr,$n]=(0,E.dynamic_time_warping)(xr.tolist()),zn=Array.from({length:Nr.length-1},(dn,Tn)=>Nr[Tn+1]-Nr[Tn]),Pi=(0,_.mergeArrays)([1],zn).map(dn=>!!dn),Mn=[];for(let dn=0;dn<Pi.length;++dn)Pi[dn]&&Mn.push($n[dn]*Ze);pr[mr].data.set(Mn,1)}return pr}}class ga extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(this,"main_input_name","pixel_values");He(this,"forward_params",["pixel_values","input_ids","encoder_hidden_states","past_key_values"]);this.generation_config=Ze}}class cu extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(this,"forward_params",["input_ids","pixel_values","attention_mask","position_ids","past_key_values"]);this.generation_config=Ze}}class wo extends cu{_merge_input_ids_with_image_features({inputs_embeds:G,image_features:ne,input_ids:Ee,attention_mask:Ze}){const it=this.config.image_token_index,Ct=Ee.tolist().map(dr=>dr.findIndex(wr=>wr==it)),Wt=Ct.every(dr=>dr===-1),cr=Ct.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 lr=[],Ir=[];for(let dr=0;dr<Ct.length;++dr){const wr=Ct[dr],pr=G[dr],mr=ne[dr],xr=Ze[dr];lr.push((0,y.cat)([pr.slice([0,wr]),mr,pr.slice([wr+1,pr.dims[0]])],0)),Ir.push((0,y.cat)([xr.slice([0,wr]),(0,y.ones)([mr.dims[0]]),xr.slice([wr+1,xr.dims[0]])],0))}return{inputs_embeds:(0,y.stack)(lr,0),attention_mask:(0,y.stack)(Ir,0)}}}class ar extends wo{}class du extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(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"]);He(this,"main_input_name","inputs_embeds");this.generation_config=Ze}}class _a extends du{_merge_input_ids_with_image_features({inputs_embeds:G,image_features:ne,input_ids:Ee,attention_mask:Ze}){return{inputs_embeds:(0,y.cat)([ne,G],1),attention_mask:(0,y.cat)([(0,y.ones)(ne.dims.slice(0,2)),Ze],1)}}async _prepare_inputs_embeds({input_ids:G,pixel_values:ne,inputs_embeds:Ee,attention_mask:Ze}){if(!G&&!ne)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let it,wt;return G&&(it=await this.encode_text({input_ids:G})),ne&&(wt=await this.encode_image({pixel_values:ne})),it&&wt?{inputs_embeds:Ee,attention_mask:Ze}=this._merge_input_ids_with_image_features({inputs_embeds:it,image_features:wt,input_ids:G,attention_mask:Ze}):Ee=it||wt,{inputs_embeds:Ee,attention_mask:Ze}}async forward({input_ids:G,pixel_values:ne,attention_mask:Ee,decoder_input_ids:Ze,decoder_attention_mask:it,encoder_outputs:wt,past_key_values:Ct,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:ne,inputs_embeds:Wt,attention_mask:Ee})),!wt){let{last_hidden_state:dr}=await L(this,{inputs_embeds:Wt,attention_mask:Ee});wt=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 Se(this,{inputs_embeds:cr,attention_mask:it,encoder_attention_mask:Ee,encoder_hidden_states:wt,past_key_values:Ct},!0)}}class Ho extends Q{}class pu extends Ho{}class hi extends Ho{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="text_model"),super.from_pretrained(G,ne)}}class fu extends Ho{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="vision_model"),super.from_pretrained(G,ne)}}class wa extends Q{}class yo extends wa{}class hu extends wa{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="text_model"),super.from_pretrained(G,ne)}}class mu extends Ho{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="vision_model"),super.from_pretrained(G,ne)}}class gu extends Q{}class _u extends gu{}class ya extends Q{}class wu extends ya{}class yu extends ya{}class va extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class vu extends va{}class bu extends va{}class Xn extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class xu extends Xn{}class Mu extends Xn{}class ba extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Tu extends ba{}class ku extends ba{}class xa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Su extends xa{}class Eu extends xa{}class Ma extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Cu extends Ma{}class rf extends Ma{}class Qn extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Pu extends Qn{}class As extends Qn{}class Is extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class ii extends Is{}class $u extends Is{}class Ta extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Au extends Ta{}class Iu extends Ta{}class ka extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Fu extends ka{}class Ou extends ka{}class Sa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class zu extends Sa{}class Du extends Sa{}class Yn extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Lu extends Yn{}class Ru extends Yn{}class Ea extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Bu extends Ea{}class Nu extends Ea{}class Ca extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class ju extends Ca{}class Uu extends Ca{}class Pa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Vu extends Pa{}class $a extends Pa{}class Fs extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Wu extends Fs{}class Gu extends Fs{}class Os extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class nf extends Os{}class Hu extends Os{}class Aa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class qu extends Aa{}class Ku extends Aa{}class vo extends Q{}class Xu extends vo{}class Qu extends vo{async _call(G){return new ur(await super._call(G))}}class zs extends Q{}class Yu extends zs{}class Zu extends zs{async _call(G){return new ur(await super._call(G))}}class Ju extends Q{}class ec extends Ju{async _call(G){return new ip(await super._call(G))}}class tc extends Q{}class rc extends tc{}class nc extends tc{async _call(G){return new ur(await super._call(G))}}class Ia extends Q{}class of extends Ia{}class ic extends Ia{async _call(G){return new ur(await super._call(G))}}class br extends Q{}class oc extends br{}class sc extends br{}class Fa extends Q{}class ac extends Fa{}class lc extends Fa{}class Oa extends Q{}class uc extends Oa{}class cc extends Oa{async _call(G){return new ur(await super._call(G))}}class Ds extends Q{}class dc extends Ds{}class pc extends Ds{async _call(G){return new za(await super._call(G))}}class fc extends Ds{async _call(G){return new hc(await super._call(G))}}class za extends ge{constructor({logits:G,pred_boxes:ne}){super(),this.logits=G,this.pred_boxes=ne}}class hc extends ge{constructor({logits:G,pred_boxes:ne,pred_masks:Ee}){super(),this.logits=G,this.pred_boxes=ne,this.pred_masks=Ee}}class bo extends Q{}class mc extends bo{}class Ls extends bo{async _call(G){return new gc(await super._call(G))}}class gc extends ge{constructor({logits:G,pred_boxes:ne}){super(),this.logits=G,this.pred_boxes=ne}}class Da extends Q{}class _c extends Da{}class wc extends Da{async _call(G){return new yc(await super._call(G))}}class yc extends za{}class La extends Q{}class vc extends La{}class bc extends La{async _call(G){return new ur(await super._call(G))}}class Ra extends Q{}class xc extends Ra{}class Mc extends Ra{async _call(G){return new ur(await super._call(G))}}class Ba extends Q{}class Tc extends Ba{}class kc extends Ba{async _call(G){return new ur(await super._call(G))}}class Na extends Q{}class Sc extends Na{}class ja extends Na{}class Ua extends Q{}class Va extends Ua{}class Wa extends Ua{}class Ec extends Q{}class Cc extends Ec{}class Ga extends Q{}class Pc extends Ga{}class $c extends Ga{}class Ac extends Q{}class Ha extends Ac{}class qa extends Q{}class Ic extends qa{}class Fc extends qa{async _call(G){return new ur(await super._call(G))}}class Oc extends Q{}class zc extends Oc{}class Dc extends Oc{async _call(G){return new ur(await super._call(G))}}class Zn extends Q{}class Lc extends Zn{}class Rc extends Zn{async _call(G){return new ur(await super._call(G))}}class Ka extends Q{}class Bc extends Ka{}class Nc extends Ka{async _call(G){return new jc(await super._call(G))}}class jc extends ge{constructor({logits:G,pred_boxes:ne}){super(),this.logits=G,this.pred_boxes=ne}}class Uc extends Q{}class Vc extends Uc{async get_image_embeddings({pixel_values:G}){return await L(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,wt)=>it*wt,1);G.input_labels=new y.Tensor("int64",new BigInt64Array(Ze).fill(1n),Ee)}const ne={image_embeddings:G.image_embeddings,image_positional_embeddings:G.image_positional_embeddings};return G.input_points&&(ne.input_points=G.input_points),G.input_labels&&(ne.input_labels=G.input_labels),G.input_boxes&&(ne.input_boxes=G.input_boxes),await ae(this.sessions.prompt_encoder_mask_decoder,ne)}async _call(G){return new Wc(await super._call(G))}}class Wc extends ge{constructor({iou_scores:G,pred_masks:ne}){super(),this.iou_scores=G,this.pred_masks=ne}}class Xa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class sf extends Xa{}class Gc extends Xa{}class Qa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Hc extends Qa{}class qc extends Qa{}class Ui extends Q{}class Kc extends Ui{}class af extends Ui{async _call(G){return new to(await super._call(G))}}class Vi extends Ui{async _call(G){return new ur(await super._call(G))}}class Wi extends Ui{async _call(G){return new hn(await super._call(G))}}class Ei extends Q{}class Ya extends Ei{}class Gi extends Ei{async _call(G){return new hn(await super._call(G))}}class vn extends Q{}class Za extends vn{}class xo extends Q{}class Ja extends xo{}class Xc extends xo{async _call(G){return new to(await super._call(G))}}class Qc extends xo{async _call(G){return new ur(await super._call(G))}}class qo extends Q{}class Rs extends qo{}class el extends qo{async _call(G){return new to(await super._call(G))}}class Yc extends qo{async _call(G){return new ur(await super._call(G))}}class Bs extends qo{async _call(G){return new hn(await super._call(G))}}class Ns extends Q{}class tl extends Ns{}class js extends Ns{async _call(G){return new to(await super._call(G))}}class Zc extends Ns{async _call(G){return new ur(await super._call(G))}}class lf extends Q{}class uf extends Ui{}class Jc extends Ui{async _call(G){return new to(await super._call(G))}}class rl extends Ui{async _call(G){return new ur(await super._call(G))}}class Ci extends Q{}class ed extends Ci{}class nl extends Ci{async _call(G){return new to(await super._call(G))}}class td extends Ci{async _call(G){return new ur(await super._call(G))}}class rd extends Ci{async _call(G){return new np(await super._call(G))}}class nd extends Ci{async _call(G){return new hn(await super._call(G))}}class il extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class id extends il{}class od extends il{}class cf extends il{async generate_speech(G,ne,{threshold:Ee=.5,minlenratio:Ze=0,maxlenratio:it=20,vocoder:wt=null}={}){const Ct={input_ids:G},{encoder_outputs:Wt,encoder_attention_mask:cr}=await L(this,Ct),lr=Wt.dims[1]/this.config.reduction_factor,Ir=Math.floor(lr*it),dr=Math.floor(lr*Ze),wr=this.config.num_mel_bins;let pr=[],mr=null,xr=null,Nr=0;for(;;){++Nr;const Pi=Y(!!xr);let Mn;xr?Mn=xr.output_sequence_out:Mn=new y.Tensor("float32",new Float32Array(wr),[1,1,wr]);let dn={use_cache_branch:Pi,output_sequence:Mn,encoder_attention_mask:cr,speaker_embeddings:ne,encoder_hidden_states:Wt};this.addPastKeyValues(dn,mr),xr=await ae(this.sessions.decoder_model_merged,dn),mr=this.getPastKeyValues(xr,mr);const{prob:Tn,spectrum:qs}=xr;if(pr.push(qs),Nr>=dr&&(Array.from(Tn.data).filter(Ks=>Ks>=Ee).length>0||Nr>=Ir))break}const $n=(0,y.cat)(pr),{waveform:zn}=await ae(wt.sessions.model,{spectrogram:$n});return{spectrogram:$n,waveform:zn}}}class ol extends Q{constructor(){super(...arguments);He(this,"main_input_name","spectrogram")}}class sd extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class ad extends sd{}class sl extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Us extends sl{}class Vs extends sl{}class al extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Ws extends al{}class ll extends al{}class ul extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class ld extends ul{}class ud extends ul{}class Ko extends Q{}class cd extends Ko{}class dd extends Ko{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="text_model"),super.from_pretrained(G,ne)}}class pd extends Ko{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="audio_model"),super.from_pretrained(G,ne)}}class df extends Q{}class cl extends df{async _call(G){return new Sf(await super._call(G))}}class Xo extends Q{}class mm extends Xo{}class fd extends Xo{}class hd extends Xo{}class dl extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class pl extends dl{}class md extends dl{}class fl extends Q{}class gd extends fl{}class _d extends fl{async _call(G){return new ur(await super._call(G))}}class hl extends Q{}class pf extends hl{}class gm extends hl{}class ml extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(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(ne){const[Ee,Ze]=ne.dims,it=this.config.decoder.num_codebooks,wt=Ze-it;let Ct=0;for(let lr=0;lr<ne.size;++lr){if(ne.data[lr]===this.config.decoder.pad_token_id)continue;const Ir=lr%Ze,dr=Math.floor(lr/Ze)%it,wr=Ir-dr;wr>0&&wr<=wt&&(ne.data[Ct++]=ne.data[lr])}const Wt=Math.floor(Ee/it),cr=Ct/(Wt*it);return new y.Tensor(ne.type,ne.data.slice(0,Ct),[Wt,it,cr])}prepare_inputs_for_generation(ne,Ee,Ze){let it=structuredClone(ne);for(let Ct=0;Ct<it.length;++Ct)for(let Wt=0;Wt<it[Ct].length;++Wt)Ct%this.config.decoder.num_codebooks>=Wt&&(it[Ct][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(ne){const Ee=await super.generate(ne),Ze=this._apply_and_filter_by_delay_pattern_mask(Ee).unsqueeze_(0),{audio_values:it}=await ae(this.sessions.encodec_decode,{audio_codes:Ze});return it}}class gl extends Q{}class wd extends gl{}class ff extends gl{async _call(G){return new ur(await super._call(G))}}class _l extends Q{}class yd extends _l{}class vd extends _l{async _call(G){return new ur(await super._call(G))}}class wl extends Q{}class bd extends wl{}class hf extends wl{async _call(G){return new ur(await super._call(G))}}class Qo extends Q{}class Yo extends Qo{}class yl extends Qo{async _call(G){return new ur(await super._call(G))}}class Rr{static async from_pretrained(G,{progress_callback:ne=null,config:Ee=null,cache_dir:Ze=null,local_files_only:it=!1,revision:wt="main",model_file_name:Ct=null,subfolder:Wt="onnx",device:cr=null,dtype:lr=null,use_external_data_format:Ir=null,session_options:dr={}}={}){let wr={progress_callback:ne,config:Ee,cache_dir:Ze,local_files_only:it,revision:wt,model_file_name:Ct,subfolder:Wt,device:cr,dtype:lr,use_external_data_format:Ir,session_options:dr};if(wr.config=await o.AutoConfig.from_pretrained(G,wr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let pr of this.MODEL_CLASS_MAPPINGS){const mr=pr.get(wr.config.model_type);if(mr)return await mr[1].from_pretrained(G,wr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${wr.config.model_type}", attempting to construct from base class.`),await Q.from_pretrained(G,wr);throw Error(`Unsupported model type: ${wr.config.model_type}`)}}He(Rr,"MODEL_CLASS_MAPPINGS",null),He(Rr,"BASE_IF_FAIL",!1);const mf=new Map([["bert",["BertModel",Be]],["nomic_bert",["NomicBertModel",je]],["roformer",["RoFormerModel",et]],["electra",["ElectraModel",ke]],["esm",["EsmModel",un]],["convbert",["ConvBertModel",ye]],["camembert",["CamembertModel",ve]],["deberta",["DebertaModel",ht]],["deberta-v2",["DebertaV2Model",Ot]],["mpnet",["MPNetModel",Cs]],["albert",["AlbertModel",Ji]],["distilbert",["DistilBertModel",Pr]],["roberta",["RobertaModel",_r]],["xlm",["XLMModel",cn]],["xlm-roberta",["XLMRobertaModel",Er]],["clap",["ClapModel",cd]],["clip",["CLIPModel",pu]],["clipseg",["CLIPSegModel",wu]],["chinese_clip",["ChineseCLIPModel",_u]],["siglip",["SiglipModel",yo]],["mobilebert",["MobileBertModel",Kr]],["squeezebert",["SqueezeBertModel",Ps]],["wav2vec2",["Wav2Vec2Model",Kc]],["wav2vec2-bert",["Wav2Vec2BertModel",tl]],["unispeech",["UniSpeechModel",Ja]],["unispeech-sat",["UniSpeechSatModel",Rs]],["hubert",["HubertModel",uf]],["wavlm",["WavLMModel",ed]],["audio-spectrogram-transformer",["ASTModel",zt]],["vits",["VitsModel",cl]],["pyannote",["PyAnnoteModel",Ya]],["wespeaker-resnet",["WeSpeakerResNetModel",Za]],["detr",["DetrModel",dc]],["rt_detr",["RTDetrModel",mc]],["table-transformer",["TableTransformerModel",_c]],["vit",["ViTModel",Xu]],["fastvit",["FastViTModel",Yu]],["mobilevit",["MobileViTModel",rc]],["mobilevitv2",["MobileViTV2Model",of]],["owlvit",["OwlViTModel",oc]],["owlv2",["Owlv2Model",ac]],["beit",["BeitModel",uc]],["deit",["DeiTModel",vc]],["convnext",["ConvNextModel",Ic]],["convnextv2",["ConvNextV2Model",zc]],["dinov2",["Dinov2Model",Lc]],["resnet",["ResNetModel",xc]],["swin",["SwinModel",Tc]],["swin2sr",["Swin2SRModel",Sc]],["donut-swin",["DonutSwinModel",Ha]],["yolos",["YolosModel",Bc]],["dpt",["DPTModel",Va]],["glpn",["GLPNModel",Pc]],["hifigan",["SpeechT5HifiGan",ol]],["efficientnet",["EfficientNetModel",gd]],["mobilenet_v1",["MobileNetV1Model",wd]],["mobilenet_v2",["MobileNetV2Model",yd]],["mobilenet_v3",["MobileNetV3Model",bd]],["mobilenet_v4",["MobileNetV4Model",Yo]]]),gf=new Map([["t5",["T5Model",jo]],["longt5",["LongT5Model",Vo]],["mt5",["MT5Model",Go]],["bart",["BartModel",Ue]],["mbart",["MBartModel",Fe]],["marian",["MarianModel",sf]],["whisper",["WhisperModel",Gt]],["m2m_100",["M2M100Model",Hc]],["blenderbot",["BlenderbotModel",kt]],["blenderbot-small",["BlenderbotSmallModel",Ar]]]),_f=new Map([["bloom",["BloomModel",Wu]],["gpt2",["GPT2Model",vu]],["gptj",["GPTJModel",Su]],["gpt_bigcode",["GPTBigCodeModel",Cu]],["gpt_neo",["GPTNeoModel",xu]],["gpt_neox",["GPTNeoXModel",Tu]],["codegen",["CodeGenModel",Pu]],["llama",["LlamaModel",ii]],["cohere",["CohereModel",Au]],["gemma",["GemmaModel",Fu]],["gemma2",["Gemma2Model",zu]],["openelm",["OpenELMModel",Lu]],["qwen2",["Qwen2Model",Bu]],["phi",["PhiModel",ju]],["phi3",["Phi3Model",Vu]],["mpt",["MptModel",nf]],["opt",["OPTModel",qu]],["mistral",["MistralModel",Us]],["starcoder2",["Starcoder2Model",Ws]],["falcon",["FalconModel",ld]],["stablelm",["StableLmModel",pl]]]),Gs=new Map([["speecht5",["SpeechT5ForSpeechToText",od]],["whisper",["WhisperForConditionalGeneration",ma]]]),xd=new Map([["speecht5",["SpeechT5ForTextToSpeech",cf]]]),Md=new Map([["vits",["VitsModel",cl]],["musicgen",["MusicgenForConditionalGeneration",ml]]]),Td=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",$e]],["electra",["ElectraForSequenceClassification",dt]],["esm",["EsmForSequenceClassification",Mi]],["convbert",["ConvBertForSequenceClassification",ee]],["camembert",["CamembertForSequenceClassification",qe]],["deberta",["DebertaForSequenceClassification",bt]],["deberta-v2",["DebertaV2ForSequenceClassification",Xt]],["mpnet",["MPNetForSequenceClassification",Ro]],["albert",["AlbertForSequenceClassification",ho]],["distilbert",["DistilBertForSequenceClassification",Yr]],["roberta",["RobertaForSequenceClassification",gn]],["xlm",["XLMForSequenceClassification",Jt]],["xlm-roberta",["XLMRobertaForSequenceClassification",vr]],["bart",["BartForSequenceClassification",pe]],["mbart",["MBartForSequenceClassification",rt]],["mobilebert",["MobileBertForSequenceClassification",Dr]],["squeezebert",["SqueezeBertForSequenceClassification",fi]]]),wf=new Map([["bert",["BertForTokenClassification",pt]],["roformer",["RoFormerForTokenClassification",Pe]],["electra",["ElectraForTokenClassification",Je]],["esm",["EsmForTokenClassification",Gr]],["convbert",["ConvBertForTokenClassification",D]],["camembert",["CamembertForTokenClassification",Qe]],["deberta",["DebertaForTokenClassification",Et]],["deberta-v2",["DebertaV2ForTokenClassification",Yt]],["mpnet",["MPNetForTokenClassification",Bo]],["distilbert",["DistilBertForTokenClassification",$r]],["roberta",["RobertaForTokenClassification",ct]],["xlm",["XLMForTokenClassification",Un]],["xlm-roberta",["XLMRobertaForTokenClassification",Lr]]]),vl=new Map([["t5",["T5ForConditionalGeneration",Uo]],["longt5",["LongT5ForConditionalGeneration",Wo]],["mt5",["MT5ForConditionalGeneration",Vr]],["bart",["BartForConditionalGeneration",W]],["mbart",["MBartForConditionalGeneration",Oe]],["marian",["MarianMTModel",Gc]],["m2m_100",["M2M100ForConditionalGeneration",qc]],["blenderbot",["BlenderbotForConditionalGeneration",It]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",or]]]),Hs=new Map([["bloom",["BloomForCausalLM",Gu]],["gpt2",["GPT2LMHeadModel",bu]],["gptj",["GPTJForCausalLM",Eu]],["gpt_bigcode",["GPTBigCodeForCausalLM",rf]],["gpt_neo",["GPTNeoForCausalLM",Mu]],["gpt_neox",["GPTNeoXForCausalLM",ku]],["codegen",["CodeGenForCausalLM",As]],["llama",["LlamaForCausalLM",$u]],["cohere",["CohereForCausalLM",Iu]],["gemma",["GemmaForCausalLM",Ou]],["gemma2",["Gemma2ForCausalLM",Du]],["openelm",["OpenELMForCausalLM",Ru]],["qwen2",["Qwen2ForCausalLM",Nu]],["phi",["PhiForCausalLM",Uu]],["phi3",["Phi3ForCausalLM",$a]],["mpt",["MptForCausalLM",Hu]],["opt",["OPTForCausalLM",Ku]],["mbart",["MBartForCausalLM",Mt]],["mistral",["MistralForCausalLM",Vs]],["starcoder2",["Starcoder2ForCausalLM",ll]],["falcon",["FalconForCausalLM",ud]],["trocr",["TrOCRForCausalLM",ad]],["stablelm",["StableLmForCausalLM",md]]]),kd=new Map([["bert",["BertForMaskedLM",We]],["roformer",["RoFormerForMaskedLM",A]],["electra",["ElectraForMaskedLM",Ne]],["esm",["EsmForMaskedLM",Bi]],["convbert",["ConvBertForMaskedLM",R]],["camembert",["CamembertForMaskedLM",Re]],["deberta",["DebertaForMaskedLM",Tt]],["deberta-v2",["DebertaV2ForMaskedLM",Ut]],["mpnet",["MPNetForMaskedLM",Lo]],["albert",["AlbertForMaskedLM",Zt]],["distilbert",["DistilBertForMaskedLM",$t]],["roberta",["RobertaForMaskedLM",Cn]],["xlm",["XLMWithLMHeadModel",On]],["xlm-roberta",["XLMRobertaForMaskedLM",At]],["mobilebert",["MobileBertForMaskedLM",pi]],["squeezebert",["SqueezeBertForMaskedLM",fo]]]),Sd=new Map([["bert",["BertForQuestionAnswering",Ge]],["roformer",["RoFormerForQuestionAnswering",se]],["electra",["ElectraForQuestionAnswering",Ve]],["convbert",["ConvBertForQuestionAnswering",ue]],["camembert",["CamembertForQuestionAnswering",tt]],["deberta",["DebertaForQuestionAnswering",Lt]],["deberta-v2",["DebertaV2ForQuestionAnswering",rr]],["mpnet",["MPNetForQuestionAnswering",No]],["albert",["AlbertForQuestionAnswering",mo]],["distilbert",["DistilBertForQuestionAnswering",mt]],["roberta",["RobertaForQuestionAnswering",Kn]],["xlm",["XLMForQuestionAnswering",yn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Xr]],["mobilebert",["MobileBertForQuestionAnswering",Ni]],["squeezebert",["SqueezeBertForQuestionAnswering",ki]]]),bl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ga]]]),_m=new Map([["llava",["LlavaForConditionalGeneration",wo]],["moondream1",["Moondream1ForConditionalGeneration",ar]],["florence2",["Florence2ForConditionalGeneration",_a]]]),yf=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ga]]]),Ed=new Map([["vit",["ViTForImageClassification",Qu]],["fastvit",["FastViTForImageClassification",Zu]],["mobilevit",["MobileViTForImageClassification",nc]],["mobilevitv2",["MobileViTV2ForImageClassification",ic]],["beit",["BeitForImageClassification",cc]],["deit",["DeiTForImageClassification",bc]],["convnext",["ConvNextForImageClassification",Fc]],["convnextv2",["ConvNextV2ForImageClassification",Dc]],["dinov2",["Dinov2ForImageClassification",Rc]],["resnet",["ResNetForImageClassification",Mc]],["swin",["SwinForImageClassification",kc]],["segformer",["SegformerForImageClassification",fd]],["efficientnet",["EfficientNetForImageClassification",_d]],["mobilenet_v1",["MobileNetV1ForImageClassification",ff]],["mobilenet_v2",["MobileNetV2ForImageClassification",vd]],["mobilenet_v3",["MobileNetV3ForImageClassification",hf]],["mobilenet_v4",["MobileNetV4ForImageClassification",yl]]]),vf=new Map([["detr",["DetrForObjectDetection",pc]],["rt_detr",["RTDetrForObjectDetection",Ls]],["table-transformer",["TableTransformerForObjectDetection",wc]],["yolos",["YolosForObjectDetection",Nc]]]),Cd=new Map([["owlvit",["OwlViTForObjectDetection",sc]],["owlv2",["Owlv2ForObjectDetection",lc]]]),Pd=new Map([["detr",["DetrForSegmentation",fc]],["clipseg",["CLIPSegForImageSegmentation",yu]]]),$d=new Map([["segformer",["SegformerForSemanticSegmentation",hd]]]),Ad=new Map([["sam",["SamModel",Vc]]]),bf=new Map([["wav2vec2",["Wav2Vec2ForCTC",af]],["wav2vec2-bert",["Wav2Vec2BertForCTC",js]],["unispeech",["UniSpeechForCTC",Xc]],["unispeech-sat",["UniSpeechSatForCTC",el]],["wavlm",["WavLMForCTC",nl]],["hubert",["HubertForCTC",Jc]]]),Id=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Vi]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Zc]],["unispeech",["UniSpeechForSequenceClassification",Qc]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Yc]],["wavlm",["WavLMForSequenceClassification",td]],["hubert",["HubertForSequenceClassification",rl]],["audio-spectrogram-transformer",["ASTForAudioClassification",$s]]]),Fd=new Map([["wavlm",["WavLMForXVector",rd]]]),Od=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Bs]],["wavlm",["WavLMForAudioFrameClassification",nd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wi]],["pyannote",["PyAnnoteForAudioFrameClassification",Gi]]]),zd=new Map([["vitmatte",["VitMatteForImageMatting",ec]]]),xf=new Map([["swin2sr",["Swin2SRForImageSuperResolution",ja]]]),Dd=new Map([["dpt",["DPTForDepthEstimation",Wa]],["depth_anything",["DepthAnythingForDepthEstimation",Cc]],["glpn",["GLPNForDepthEstimation",$c]]]),Ld=new Map([["clip",["CLIPVisionModelWithProjection",fu]],["siglip",["SiglipVisionModel",mu]]]),Rd=[[mf,b.EncoderOnly],[gf,b.EncoderDecoder],[_f,b.DecoderOnly],[Td,b.EncoderOnly],[wf,b.EncoderOnly],[vl,b.Seq2Seq],[Gs,b.Seq2Seq],[Hs,b.DecoderOnly],[kd,b.EncoderOnly],[Sd,b.EncoderOnly],[bl,b.Vision2Seq],[_m,b.ImageTextToText],[Ed,b.EncoderOnly],[Pd,b.EncoderOnly],[$d,b.EncoderOnly],[zd,b.EncoderOnly],[xf,b.EncoderOnly],[Dd,b.EncoderOnly],[vf,b.EncoderOnly],[Cd,b.EncoderOnly],[Ad,b.MaskGeneration],[bf,b.EncoderOnly],[Id,b.EncoderOnly],[xd,b.Seq2Seq],[Md,b.EncoderOnly],[Fd,b.EncoderOnly],[Od,b.EncoderOnly],[Ld,b.EncoderOnly]];for(const[V,G]of Rd)for(const[ne,Ee]of V.values())I.set(ne,G),z.set(Ee,ne),U.set(ne,Ee);const Mf=[["MusicgenForConditionalGeneration",ml,b.Musicgen],["CLIPTextModelWithProjection",hi,b.EncoderOnly],["SiglipTextModel",hu,b.EncoderOnly],["ClapTextModelWithProjection",dd,b.EncoderOnly],["ClapAudioModelWithProjection",pd,b.EncoderOnly]];for(const[V,G,ne]of Mf)I.set(V,ne),z.set(G,V),U.set(V,G);class Bd extends Rr{}He(Bd,"MODEL_CLASS_MAPPINGS",Rd.map(G=>G[0])),He(Bd,"BASE_IF_FAIL",!0);class Pn extends Rr{}He(Pn,"MODEL_CLASS_MAPPINGS",[Td]);class Nd extends Rr{}He(Nd,"MODEL_CLASS_MAPPINGS",[wf]);class jd extends Rr{}He(jd,"MODEL_CLASS_MAPPINGS",[vl]);class xl extends Rr{}He(xl,"MODEL_CLASS_MAPPINGS",[Gs]);class Ud extends Rr{}He(Ud,"MODEL_CLASS_MAPPINGS",[xd]);class Zo extends Rr{}He(Zo,"MODEL_CLASS_MAPPINGS",[Md]);class Vd extends Rr{}He(Vd,"MODEL_CLASS_MAPPINGS",[Hs]);class Wd extends Rr{}He(Wd,"MODEL_CLASS_MAPPINGS",[kd]);class Ml extends Rr{}He(Ml,"MODEL_CLASS_MAPPINGS",[Sd]);class Gd extends Rr{}He(Gd,"MODEL_CLASS_MAPPINGS",[bl]);class Hd extends Rr{}He(Hd,"MODEL_CLASS_MAPPINGS",[Ed]);class Tl extends Rr{}He(Tl,"MODEL_CLASS_MAPPINGS",[Pd]);class qd extends Rr{}He(qd,"MODEL_CLASS_MAPPINGS",[$d]);class Kd extends Rr{}He(Kd,"MODEL_CLASS_MAPPINGS",[vf]);class Xd extends Rr{}He(Xd,"MODEL_CLASS_MAPPINGS",[Cd]);class kl extends Rr{}He(kl,"MODEL_CLASS_MAPPINGS",[Ad]);class Qd extends Rr{}He(Qd,"MODEL_CLASS_MAPPINGS",[bf]);class Yd extends Rr{}He(Yd,"MODEL_CLASS_MAPPINGS",[Id]);class Sl extends Rr{}He(Sl,"MODEL_CLASS_MAPPINGS",[Fd]);class Zd extends Rr{}He(Zd,"MODEL_CLASS_MAPPINGS",[Od]);class Tf extends Rr{}He(Tf,"MODEL_CLASS_MAPPINGS",[yf]);class Jd extends Rr{}He(Jd,"MODEL_CLASS_MAPPINGS",[zd]);class ep extends Rr{}He(ep,"MODEL_CLASS_MAPPINGS",[xf]);class tp extends Rr{}He(tp,"MODEL_CLASS_MAPPINGS",[Dd]);class rp extends Rr{}He(rp,"MODEL_CLASS_MAPPINGS",[Ld]);class wm extends ge{constructor({logits:G,past_key_values:ne,encoder_outputs:Ee,decoder_attentions:Ze=null,cross_attentions:it=null}){super(),this.logits=G,this.past_key_values=ne,this.encoder_outputs=Ee,this.decoder_attentions=Ze,this.cross_attentions=it}}class ur extends ge{constructor({logits:G}){super(),this.logits=G}}class np extends ge{constructor({logits:G,embeddings:ne}){super(),this.logits=G,this.embeddings=ne}}class hn extends ge{constructor({logits:G}){super(),this.logits=G}}class bn extends ge{constructor({logits:G}){super(),this.logits=G}}class xn extends ge{constructor({start_logits:G,end_logits:ne}){super(),this.start_logits=G,this.end_logits=ne}}class to extends ge{constructor({logits:G}){super(),this.logits=G}}class kf extends ge{constructor({logits:G,past_key_values:ne}){super(),this.logits=G,this.past_key_values=ne}}class ip extends ge{constructor({alphas:G}){super(),this.alphas=G}}class Sf extends ge{constructor({waveform:G,spectrogram:ne}){super(),this.waveform=G,this.spectrogram=ne}}},"./src/models/whisper/common_whisper.js":(e,t,r)=>{r.r(t),r.d(t,{WHISPER_LANGUAGE_MAPPING:()=>a,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>l,whisper_language_to_code:()=>p});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 p(_){_=_.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,r)=>{r.r(t),r.d(t,{WhisperGenerationConfig:()=>a});var o=r("./src/generation/configuration_utils.js");class a extends o.GenerationConfig{constructor(){super(...arguments);He(this,"return_timestamps",null);He(this,"return_token_timestamps",null);He(this,"num_frames",null);He(this,"alignment_heads",null);He(this,"task",null);He(this,"language",null);He(this,"no_timestamps_token_id",null);He(this,"prompt_ids",null);He(this,"is_multilingual",null);He(this,"lang_to_id",null);He(this,"task_to_id",null);He(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(e,t,r)=>{r.r(t),r.d(t,{TensorOpRegistry:()=>p});var o=r("./src/backends/onnx.js"),a=r("./src/utils/tensor.js");const l=async(_,h,g)=>{const M=await(0,o.createInferenceSession)(new Uint8Array(_),h);return async y=>{const E=Object.fromEntries(Object.entries(y).map(([O,S])=>[O,S.ort_tensor])),T=await M.run(E);return Array.isArray(g)?g.map(O=>new a.Tensor(T[O])):new a.Tensor(T[g])}};class p{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}}He(p,"session_options",{})},"./src/pipelines.js":(e,t,r)=>{r.r(t),r.d(t,{AudioClassificationPipeline:()=>Y,AutomaticSpeechRecognitionPipeline:()=>L,DepthEstimationPipeline:()=>Le,DocumentQuestionAnsweringPipeline:()=>Q,FeatureExtractionPipeline:()=>ce,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>Xe,ImageFeatureExtractionPipeline:()=>xe,ImageSegmentationPipeline:()=>me,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>Se,ObjectDetectionPipeline:()=>ie,Pipeline:()=>S,QuestionAnsweringPipeline:()=>b,SummarizationPipeline:()=>z,Text2TextGenerationPipeline:()=>U,TextClassificationPipeline:()=>C,TextGenerationPipeline:()=>N,TextToAudioPipeline:()=>ge,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>B,ZeroShotAudioClassificationPipeline:()=>_e,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>X,ZeroShotObjectDetectionPipeline:()=>Me,pipeline:()=>st});var o=r("./src/tokenizers.js"),a=r("./src/models.js"),l=r("./src/processors.js"),p=r("./src/utils/generic.js"),_=r("./src/utils/core.js"),h=r("./src/utils/maths.js"),g=r("./src/utils/audio.js"),M=r("./src/utils/tensor.js"),y=r("./src/utils/image.js");async function E(Ge){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(Te=>y.RawImage.read(Te)))}async function T(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 O(Ge,Te){Te&&(Ge=Ge.map($e=>$e|0));const[je,Ye,et,A]=Ge;return{xmin:je,ymin:Ye,xmax:et,ymax:A}}class S extends p.Callable{constructor({task:Te,model:je,tokenizer:Ye=null,processor:et=null}){super(),this.task=Te,this.model=je,this.tokenizer=Ye,this.processor=et}async dispose(){await this.model.dispose()}}class C extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=1}={}){const Ye=this.tokenizer(Te,{padding:!0,truncation:!0}),et=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),$e=this.model.config.id2label,Pe=[];for(const se of et.logits){const re=A(se),ye=await(0,M.topk)(re,je),R=ye[0].tolist(),D=ye[1].tolist().map((ue,le)=>({label:$e?$e[ue]:`LABEL_${ue}`,score:R[le]}));je===1?Pe.push(...D):Pe.push(D)}return Array.isArray(Te)||je===1?Pe:Pe[0]}}class w extends S{constructor(Te){super(Te)}async _call(Te,{ignore_labels:je=["O"]}={}){const Ye=Array.isArray(Te),et=this.tokenizer(Ye?Te:[Te],{padding:!0,truncation:!0}),$e=(await this.model(et)).logits,Pe=this.model.config.id2label,se=[];for(let re=0;re<$e.dims[0];++re){const ye=et.input_ids[re],R=$e[re],ee=[];for(let D=0;D<R.dims[0];++D){const ue=R[D],le=(0,h.max)(ue.data)[1],ke=Pe?Pe[le]:`LABEL_${le}`;if(je.includes(ke))continue;const Ne=this.tokenizer.decode([ye[D].item()],{skip_special_tokens:!0});if(Ne==="")continue;const dt=(0,h.softmax)(ue.data);ee.push({entity:ke,score:dt[le],index:D,word:Ne})}se.push(ee)}return Ye?se:se[0]}}class b extends S{constructor(Te){super(Te)}async _call(Te,je,{top_k:Ye=1}={}){const et=this.tokenizer(Te,{text_pair:je,padding:!0,truncation:!0}),{start_logits:A,end_logits:$e}=await this.model(et),Pe=et.input_ids.tolist(),se=et.attention_mask.tolist(),re=this.tokenizer.all_special_ids,ye=[];for(let R=0;R<A.dims[0];++R){const ee=Pe[R],D=ee.findIndex(Je=>Je==this.tokenizer.sep_token_id);se[R].map((Je,Ve)=>Je==1&&(Ve===0||Ve>D&&re.findIndex(Z=>Z==ee[Ve])===-1));const ue=A[R].tolist(),le=$e[R].tolist();for(let Je=1;Je<ue.length;++Je)(se[R]==0||Je<=D||re.findIndex(Ve=>Ve==ee[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 dt=(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(dt.length,Ye);++Je){const[Ve,Z,ve]=dt[Je],Re=ee.slice(Ve,Z+1),qe=this.tokenizer.decode(Re,{skip_special_tokens:!0});ye.push({answer:qe,score:ve})}}return Ye===1?ye[0]:ye}}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:et}=await this.model(Ye),A=[],$e=Ye.input_ids.tolist();for(let Pe=0;Pe<$e.length;++Pe){const se=$e[Pe],re=se.findIndex(ue=>ue==this.tokenizer.mask_token_id);if(re===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ye=et[Pe][re],R=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(ye.data),ye.dims),je),ee=R[0].tolist(),D=R[1].tolist();A.push(D.map((ue,le)=>{const ke=se.slice();return ke[re]=ue,{score:ee[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);He(this,"_key","generated_text")}async _call(je,Ye={}){Array.isArray(je)||(je=[je]),this.model.config.prefix&&(je=je.map(re=>this.model.config.prefix+re));const et=this.model.config.task_specific_params;et&&et[this.task]&&et[this.task].prefix&&(je=je.map(re=>et[this.task].prefix+re));const A=this.tokenizer,$e={padding:!0,truncation:!0};let Pe;this instanceof B&&"_build_translation_inputs"in A?Pe=A._build_translation_inputs(je,$e,Ye):Pe=A(je,$e);const se=await this.model.generate({...Pe,...Ye});return A.batch_decode(se,{skip_special_tokens:!0}).map(re=>({[this._key]:re}))}}class z extends U{constructor(je){super(je);He(this,"_key","summary_text")}}class B extends U{constructor(je){super(je);He(this,"_key","translation_text")}}function j(Ge){return Array.isArray(Ge)&&Ge.every(Te=>"role"in Te&&"content"in Te)}class N extends S{constructor(Te){super(Te)}async _call(Te,je={}){let Ye=!1,et=!1,A;if(typeof Te=="string")A=Te=[Te];else if(Array.isArray(Te)&&Te.every(D=>typeof D=="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");et=!0,A=Te.map(D=>this.tokenizer.apply_chat_template(D,{tokenize:!1,add_generation_prompt:!0}))}const $e=je.add_special_tokens??!1,Pe=et?!1:je.return_full_text??!0;this.tokenizer.padding_side="left";const se=this.tokenizer(A,{add_special_tokens:$e,padding:!0,truncation:!0}),re=await this.model.generate({...se,...je}),ye=this.tokenizer.batch_decode(re,{skip_special_tokens:!0});let R;!Pe&&se.input_ids.dims.at(-1)>0&&(R=this.tokenizer.batch_decode(se.input_ids,{skip_special_tokens:!0}).map(D=>D.length));const ee=Array.from({length:Te.length},D=>[]);for(let D=0;D<ye.length;++D){const ue=Math.floor(D/re.dims[0]*Te.length);R&&(ye[D]=ye[D].slice(R[ue])),ee[ue].push({generated_text:et?[...Te[ue],{role:"assistant",content:ye[D]}]:ye[D]})}return!Ye&&ee.length===1?ee[0]:ee}}class ae 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:et=!1}={}){const A=Array.isArray(Te);A||(Te=[Te]),Array.isArray(je)||(je=[je]);const $e=je.map(re=>Ye.replace("{}",re)),Pe=et||je.length===1,se=[];for(const re of Te){const ye=[];for(const D of $e){const ue=this.tokenizer(re,{text_pair:D,padding:!0,truncation:!0}),le=await this.model(ue);Pe?ye.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):ye.push(le.logits.data[this.entailment_id])}const ee=(Pe?ye.map(D=>(0,h.softmax)(D)[1]):(0,h.softmax)(ye)).map((D,ue)=>[D,ue]).sort((D,ue)=>ue[0]-D[0]);se.push({sequence:re,labels:ee.map(D=>je[D[1]]),scores:ee.map(D=>D[0])})}return A?se:se[0]}}class ce extends S{constructor(Te){super(Te)}async _call(Te,{pooling:je="none",normalize:Ye=!1,quantize:et=!1,precision:A="binary"}={}){const $e=this.tokenizer(Te,{padding:!0,truncation:!0}),Pe=await this.model($e);let se=Pe.last_hidden_state??Pe.logits??Pe.token_embeddings;if(je!=="none")if(je==="mean")se=(0,M.mean_pooling)(se,$e.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)),et&&(se=(0,M.quantize_embeddings)(se,A)),se}}class xe extends S{constructor(Te){super(Te)}async _call(Te,{pool:je=null}={}){const Ye=await E(Te),{pixel_values:et}=await this.processor(Ye),A=await this.model({pixel_values:et});let $e;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.");$e=A.pooler_output}else $e=A.last_hidden_state??A.logits??A.image_embeds;return $e}}class Y extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=this.processor.feature_extractor.config.sampling_rate,et=await T(Te,Ye),A=this.model.config.id2label,$e=[];for(const Pe of et){const se=await this.processor(Pe),ye=(await this.model(se)).logits[0],R=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(ye.data),ye.dims),je),ee=R[0].tolist(),ue=R[1].tolist().map((le,ke)=>({label:A?A[le]:`LABEL_${le}`,score:ee[ke]}));$e.push(ue)}return Array.isArray(Te)?$e:$e[0]}}class _e extends S{constructor(Te){super(Te)}async _call(Te,je,{hypothesis_template:Ye="This is a sound of {}."}={}){const et=!Array.isArray(Te);et&&(Te=[Te]);const A=je.map(ye=>Ye.replace("{}",ye)),$e=this.tokenizer(A,{padding:!0,truncation:!0}),Pe=this.processor.feature_extractor.config.sampling_rate,se=await T(Te,Pe),re=[];for(const ye of se){const R=await this.processor(ye),ee=await this.model({...$e,...R}),D=(0,h.softmax)(ee.logits_per_audio.data);re.push([...D].map((ue,le)=>({score:ue,label:je[le]})))}return et?re[0]:re}}class L 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 et=this.processor.feature_extractor.config.sampling_rate,A=await T(Te,et),$e=[];for(const Pe of A){const se=await this.processor(Pe),ye=(await this.model(se)).logits[0],R=[];for(const D of ye)R.push((0,h.max)(D.data)[1]);const ee=this.tokenizer.decode(R);$e.push({text:ee})}return Ye?$e[0]:$e}async _call_whisper(Te,je){const Ye=je.return_timestamps??!1,et=je.chunk_length_s??0,A=je.force_full_sequences??!1;let $e=je.stride_length_s??null;const Pe={...je};Ye==="word"&&(Pe.return_token_timestamps=!0,Pe.return_timestamps=!1);const se=!Array.isArray(Te);se&&(Te=[Te]);const re=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ye=this.processor.feature_extractor.config.hop_length,R=this.processor.feature_extractor.config.sampling_rate,ee=await T(Te,R),D=[];for(const ue of ee){let le=[];if(et>0){if($e===null)$e=et/6;else if(et<=$e)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const dt=R*et,Je=R*$e,Ve=dt-2*Je;let Z=0;for(;;){const ve=Z+dt,Re=ue.subarray(Z,ve),qe=await this.processor(Re),Qe=Z===0,tt=ve>=ue.length;if(le.push({stride:[Re.length,Qe?0:Je,tt?0:Je],input_features:qe.input_features,is_last:tt}),tt)break;Z+=Ve}}else le=[{stride:[ue.length,0,0],input_features:(await this.processor(ue)).input_features,is_last:!0}];for(const dt of le){Pe.num_frames=Math.floor(dt.stride[0]/ye);const Je=await this.model.generate({inputs:dt.input_features,...Pe});Ye==="word"?(dt.tokens=Je.sequences.tolist()[0],dt.token_timestamps=Je.token_timestamps.tolist()[0].map(Ve=>(0,h.round)(Ve,2))):dt.tokens=Je[0].tolist(),dt.stride=dt.stride.map(Ve=>Ve/R)}const[ke,Ne]=this.tokenizer._decode_asr(le,{time_precision:re,return_timestamps:Ye,force_full_sequences:A});D.push({text:ke,...Ne})}return se?D[0]:D}}class Se extends S{constructor(Te){super(Te)}async _call(Te,je={}){const Ye=Array.isArray(Te),et=await E(Te),{pixel_values:A}=await this.processor(et),$e=[];for(const Pe of A){Pe.dims=[1,...Pe.dims];const se=await this.model.generate({inputs:Pe,...je}),re=this.tokenizer.batch_decode(se,{skip_special_tokens:!0}).map(ye=>({generated_text:ye.trim()}));$e.push(re)}return Ye?$e:$e[0]}}class Xe extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=await E(Te),{pixel_values:et}=await this.processor(Ye),A=await this.model({pixel_values:et}),$e=this.model.config.id2label,Pe=[];for(const se of A.logits){const re=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(se.data),se.dims),je),ye=re[0].tolist(),ee=re[1].tolist().map((D,ue)=>({label:$e?$e[D]:`LABEL_${D}`,score:ye[ue]}));Pe.push(ee)}return Array.isArray(Te)?Pe:Pe[0]}}class me 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:et=.8,label_ids_to_fuse:A=null,target_sizes:$e=null,subtask:Pe=null}={}){if(Array.isArray(Te)&&Te.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const re=await E(Te),ye=re.map(Ne=>[Ne.height,Ne.width]),{pixel_values:R,pixel_mask:ee}=await this.processor(re),D=await this.model({pixel_values:R,pixel_mask:ee});let ue=null;if(Pe!==null)ue=this.subtasks_mapping[Pe];else for(let[Ne,dt]of Object.entries(this.subtasks_mapping))if(dt in this.processor.feature_extractor){ue=this.processor.feature_extractor[dt].bind(this.processor.feature_extractor),Pe=Ne;break}const le=this.model.config.id2label,ke=[];if(Pe==="panoptic"||Pe==="instance"){const Ne=ue(D,je,Ye,et,A,$e??ye)[0],dt=Ne.segmentation;for(const Je of Ne.segments_info){const Ve=new Uint8ClampedArray(dt.data.length);for(let ve=0;ve<dt.data.length;++ve)dt.data[ve]===Je.id&&(Ve[ve]=255);const Z=new y.RawImage(Ve,dt.dims[1],dt.dims[0],1);ke.push({score:Je.score,label:le[Je.label_id],mask:Z})}}else if(Pe==="semantic"){const{segmentation:Ne,labels:dt}=ue(D,$e??ye)[0];for(const Je of dt){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 y.RawImage(Ve,Ne.dims[1],Ne.dims[0],1);ke.push({score:null,label:le[Je],mask:Z})}}else throw Error(`Subtask ${Pe} not supported.`);return ke}}class X extends S{constructor(Te){super(Te)}async _call(Te,je,{hypothesis_template:Ye="This is a photo of {}"}={}){const et=Array.isArray(Te),A=await E(Te),$e=je.map(ee=>Ye.replace("{}",ee)),Pe=this.tokenizer($e,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:se}=await this.processor(A),re=await this.model({...Pe,pixel_values:se}),ye=this.model.config.model_type==="siglip"?ee=>ee.sigmoid().data:ee=>(0,h.softmax)(ee.data),R=[];for(const ee of re.logits_per_image){const ue=[...ye(ee)].map((le,ke)=>({score:le,label:je[ke]}));ue.sort((le,ke)=>ke.score-le.score),R.push(ue)}return et?R:R[0]}}class ie extends S{constructor(Te){super(Te)}async _call(Te,{threshold:je=.9,percentage:Ye=!1}={}){const et=Array.isArray(Te);if(et&&Te.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const A=await E(Te),$e=Ye?null:A.map(D=>[D.height,D.width]),{pixel_values:Pe,pixel_mask:se}=await this.processor(A),re=await this.model({pixel_values:Pe,pixel_mask:se}),ye=this.processor.feature_extractor.post_process_object_detection(re,je,$e),R=this.model.config.id2label,ee=ye.map(D=>D.boxes.map((ue,le)=>({score:D.scores[le],label:R[D.classes[le]],box:O(ue,!Ye)})));return et?ee:ee[0]}}class Me extends S{constructor(Te){super(Te)}async _call(Te,je,{threshold:Ye=.1,top_k:et=null,percentage:A=!1}={}){const $e=Array.isArray(Te),Pe=await E(Te),se=this.tokenizer(je,{padding:!0,truncation:!0}),re=await this.processor(Pe),ye=[];for(let R=0;R<Pe.length;++R){const ee=Pe[R],D=A?null:[[ee.height,ee.width]],ue=re.pixel_values[R].unsqueeze_(0),le=await this.model({...se,pixel_values:ue}),ke=this.processor.feature_extractor.post_process_object_detection(le,Ye,D,!0)[0];let Ne=ke.boxes.map((dt,Je)=>({score:ke.scores[Je],label:je[ke.classes[Je]],box:O(dt,!A)})).sort((dt,Je)=>Je.score-dt.score);et!==null&&(Ne=Ne.slice(0,et)),ye.push(Ne)}return $e?ye:ye[0]}}class Q 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 ge extends S{constructor(je){super(je);He(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:et}=await this.model(Ye),A=this.model.config.sampling_rate;return{audio:et.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:et}=this.tokenizer(je,{padding:!0,truncation:!0}),{waveform:A}=await this.model.generate_speech(et,Ye,{vocoder:this.vocoder}),$e=this.processor.feature_extractor.config.sampling_rate;return{audio:A.data,sampling_rate:$e}}}class Ke extends S{constructor(Te){super(Te)}async _call(Te){const je=await E(Te),Ye=await this.processor(je),et=await this.model(Ye),A=[];for(const $e of et.reconstruction){const Pe=$e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");A.push(y.RawImage.fromTensor(Pe))}return A.length>1?A:A[0]}}class Le extends S{constructor(Te){super(Te)}async _call(Te){const je=await E(Te),Ye=await this.processor(je),{predicted_depth:et}=await this.model(Ye),A=[];for(let $e=0;$e<je.length;++$e){const Pe=(0,M.interpolate)(et[$e],je[$e].size.reverse(),"bilinear",!1),se=Pe.mul_(255/(0,h.max)(Pe.data)[0]).to("uint8");A.push({predicted_depth:et[$e],depth:y.RawImage.fromTensor(se)})}return A.length>1?A:A[0]}}const Be=Object.freeze({"text-classification":{tokenizer:o.AutoTokenizer,pipeline:C,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:o.AutoTokenizer,pipeline:w,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:o.AutoTokenizer,pipeline:b,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:z,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:o.AutoTokenizer,pipeline:B,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:N,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:o.AutoTokenizer,pipeline:ae,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Y,model:a.AutoModelForAudioClassification,processor:l.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:o.AutoTokenizer,pipeline:_e,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:o.AutoTokenizer,pipeline:L,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:l.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:o.AutoTokenizer,pipeline:ge,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[l.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:o.AutoTokenizer,pipeline:Se,model:a.AutoModelForVision2Seq,processor:l.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Xe,model:a.AutoModelForImageClassification,processor:l.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:me,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:X,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ie,model:a.AutoModelForObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:o.AutoTokenizer,pipeline:Me,model:a.AutoModelForZeroShotObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:o.AutoTokenizer,pipeline:Q,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:Le,model:a.AutoModelForDepthEstimation,processor:l.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:o.AutoTokenizer,pipeline:ce,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:l.AutoProcessor,pipeline:xe,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 st(Ge,Te=null,{progress_callback:je=null,config:Ye=null,cache_dir:et=null,local_files_only:A=!1,revision:$e="main",device:Pe=null,dtype:se=null,model_file_name:re=null,session_options:ye={}}={}){Ge=We[Ge]??Ge;const R=Be[Ge.split("_",1)[0]];if(!R)throw Error(`Unsupported pipeline: ${Ge}. Must be one of [${Object.keys(Be)}]`);Te||(Te=R.default.model,console.log(`No model specified. Using default model: "${Te}".`));const ee={progress_callback:je,config:Ye,cache_dir:et,local_files_only:A,revision:$e,device:Pe,dtype:se,model_file_name:re,session_options:ye},D=new Map([["tokenizer",R.tokenizer],["model",R.model],["processor",R.processor]]),ue=await pt(D,Te,ee);ue.task=Ge,(0,_.dispatchCallback)(je,{status:"ready",task:Ge,model:Te});const le=R.pipeline;return new le(ue)}async function pt(Ge,Te,je){const Ye=Object.create(null),et=[];for(let[A,$e]of Ge.entries()){if(!$e)continue;let Pe;Array.isArray($e)?Pe=new Promise(async(se,re)=>{var R,ee;let ye;for(let D of $e){if(D===null){se(null);return}try{se(await D.from_pretrained(Te,je));return}catch(ue){if((R=ue.message)!=null&&R.includes("Unsupported model type"))ye=ue;else if((ee=ue.message)!=null&&ee.includes("Could not locate file"))ye=ue;else{re(ue);return}}}re(ye)}):Pe=$e.from_pretrained(Te,je),Ye[A]=Pe,et.push(Pe)}await Promise.all(et);for(let[A,$e]of Object.entries(Ye))Ye[A]=await $e;return Ye}},"./src/processors.js":(e,t,r)=>{r.r(t),r.d(t,{ASTFeatureExtractor:()=>$e,AutoProcessor:()=>Je,BeitFeatureExtractor:()=>Le,BitImageProcessor:()=>I,CLIPFeatureExtractor:()=>z,CLIPImageProcessor:()=>B,ChineseCLIPFeatureExtractor:()=>j,ClapFeatureExtractor:()=>Pe,ConvNextFeatureExtractor:()=>ae,ConvNextImageProcessor:()=>ce,DPTFeatureExtractor:()=>w,DPTImageProcessor:()=>b,DeiTFeatureExtractor:()=>Ke,DetrFeatureExtractor:()=>st,DonutFeatureExtractor:()=>Be,EfficientNetImageProcessor:()=>_e,FeatureExtractor:()=>O,Florence2Processor:()=>dt,GLPNFeatureExtractor:()=>U,ImageFeatureExtractor:()=>S,MobileNetV1FeatureExtractor:()=>L,MobileNetV2FeatureExtractor:()=>Se,MobileNetV3FeatureExtractor:()=>Xe,MobileNetV4FeatureExtractor:()=>me,MobileViTFeatureExtractor:()=>X,MobileViTImageProcessor:()=>ie,NougatImageProcessor:()=>We,OwlViTFeatureExtractor:()=>Me,OwlViTProcessor:()=>Ne,Owlv2ImageProcessor:()=>Q,Processor:()=>R,PyAnnoteFeatureExtractor:()=>se,PyAnnoteProcessor:()=>le,RTDetrImageProcessor:()=>ge,SamImageProcessor:()=>Ge,SamProcessor:()=>ee,SeamlessM4TFeatureExtractor:()=>A,SegformerFeatureExtractor:()=>C,SiglipImageProcessor:()=>N,SpeechT5FeatureExtractor:()=>ye,SpeechT5Processor:()=>ke,Swin2SRImageProcessor:()=>Te,ViTFeatureExtractor:()=>xe,ViTImageProcessor:()=>Y,VitMatteImageProcessor:()=>je,Wav2Vec2FeatureExtractor:()=>et,Wav2Vec2ProcessorWithLM:()=>ue,WeSpeakerFeatureExtractor:()=>re,WhisperFeatureExtractor:()=>Ye,WhisperProcessor:()=>D,YolosFeatureExtractor:()=>pt});var o=r("./src/utils/generic.js"),a=r("./src/utils/core.js"),l=r("./src/utils/hub.js"),p=r("./src/utils/maths.js"),_=r("./src/utils/tensor.js");r("./src/utils/image.js");var h=r("./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 qe=Ve.logits,Qe=Ve.pred_boxes,[tt,ft,ht]=qe.dims;if(ve!==null&&ve.length!==tt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Tt=[];for(let bt=0;bt<tt;++bt){let Et=ve!==null?ve[bt]:null,Lt={boxes:[],classes:[],scores:[]},at=qe[bt],Ot=Qe[bt];for(let Ut=0;Ut<ft;++Ut){let Xt=at[Ut],Yt=[],rr;if(Re){rr=Xt.sigmoid().data;for(let Ht=0;Ht<rr.length;++Ht)rr[Ht]>Z&&Yt.push(Ht)}else{let Ht=(0,p.max)(Xt.data)[1];if(Ht===ht-1||(rr=(0,p.softmax)(Xt.data),rr[Ht]<Z))continue;Yt.push(Ht)}for(const Ht of Yt){let Pr=Ot[Ut].data;Pr=g(Pr),Et!==null&&(Pr=Pr.map((Yr,$r)=>Yr*Et[($r+1)%2])),Lt.boxes.push(Pr),Lt.classes.push(Ht),Lt.scores.push(rr[Ht])}}Tt.push(Lt)}return Tt}function y(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 E(Ve,Z,ve=0,Re=null){const qe=Ve/Z;let Qe=(0,p.bankers_round)(qe)*Z;return Re!==null&&Qe>Re&&(Qe=Math.floor(qe)*Z),Qe<ve&&(Qe=Math.ceil(qe)*Z),Qe}function T([Ve,Z],ve){return[Math.max(Math.floor(Ve/ve),1)*ve,Math.max(Math.floor(Z/ve),1)*ve]}class O extends o.Callable{constructor(Z){super(),this.config=Z}}class S extends O{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 qe=Z.height,Qe=Z.width,tt=ve.height,ft=ve.width;let ht=Math.min(qe,tt),Tt=Math.min(Qe,ft);return ht===qe&&Tt===Qe?Z:(qe>Qe?Tt=Math.floor(Qe*ht/qe):Qe>qe&&(ht=Math.floor(qe*Tt/Qe)),await Z.resize(Tt,ht,{resample:Re}))}async crop_margin(Z,ve=200){const Re=Z.clone().grayscale(),qe=(0,p.min)(Re.data)[0],tt=(0,p.max)(Re.data)[0]-qe;if(tt===0)return Z;const ft=ve/255;let ht=Re.width,Tt=Re.height,bt=0,Et=0;const Lt=Re.data;for(let at=0;at<Re.height;++at){const Ot=at*Re.width;for(let Ut=0;Ut<Re.width;++Ut)(Lt[Ot+Ut]-qe)/tt<ft&&(ht=Math.min(ht,Ut),Tt=Math.min(Tt,at),bt=Math.max(bt,Ut),Et=Math.max(Et,at))}return Z=await Z.crop([ht,Tt,bt,Et]),Z}pad_image(Z,ve,Re,{mode:qe="constant",center:Qe=!1,constant_values:tt=0}={}){const[ft,ht,Tt]=ve;let bt,Et;if(typeof Re=="number"?(bt=Re,Et=Re):(bt=Re.width,Et=Re.height),bt!==ht||Et!==ft){const Lt=new Float32Array(bt*Et*Tt);if(Array.isArray(tt))for(let Ut=0;Ut<Lt.length;++Ut)Lt[Ut]=tt[Ut%Tt];else tt!==0&&Lt.fill(tt);const[at,Ot]=Qe?[Math.floor((bt-ht)/2),Math.floor((Et-ft)/2)]:[0,0];for(let Ut=0;Ut<ft;++Ut){const Xt=(Ut+Ot)*bt,Yt=Ut*ht;for(let rr=0;rr<ht;++rr){const Ht=(Xt+rr+at)*Tt,Pr=(Yt+rr)*Tt;for(let Yr=0;Yr<Tt;++Yr)Lt[Ht+Yr]=Z[Pr+Yr]}}if(qe==="symmetric"){if(Qe)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const Ut=ft-1,Xt=ht-1;for(let Yt=0;Yt<Et;++Yt){const rr=Yt*bt,Ht=(0,a.calculateReflectOffset)(Yt,Ut)*ht;for(let Pr=0;Pr<bt;++Pr){if(Yt<ft&&Pr<ht)continue;const Yr=(rr+Pr)*Tt,$r=(Ht+(0,a.calculateReflectOffset)(Pr,Xt))*Tt;for(let mt=0;mt<Tt;++mt)Lt[Yr+mt]=Z[$r+mt]}}}Z=Lt,ve=[Et,bt,Tt]}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,qe]=Z.size;let Qe,tt;if(this.do_thumbnail){const{height:ft,width:ht}=ve;Qe=Math.min(ft,ht)}else Number.isInteger(ve)?(Qe=ve,tt=this.config.max_size??Qe):ve!==void 0&&(Qe=ve.shortest_edge,tt=ve.longest_edge);if(Qe!==void 0||tt!==void 0){const ft=Qe===void 0?1:Math.max(Qe/Re,Qe/qe),ht=Re*ft,Tt=qe*ft,bt=tt===void 0?1:Math.min(tt/ht,tt/Tt);let Et=Math.floor(Number((ht*bt).toFixed(2))),Lt=Math.floor(Number((Tt*bt).toFixed(2)));return this.size_divisibility!==void 0&&([Et,Lt]=T([Et,Lt],this.size_divisibility)),[Et,Lt]}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 Tt=ht/qe,bt=ft/Re;Math.abs(1-bt)<Math.abs(1-Tt)?Tt=bt:bt=Tt,ht=E(Tt*qe,this.config.ensure_multiple_of),ft=E(bt*Re,this.config.ensure_multiple_of)}return[ft,ht]}else{if(this.size_divisibility!==void 0)return T([Re,qe],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:qe=null,do_convert_grayscale:Qe=null,do_flip_channel_order:tt=null}={}){this.do_crop_margin&&(Z=await this.crop_margin(Z));const[ft,ht]=Z.size;if(qe??this.do_convert_rgb?Z=Z.rgb():Qe&&(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 Tt=[Z.height,Z.width];let bt=Float32Array.from(Z.data),Et=[Z.height,Z.width,Z.channels];if(this.do_rescale&&this.rescale(bt),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<bt.length;Ut+=Z.channels)for(let Xt=0;Xt<Z.channels;++Xt)bt[Ut+Xt]=(bt[Ut+Xt]-at[Xt])/Ot[Xt]}if(Re??this.do_pad){if(this.pad_size)[bt,Et]=this.pad_image(bt,[Z.height,Z.width,Z.channels],this.pad_size);else if(this.size_divisibility){const[at,Ot]=T([Et[1],Et[0]],this.size_divisibility);[bt,Et]=this.pad_image(bt,Et,{width:at,height:Ot})}}if(tt??this.do_flip_channel_order){if(Et[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let at=0;at<bt.length;at+=3){const Ot=bt[at];bt[at]=bt[at+2],bt[at+2]=Ot}}const Lt=new _.Tensor("float32",bt,Et).permute(2,0,1);return{original_size:[ht,ft],reshaped_input_size:Tt,pixel_values:Lt}}async _call(Z,...ve){Array.isArray(Z)||(Z=[Z]);const Re=await Promise.all(Z.map(Qe=>this.preprocess(Qe)));return{pixel_values:(0,_.stack)(Re.map(Qe=>Qe.pixel_values),0),original_sizes:Re.map(Qe=>Qe.original_size),reshaped_input_sizes:Re.map(Qe=>Qe.reshaped_input_size)}}}class C extends S{post_process_semantic_segmentation(Z,ve=null){const Re=Z.logits,qe=Re.dims[0];if(ve!==null&&ve.length!==qe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Qe=[];for(let tt=0;tt<qe;++tt){const ft=ve!==null?ve[tt]:null;let ht=Re[tt];ft!==null&&(ht=(0,_.interpolate)(ht,ft,"bilinear",!1));const[Tt,bt]=ft??ht.dims.slice(-2),Et=new _.Tensor("int32",new Int32Array(Tt*bt),[Tt,bt]),Lt=ht[0].data,at=Et.data;for(let Yt=1;Yt<ht.dims[0];++Yt){const rr=ht[Yt].data;for(let Ht=0;Ht<rr.length;++Ht)rr[Ht]>Lt[Ht]&&(Lt[Ht]=rr[Ht],at[Ht]=Yt)}const Ot=new Array(ht.dims[0]),Ut=Et.data;for(let Yt=0;Yt<Ut.length;++Yt){const rr=Ut[Yt];Ot[rr]=rr}const Xt=Ot.filter(Yt=>Yt!==void 0);Qe.push({segmentation:Et,labels:Xt})}return Qe}}class w extends S{}class b extends w{}class I extends S{}class U extends S{}class z extends S{}class B extends z{}class j extends S{}class N extends S{}class ae 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 qe=Math.floor(ve/this.crop_pct),[Qe,tt]=this.get_resize_output_image_size(Z,{shortest_edge:qe});Z=await Z.resize(Qe,tt,{resample:this.resample}),Z=await Z.center_crop(ve,ve)}else Z=await Z.resize(ve,ve,{resample:this.resample});return Z}}class ce extends ae{}class xe extends S{}class Y extends S{}class _e 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 L extends S{}class Se extends S{}class Xe extends S{}class me extends S{}class X extends S{}class ie extends X{}class Me extends S{post_process_object_detection(...Z){return M(...Z)}}class Q extends Me{}class ge extends S{post_process_object_detection(...Z){return M(...Z)}}class Ke extends S{}class Le extends S{}class Be extends S{pad_image(Z,ve,Re,qe={}){const[Qe,tt,ft]=ve;let ht=this.image_mean;Array.isArray(this.image_mean)||(ht=new Array(ft).fill(ht));let Tt=this.image_std;Array.isArray(Tt)||(Tt=new Array(ft).fill(ht));const bt=ht.map((Et,Lt)=>-Et/Tt[Lt]);return super.pad_image(Z,ve,Re,{center:!0,constant_values:bt,...qe})}}class We extends Be{}class st extends S{async _call(Z){const ve=await super._call(Z),Re=[ve.pixel_values.dims[0],64,64],qe=new _.Tensor("int64",new BigInt64Array(Re.reduce((Qe,tt)=>Qe*tt)).fill(1n),Re);return{...ve,pixel_mask:qe}}post_process_object_detection(...Z){return M(...Z)}remove_low_and_no_objects(Z,ve,Re,qe){let Qe=[],tt=[],ft=[];for(let ht=0;ht<Z.dims[0];++ht){let Tt=Z[ht],bt=ve[ht],Et=(0,p.max)(Tt.data)[1];if(Et===qe)continue;let at=(0,p.softmax)(Tt.data)[Et];at>Re&&(Qe.push(bt),tt.push(at),ft.push(Et))}return[Qe,tt,ft]}check_segment_validity(Z,ve,Re,qe=.5,Qe=.8){let tt=[],ft=0,ht=0;const Tt=ve[Re].data;for(let Et=0;Et<Z.length;++Et)Z[Et]===Re&&(tt.push(Et),++ft),Tt[Et]>=qe&&++ht;let bt=ft>0&&ht>0;return bt&&(bt=ft/ht>Qe),[bt,tt]}compute_segments(Z,ve,Re,qe,Qe,tt=null,ft=null){let[ht,Tt]=ft??Z[0].dims,bt=new _.Tensor("int32",new Int32Array(ht*Tt),[ht,Tt]),Et=[];if(ft!==null)for(let Xt=0;Xt<Z.length;++Xt)Z[Xt]=(0,_.interpolate)(Z[Xt],ft,"bilinear",!1);let Lt=new Int32Array(Z[0].data.length),at=new Float32Array(Z[0].data.length);for(let Xt=0;Xt<Z.length;++Xt){let Yt=ve[Xt];const rr=Z[Xt].data;for(let Ht=0;Ht<rr.length;++Ht)rr[Ht]*=Yt,rr[Ht]>at[Ht]&&(Lt[Ht]=Xt,at[Ht]=rr[Ht])}let Ot=0;const Ut=bt.data;for(let Xt=0;Xt<Re.length;++Xt){let Yt=Re[Xt],[rr,Ht]=this.check_segment_validity(Lt,Z,Xt,qe,Qe);if(rr){++Ot;for(let Pr of Ht)Ut[Pr]=Ot;Et.push({id:Ot,label_id:Yt,score:ve[Xt]})}}return[bt,Et]}post_process_panoptic_segmentation(Z,ve=.5,Re=.5,qe=.8,Qe=null,tt=null){Qe===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),Qe=new Set);const ft=Z.logits,Tt=Z.pred_masks.sigmoid();let[bt,Et,Lt]=ft.dims;if(Lt-=1,tt!==null&&tt.length!==bt)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<bt;++Ot){let Ut=tt!==null?tt[Ot]:null,Xt=ft[Ot],Yt=Tt[Ot],[rr,Ht,Pr]=this.remove_low_and_no_objects(Xt,Yt,ve,Lt);if(Pr.length===0){let[mt,$t]=Ut??Yt.dims.slice(-2),Bt=new _.Tensor("int32",new Int32Array(mt*$t).fill(-1),[mt,$t]);at.push({segmentation:Bt,segments_info:[]});continue}let[Yr,$r]=this.compute_segments(rr,Ht,Pr,Re,qe,Qe,Ut);at.push({segmentation:Yr,segments_info:$r})}return at}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class pt extends S{post_process_object_detection(...Z){return M(...Z)}}class Ge extends S{reshape_input_points(Z,ve,Re,qe=!1){Z=structuredClone(Z);let Qe=(0,a.calculateDimensions)(Z);if(Qe.length===3)qe||(Qe=[1,...Qe]),Z=[Z];else if(Qe.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 tt=0;tt<Z.length;++tt){let ft=ve[tt],ht=Re[tt],Tt=[ht[0]/ft[0],ht[1]/ft[1]];for(let bt=0;bt<Z[tt].length;++bt)for(let Et=0;Et<Z[tt][bt].length;++Et)for(let Lt=0;Lt<Z[tt][bt][Et].length;++Lt)Z[tt][bt][Et][Lt]*=Tt[Lt%2]}return new _.Tensor("float32",Float32Array.from(Z.flat(1/0)),Qe)}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((qe,Qe)=>qe!==ve.dims[Qe]))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:qe=null}={}){const Qe=await super._call(Z);if(ve&&(Qe.input_points=this.reshape_input_points(ve,Qe.original_sizes,Qe.reshaped_input_sizes)),Re){if(!Qe.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Qe.input_labels=this.add_input_labels(Re,Qe.input_points)}return qe&&(Qe.input_boxes=this.reshape_input_points(qe,Qe.original_sizes,Qe.reshaped_input_sizes,!0)),Qe}async post_process_masks(Z,ve,Re,{mask_threshold:qe=0,binarize:Qe=!0,pad_size:tt=null}={}){const ft=[];tt=tt??this.pad_size;const ht=[tt.height,tt.width];for(let Tt=0;Tt<ve.length;++Tt){const bt=ve[Tt],Et=Re[Tt];let Lt=await(0,_.interpolate_4d)(Z[Tt],{mode:"bilinear",size:ht});if(Lt=Lt.slice(null,null,[0,Et[0]],[0,Et[1]]),Lt=await(0,_.interpolate_4d)(Lt,{mode:"bilinear",size:bt}),Qe){const at=Lt.data,Ot=new Uint8Array(at.length);for(let Ut=0;Ut<at.length;++Ut)at[Ut]>qe&&(Ot[Ut]=1);Lt=new _.Tensor("bool",Ot,Lt.dims)}ft.push(Lt)}return ft}generate_crop_boxes(Z,ve,{crop_n_layers:Re=0,overlap_ratio:qe=512/1500,points_per_crop:Qe=32,crop_n_points_downscale_factor:tt=1}={}){}}class Te extends S{pad_image(Z,ve,Re,qe={}){const[Qe,tt,ft]=ve;return super.pad_image(Z,ve,{width:tt+(Re-tt%Re)%Re,height:Qe+(Re-Qe%Re)%Re},{mode:"symmetric",center:!1,constant_values:-1,...qe})}}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(tt=>this.preprocess(tt))),qe=await Promise.all(ve.map(tt=>this.preprocess(tt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,_.stack)(Re.map((tt,ft)=>(0,_.cat)([tt.pixel_values,qe[ft].pixel_values],0)),0),original_sizes:Re.map(tt=>tt.original_size),reshaped_input_sizes:Re.map(tt=>tt.reshaped_input_size)}}}class Ye extends O{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,qe=(0,p.max)(Re)[0];for(let Qe=0;Qe<Re.length;++Qe)Re[Qe]=(Math.max(Re[Qe],qe-8)+4)/4;return ve}async _call(Z){y(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 et extends O{_zero_mean_unit_var_norm(Z){const Re=Z.reduce((Qe,tt)=>Qe+tt,0)/Z.length,qe=Z.reduce((Qe,tt)=>Qe+(tt-Re)**2,0)/Z.length;return Z.map(Qe=>(Qe-Re)/Math.sqrt(qe+1e-7))}async _call(Z){y(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 O{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 qe=0;qe<Re.length;++qe)Re[qe].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:qe=!0,return_attention_mask:Qe=!0}={}){y(Z,"SeamlessM4TFeatureExtractor");let tt=await this._extract_fbank_features(Z,this.config.max_length);if(qe){const[Ot,Ut]=tt.dims,Xt=tt.data;for(let Yt=0;Yt<Ut;++Yt){let rr=0;for(let $r=0;$r<Ot;++$r)rr+=Xt[$r*Ut+Yt];const Ht=rr/Ot;let Pr=0;for(let $r=0;$r<Ot;++$r)Pr+=(Xt[$r*Ut+Yt]-Ht)**2;Pr/=Ot-1;const Yr=Math.sqrt(Pr+1e-7);for(let $r=0;$r<Ot;++$r){const mt=$r*Ut+Yt;Xt[mt]=(Xt[mt]-Ht)/Yr}}}let ft;if(ve){const[Ot,Ut]=tt.dims,Xt=tt.data,Yt=Ot%Re;if(Yt>0){const rr=new Float32Array(Ut*(Ot+Yt));rr.set(Xt),rr.fill(this.config.padding_value,Xt.length);const Ht=Ot+Yt;tt=new _.Tensor(tt.type,rr,[Ht,Ut]),Qe&&(ft=new _.Tensor("int64",new BigInt64Array(Ht),[1,Ht]),ft.data.fill(1n,0,Ot))}}const[ht,Tt]=tt.dims,bt=this.config.stride;if(ht%bt!==0)throw new Error(`The number of frames (${ht}) must be a multiple of the stride (${bt}).`);const Lt=tt.view(1,Math.floor(ht/bt),Tt*bt),at={input_features:Lt};if(Qe){const Ot=Lt.dims[1],Ut=new BigInt64Array(Ot);if(ft){const Xt=ft.data;for(let Yt=1,rr=0;Yt<ht;Yt+=bt,++rr)Ut[rr]=Xt[Yt]}else Ut.fill(1n);at.attention_mask=new _.Tensor("int64",Ut,[1,Ot])}return at}}class $e extends O{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 qe=0;qe<Re.length;++qe)Re[qe].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){y(Z,"ASTFeatureExtractor");const ve=await this._extract_fbank_features(Z,this.config.max_length);if(this.config.do_normalize){const Re=this.std*2,qe=ve.data;for(let Qe=0;Qe<qe.length;++Qe)qe[Qe]=(qe[Qe]-this.mean)/Re}return{input_values:ve.unsqueeze_(0)}}}class Pe extends O{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,qe){let Qe;const tt=Z.length-ve;if(tt>0)if(Re==="rand_trunc"){const ft=Math.floor(Math.random()*(tt+1));Z=Z.subarray(ft,ft+ve),Qe=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(tt<0){let ft=new Float64Array(ve);if(ft.set(Z),qe==="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(qe==="repeatpad")for(let ht=Z.length;ht<-tt;ht+=Z.length)ft.set(Z,ht);Z=ft}if(Re==="fusion")throw new Error(`Truncation strategy "${Re}" not implemented`);Qe=await this._extract_fbank_features(Z,this.mel_filters_slaney,this.config.nb_max_samples)}return Qe.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 y(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 O{async _call(Z){y(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,qe=[];for(const Qe of Z.tolist()){const tt=[];let ft=-1;for(let ht=0;ht<Qe.length;++ht){const Tt=(0,p.softmax)(Qe[ht]),[bt,Et]=(0,p.max)(Tt),[Lt,at]=[ht,ht+1];Et!==ft?(ft=Et,tt.push({id:Et,start:Lt,end:at,score:bt})):(tt.at(-1).end=at,tt.at(-1).score+=bt)}qe.push(tt.map(({id:ht,start:Tt,end:bt,score:Et})=>({id:ht,start:Tt*Re,end:bt*Re,confidence:Et/(bt-Tt)})))}return qe}}class re extends O{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 qe=0;qe<Re.length;++qe)Re[qe].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){y(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,qe=ve.data,[Qe,tt,ft]=ve.dims;for(let ht=0;ht<Qe;++ht){const Tt=ht*tt*ft,bt=ht*ft;for(let Et=0;Et<tt;++Et){const Lt=Tt+Et*ft;for(let at=0;at<ft;++at)qe[Lt+at]-=Re[bt+at]}}}return{input_features:ve}}}class ye extends O{}class R extends o.Callable{constructor(Z){super(),this.feature_extractor=Z}async _call(Z,...ve){return await this.feature_extractor(Z,...ve)}}class ee extends R{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 D extends R{async _call(Z){return await this.feature_extractor(Z)}}class ue extends R{async _call(Z){return await this.feature_extractor(Z)}}class le extends R{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 R{async _call(Z){return await this.feature_extractor(Z)}}class Ne extends R{}class dt extends R{constructor(Z){super(Z);const{tasks_answer_post_processing_type:ve,task_prompts_without_inputs:Re,task_prompts_with_input:qe}=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(qe??{})),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[qe,Qe]of this.task_prompts_with_input)if(Re.includes(qe)){ve.push(Qe.replaceAll("{input}",Re).replaceAll(qe,""));break}ve.length!==Z.length&&ve.push(Re)}return ve}post_process_generation(Z,ve,Re){const qe=this.tasks_answer_post_processing_type.get(ve)??"pure_text";Z=Z.replaceAll("<s>","").replaceAll("</s>","");let Qe;switch(qe){case"pure_text":Qe=Z;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const tt=qe==="ocr"?"quad_boxes":"bboxes",ft=Z.matchAll(this.regexes[tt]),ht=[],Tt=[];for(const[bt,Et,...Lt]of ft)ht.push(Et?Et.trim():ht.at(-1)??""),Tt.push(Lt.map((at,Ot)=>(Number(at)+.5)/this.size_per_bin*Re[Ot%2]));Qe={labels:ht,[tt]:Tt};break;default:throw new Error(`Task "${ve}" (of type "${qe}") not yet implemented.`)}return{[ve]:Qe}}}class Je{static async from_pretrained(Z,{progress_callback:ve=null,config:Re=null,cache_dir:qe=null,local_files_only:Qe=!1,revision:tt="main"}={}){let ft=Re??await(0,l.getModelJSON)(Z,"preprocessor_config.json",!0,{progress_callback:ve,config:Re,cache_dir:qe,local_files_only:Qe,revision:tt}),ht=ft.feature_extractor_type??ft.image_processor_type,Tt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ht];if(!Tt)if(ft.size!==void 0)console.warn(`Feature extractor type "${ht}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Tt=S;else throw new Error(`Unknown Feature Extractor type: ${ht}`);let bt=this.PROCESSOR_CLASS_MAPPING[ft.processor_class]??R,Et=new Tt(ft);return new bt(Et)}}He(Je,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:S,WhisperFeatureExtractor:Ye,ViTFeatureExtractor:xe,MobileViTFeatureExtractor:X,MobileViTImageProcessor:ie,MobileNetV1FeatureExtractor:L,MobileNetV2FeatureExtractor:Se,MobileNetV3FeatureExtractor:Xe,MobileNetV4FeatureExtractor:me,OwlViTFeatureExtractor:Me,Owlv2ImageProcessor:Q,CLIPFeatureExtractor:z,CLIPImageProcessor:B,Florence2Processor:dt,ChineseCLIPFeatureExtractor:j,SiglipImageProcessor:N,ConvNextFeatureExtractor:ae,ConvNextImageProcessor:ce,SegformerFeatureExtractor:C,BitImageProcessor:I,DPTImageProcessor:b,DPTFeatureExtractor:w,GLPNFeatureExtractor:U,BeitFeatureExtractor:Le,DeiTFeatureExtractor:Ke,DetrFeatureExtractor:st,RTDetrImageProcessor:ge,YolosFeatureExtractor:pt,DonutFeatureExtractor:Be,NougatImageProcessor:We,EfficientNetImageProcessor:_e,ViTImageProcessor:Y,VitMatteImageProcessor:je,SamImageProcessor:Ge,Swin2SRImageProcessor:Te,Wav2Vec2FeatureExtractor:et,SeamlessM4TFeatureExtractor:A,SpeechT5FeatureExtractor:ye,ASTFeatureExtractor:$e,ClapFeatureExtractor:Pe,PyAnnoteFeatureExtractor:se,WeSpeakerFeatureExtractor:re}),He(Je,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:D,Wav2Vec2ProcessorWithLM:ue,PyAnnoteProcessor:le,SamProcessor:ee,SpeechT5Processor:ke,OwlViTProcessor:Ne,Florence2Processor:dt})},"./src/tokenizers.js":(e,t,r)=>{r.r(t),r.d(t,{AlbertTokenizer:()=>Ut,AutoTokenizer:()=>jn,BartTokenizer:()=>Gr,BertTokenizer:()=>Ot,BlenderbotSmallTokenizer:()=>Vo,BlenderbotTokenizer:()=>go,BloomTokenizer:()=>Dr,CLIPTokenizer:()=>Zt,CamembertTokenizer:()=>$t,CodeGenTokenizer:()=>mo,CodeLlamaTokenizer:()=>Cs,CohereTokenizer:()=>Vr,ConvBertTokenizer:()=>Yr,DebertaTokenizer:()=>rr,DebertaV2Tokenizer:()=>Ht,DistilBertTokenizer:()=>mt,ElectraTokenizer:()=>un,EsmTokenizer:()=>ji,FalconTokenizer:()=>Bo,GPT2Tokenizer:()=>Mi,GPTNeoXTokenizer:()=>No,GemmaTokenizer:()=>fo,Grok1Tokenizer:()=>fi,HerbertTokenizer:()=>Pr,LlamaTokenizer:()=>Ti,M2M100Tokenizer:()=>Ji,MBart50Tokenizer:()=>Kr,MBartTokenizer:()=>wn,MPNetTokenizer:()=>Ro,MarianTokenizer:()=>jo,MobileBertTokenizer:()=>Xt,NllbTokenizer:()=>Si,NougatTokenizer:()=>_o,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ps,RoFormerTokenizer:()=>$r,RobertaTokenizer:()=>pi,SiglipTokenizer:()=>eo,SpeechT5Tokenizer:()=>Wo,SqueezeBertTokenizer:()=>Yt,T5Tokenizer:()=>Bi,TokenizerModel:()=>xe,VitsTokenizer:()=>Go,Wav2Vec2CTCTokenizer:()=>Uo,WhisperTokenizer:()=>ho,XLMRobertaTokenizer:()=>Lo,XLMTokenizer:()=>Bt,is_chinese_char:()=>U});var o=r("./src/utils/generic.js"),a=r("./src/utils/core.js"),l=r("./src/utils/hub.js"),p=r("./src/utils/maths.js"),_=r("./src/utils/tensor.js"),h=r("./src/utils/data-structures.js"),g=r("./node_modules/@huggingface/jinja/dist/index.js"),M=r("./src/models/whisper/common_whisper.js"),y=r("./src/utils/constants.js");async function E(Ue,W){const pe=await Promise.all([(0,l.getModelJSON)(Ue,"tokenizer.json",!0,W),(0,l.getModelJSON)(Ue,"tokenizer_config.json",!0,W)]);return W.legacy!==null&&(pe[1].legacy=W.legacy),pe}function T(Ue,W){const pe=[];let Ce=0;for(const Fe of Ue.matchAll(W)){const Oe=Fe[0];Ce<Fe.index&&pe.push(Ue.slice(Ce,Fe.index)),Oe.length>0&&pe.push(Oe),Ce=Fe.index+Oe.length}return Ce<Ue.length&&pe.push(Ue.slice(Ce)),pe}function O(Ue,W=!0){if(Ue.Regex!==void 0){let pe=Ue.Regex.replace(/\\([#&~])/g,"$1");for(const[Ce,Fe]of ae)pe=pe.replaceAll(Ce,Fe);return new RegExp(pe,"gu")}else if(Ue.String!==void 0){const pe=(0,a.escapeRegExp)(Ue.String);return new RegExp(W?pe:`(${pe})`,"gu")}else return console.warn("Unknown pattern type:",Ue),null}function S(Ue){return new Map(Object.entries(Ue))}function C(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 w(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 b(Ue){return Ue.replace(/[\u0300-\u036f]/g,"")}function I(Ue){return b(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 z(Ue,W,pe){const Ce=[];let Fe=0;for(;Fe<Ue.length;){if(Ce.push(Ue[Fe]),(pe.get(Ue[Fe])??W)!==W){++Fe;continue}for(;Fe<Ue.length&&(pe.get(Ue[Fe])??W)===W;)++Fe}return Ce}function B(Ue){return Ue.match(/\S+/g)||[]}const j="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",N=new RegExp(`^[${j}]+$`,"gu"),ae=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"]]);class ce{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 xe 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,...pe){switch(W.type){case"WordPiece":return new Y(W);case"Unigram":return new _e(W,...pe);case"BPE":return new Xe(W);default:if(W.vocab)return new me(W,...pe);throw new Error(`Unknown TokenizerModel type: ${W.type}`)}}_call(W){let pe=this.encode(W);return this.fuse_unk&&(pe=z(pe,this.unk_token_id,this.tokens_to_ids)),pe}encode(W){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(W){return W.map(pe=>this.tokens_to_ids.get(pe)??this.unk_token_id)}convert_ids_to_tokens(W){return W.map(pe=>this.vocab[pe]??this.unk_token)}}class Y extends xe{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[pe,Ce]of this.tokens_to_ids)this.vocab[Ce]=pe}encode(W){const pe=[];for(const Ce of W){const Fe=[...Ce];if(Fe.length>this.max_input_chars_per_word){pe.push(this.unk_token);continue}let Oe=!1,rt=0;const Mt=[];for(;rt<Fe.length;){let St=Fe.length,kt=null;for(;rt<St;){let It=Fe.slice(rt,St).join("");if(rt>0&&(It=this.config.continuing_subword_prefix+It),this.tokens_to_ids.has(It)){kt=It;break}--St}if(kt===null){Oe=!0;break}Mt.push(kt),rt=St}Oe?pe.push(this.unk_token):pe.push(...Mt)}return pe}}class _e extends xe{constructor(W,pe){super(W);const Ce=W.vocab.length;this.vocab=new Array(Ce),this.scores=new Array(Ce);for(let Fe=0;Fe<Ce;++Fe){const Oe=W.vocab[Fe];this.vocab[Fe]=Oe[0],this.scores[Fe]=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((Fe,Oe)=>[Fe,Oe])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=pe.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,p.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 pe=W.sentence,Ce=pe.length;let Fe=0;for(;Fe<Ce;){let rt=!1;for(let Mt of this.trie.commonPrefixSearch(pe.slice(Fe))){const St=this.tokens_to_ids.get(Mt),kt=this.scores[St],It=Mt.length;W.insert(Fe,It,kt,St),!rt&&It===1&&(rt=!0)}rt||W.insert(Fe,1,this.unkScore,this.unk_token_id),Fe+=1}}tokenize(W){const pe=new h.TokenLattice(W,this.bosTokenId,this.eosTokenId);return this.populateNodes(pe),pe.tokens()}encode(W){const pe=[];for(const Ce of W){const Fe=this.tokenize(Ce);pe.push(...Fe)}return pe}}const L=(()=>{const Ue=[...Array.from({length:94},(Fe,Oe)=>Oe+33),...Array.from({length:12},(Fe,Oe)=>Oe+161),...Array.from({length:82},(Fe,Oe)=>Oe+174)],W=Ue.slice();let pe=0;for(let Fe=0;Fe<256;++Fe)Ue.includes(Fe)||(Ue.push(Fe),W.push(256+pe),pe+=1);const Ce=W.map(Fe=>String.fromCharCode(Fe));return Object.fromEntries(Ue.map((Fe,Oe)=>[Fe,Ce[Oe]]))})(),Se=(0,a.reverseDictionary)(L);class Xe extends xe{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[pe,Ce]of this.tokens_to_ids)this.vocab[Ce]=pe;this.bpe_ranks=new Map(W.merges.map((pe,Ce)=>[pe,Ce])),this.merges=W.merges.map(pe=>pe.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 pe=this.cache.get(W);if(pe!==void 0)return pe;const Ce=Array.from(W);this.end_of_word_suffix&&(Ce[Ce.length-1]+=this.end_of_word_suffix);let Fe=[];if(Ce.length>1){const Oe=new h.PriorityQueue((St,kt)=>St.score<kt.score);let rt={token:Ce[0],bias:0,prev:null,next:null},Mt=rt;for(let St=1;St<Ce.length;++St){const kt={bias:St/Ce.length,token:Ce[St],prev:Mt,next:null};Mt.next=kt,this._add_node(Oe,Mt),Mt=kt}for(;!Oe.isEmpty();){const St=Oe.pop();if(St.deleted||!St.next||St.next.deleted)continue;if(St.deleted=!0,St.next.deleted=!0,St.prev){const It={...St.prev};St.prev.deleted=!0,St.prev=It,It.prev?It.prev.next=It:rt=It}const kt={token:St.token+St.next.token,bias:St.bias,prev:St.prev,next:St.next.next};kt.prev?(kt.prev.next=kt,this._add_node(Oe,kt.prev)):rt=kt,kt.next&&(kt.next.prev=kt,this._add_node(Oe,kt))}for(let St=rt;St!==null;St=St.next)Fe.push(St.token)}else Fe=Ce;if(this.continuing_subword_suffix)for(let Oe=0;Oe<Fe.length-1;++Oe)Fe[Oe]+=this.continuing_subword_suffix;return this.cache.set(W,Fe),Fe}_add_node(W,pe){const Ce=this.bpe_ranks.get(pe.token+this.BPE_SPLIT_TOKEN+pe.next.token);Ce!==void 0&&(pe.score=Ce+pe.bias,W.push(pe))}encode(W){const pe=[];for(const Ce of W){if(this.ignore_merges&&this.tokens_to_ids.has(Ce)){pe.push(Ce);continue}const Fe=this.bpe(Ce);for(const Oe of Fe)this.tokens_to_ids.has(Oe)?pe.push(Oe):this.byte_fallback?pe.push(...Array.from(this.text_encoder.encode(Oe)).map(rt=>`<0x${rt.toString(16).toUpperCase().padStart(2,"0")}>`)):pe.push(this.unk_token)}return pe}}class me extends xe{constructor(W,pe){super(W),this.tokens_to_ids=S(pe.target_lang?W.vocab[pe.target_lang]:W.vocab),this.bos_token=pe.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=pe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=pe.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=pe.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[Ce,Fe]of this.tokens_to_ids)this.vocab[Fe]=Ce}encode(W){return W}}class X extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"BertNormalizer":return new pt(W);case"Precompiled":return new Qe(W);case"Sequence":return new st(W);case"Replace":return new ie(W);case"NFC":return new Me(W);case"NFKC":return new Q(W);case"NFKD":return new ge(W);case"Strip":return new Ke(W);case"StripAccents":return new Le(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 ie extends X{normalize(W){const pe=O(this.config.pattern);return pe===null?W:W.replaceAll(pe,this.config.content)}}class Me extends X{normalize(W){return W=W.normalize("NFC"),W}}class Q extends X{normalize(W){return W=W.normalize("NFKC"),W}}class ge extends X{normalize(W){return W=W.normalize("NFKD"),W}}class Ke extends X{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 Le extends X{normalize(W){return W=b(W),W}}class Be extends X{normalize(W){return W=W.toLowerCase(),W}}class We extends X{normalize(W){return W=this.config.prepend+W,W}}class st extends X{constructor(W){super(W),this.normalizers=W.normalizers.map(pe=>X.fromConfig(pe))}normalize(W){return this.normalizers.reduce((pe,Ce)=>Ce.normalize(pe),W)}}class pt extends X{_tokenize_chinese_chars(W){const pe=[];for(let Ce=0;Ce<W.length;++Ce){const Fe=W[Ce],Oe=Fe.charCodeAt(0);U(Oe)?(pe.push(" "),pe.push(Fe),pe.push(" ")):pe.push(Fe)}return pe.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 pe=[];for(const Ce of W){const Fe=Ce.charCodeAt(0);Fe===0||Fe===65533||this._is_control(Ce)||(/^\s$/.test(Ce)?pe.push(" "):pe.push(Ce))}return pe.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 tt(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 et(W);case"Digits":return new A(W);case"Replace":return new Tt(W);default:throw new Error(`Unknown PreTokenizer type: ${W.type}`)}}pre_tokenize_text(W,pe){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(W,pe){return(Array.isArray(W)?W.map(Ce=>this.pre_tokenize_text(Ce,pe)):this.pre_tokenize_text(W,pe)).flat()}_call(W,pe){return this.pre_tokenize(W,pe)}}class Te extends Ge{constructor(W){super(),this.pattern=new RegExp(`[^\\s${j}]+|[${j}]`,"gu")}pre_tokenize_text(W,pe){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=L,this.text_encoder=new TextEncoder}pre_tokenize_text(W,pe){return this.add_prefix_space&&!W.startsWith(" ")&&(W=" "+W),(this.use_regex?W.match(this.pattern)||[]:[W]).map(Fe=>Array.from(this.text_encoder.encode(Fe),Oe=>this.byte_encoder[Oe]).join(""))}}class Ye extends Ge{constructor(W){super(),this.config=W,this.pattern=O(this.config.pattern,this.config.invert)}pre_tokenize_text(W,pe){return this.pattern===null?[]:this.config.invert?W.match(this.pattern)||[]:T(W,this.pattern)}}class et extends Ge{constructor(W){super(),this.config=W,this.pattern=new RegExp(`[^${j}]+|[${j}]+`,"gu")}pre_tokenize_text(W,pe){return W.match(this.pattern)||[]}}class A extends Ge{constructor(W){super(),this.config=W;const pe=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(pe,"gu")}pre_tokenize_text(W,pe){return W.match(this.pattern)||[]}}class $e extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"TemplateProcessing":return new re(W);case"ByteLevel":return new ye(W);case"RobertaProcessing":return new se(W);case"BertProcessing":return new Pe(W);case"Sequence":return new R(W);default:throw new Error(`Unknown PostProcessor type: ${W.type}`)}}post_process(W,...pe){throw Error("post_process should be implemented in subclass.")}_call(W,...pe){return this.post_process(W,...pe)}}class Pe extends $e{constructor(W){super(W),this.cls=W.cls[0],this.sep=W.sep[0]}post_process(W,pe=null,{add_special_tokens:Ce=!0}={}){Ce&&(W=(0,a.mergeArrays)([this.cls],W,[this.sep]));let Fe=new Array(W.length).fill(0);if(pe!==null){const Oe=Ce&&this instanceof se?[this.sep]:[],rt=Ce?[this.sep]:[];W=(0,a.mergeArrays)(W,Oe,pe,rt),Fe=(0,a.mergeArrays)(Fe,new Array(pe.length+Oe.length+rt.length).fill(1))}return{tokens:W,token_type_ids:Fe}}}class se extends Pe{}class re extends $e{constructor(W){super(W),this.single=W.single,this.pair=W.pair}post_process(W,pe=null,{add_special_tokens:Ce=!0}={}){const Fe=pe===null?this.single:this.pair;let Oe=[],rt=[];for(const Mt of Fe)"SpecialToken"in Mt?Ce&&(Oe.push(Mt.SpecialToken.id),rt.push(Mt.SpecialToken.type_id)):"Sequence"in Mt&&(Mt.Sequence.id==="A"?(Oe=(0,a.mergeArrays)(Oe,W),rt=(0,a.mergeArrays)(rt,new Array(W.length).fill(Mt.Sequence.type_id))):Mt.Sequence.id==="B"&&(Oe=(0,a.mergeArrays)(Oe,pe),rt=(0,a.mergeArrays)(rt,new Array(pe.length).fill(Mt.Sequence.type_id))));return{tokens:Oe,token_type_ids:rt}}}class ye extends $e{post_process(W,pe=null){return pe&&(W=(0,a.mergeArrays)(W,pe)),{tokens:W}}}class R extends $e{constructor(W){super(W),this.processors=W.processors.map(pe=>$e.fromConfig(pe))}post_process(W,pe=null,Ce={}){let Fe;for(const Oe of this.processors)if(Oe instanceof ye)W=Oe.post_process(W).tokens,pe&&(pe=Oe.post_process(pe).tokens);else{const rt=Oe.post_process(W,pe,Ce);W=rt.tokens,Fe=rt.token_type_ids}return{tokens:W,token_type_ids:Fe}}}class ee 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 qe(W);case"ByteLevel":return new dt(W);case"Replace":return new D(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 D extends ee{decode_chain(W){const pe=O(this.config.pattern);return pe===null?W:W.map(Ce=>Ce.replaceAll(pe,this.config.content))}}class ue extends ee{constructor(W){super(W),this.text_decoder=new TextDecoder}decode_chain(W){const pe=[];let Ce=[];for(const Fe of W){let Oe=null;if(Fe.length===6&&Fe.startsWith("<0x")&&Fe.endsWith(">")){const rt=parseInt(Fe.slice(3,5),16);isNaN(rt)||(Oe=rt)}if(Oe!==null)Ce.push(Oe);else{if(Ce.length>0){const rt=this.text_decoder.decode(Uint8Array.from(Ce));pe.push(rt),Ce=[]}pe.push(Fe)}}if(Ce.length>0){const Fe=this.text_decoder.decode(Uint8Array.from(Ce));pe.push(Fe),Ce=[]}return pe}}class le extends ee{decode_chain(W){return[W.join("")]}}class ke extends ee{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(pe=>{let Ce=0;for(let Oe=0;Oe<this.start&&pe[Oe]===this.content;++Oe){Ce=Oe+1;continue}let Fe=pe.length;for(let Oe=0;Oe<this.stop;++Oe){const rt=pe.length-Oe-1;if(pe[rt]===this.content){Fe=rt;continue}else break}return pe.slice(Ce,Fe)})}}class Ne extends ee{constructor(W){super(W),this.cleanup=W.cleanup}decode_chain(W){return W.map((pe,Ce)=>(Ce!==0&&(pe.startsWith(this.config.prefix)?pe=pe.replace(this.config.prefix,""):pe=" "+pe),this.cleanup&&(pe=w(pe)),pe))}}class dt extends ee{constructor(W){super(W),this.byte_decoder=Se,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(W){const pe=W.join(""),Ce=new Uint8Array([...pe].map(Oe=>this.byte_decoder[Oe]));return this.text_decoder.decode(Ce)}decode_chain(W){const pe=[];let Ce=[];for(const Fe of W)this.added_tokens.find(Oe=>Oe.content===Fe)!==void 0?(Ce.length>0&&(pe.push(this.convert_tokens_to_string(Ce)),Ce=[]),pe.push(Fe)):Ce.push(Fe);return Ce.length>0&&pe.push(this.convert_tokens_to_string(Ce)),pe}}class Je extends ee{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 pe=[W[0]];for(let Oe=1;Oe<W.length;++Oe)W[Oe]!==pe.at(-1)&&pe.push(W[Oe]);let Fe=pe.filter(Oe=>Oe!==this.pad_token).join("");return this.cleanup&&(Fe=w(Fe).replaceAll(this.word_delimiter_token," ").trim()),Fe}decode_chain(W){return[this.convert_tokens_to_string(W)]}}class Ve extends ee{constructor(W){super(W),this.decoders=W.decoders.map(pe=>ee.fromConfig(pe))}decode_chain(W){return this.decoders.reduce((pe,Ce)=>Ce.decode_chain(pe),W)}}class Z extends ee{constructor(W){super(W),this.suffix=this.config.suffix}decode_chain(W){return W.map((pe,Ce)=>pe.replaceAll(this.suffix,Ce===W.length-1?"":" "))}}class ve extends ee{decode_chain(W){let pe="";for(let Ce=1;Ce<W.length;Ce+=2)pe+=W[Ce];return[pe]}}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:pe=void 0}={}){let Ce=W.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Ce.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&pe===0)&&(Ce=this.strRep+Ce),[Ce]}}class qe extends ee{constructor(W){super(W),this.addPrefixSpace=W.add_prefix_space,this.replacement=W.replacement}decode_chain(W){const pe=[];for(let Ce=0;Ce<W.length;++Ce){let Fe=W[Ce].replaceAll(this.replacement," ");this.addPrefixSpace&&Ce==0&&Fe.startsWith(" ")&&(Fe=Fe.substring(1)),pe.push(Fe)}return pe}}class Qe extends X{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(Ce=>Ce.normalize("NFKC")).join("~"):W=W.normalize("NFKC"),W}}class tt extends Ge{constructor(W){super(),this.tokenizers=W.pretokenizers.map(pe=>Ge.fromConfig(pe))}pre_tokenize_text(W,pe){return this.tokenizers.reduce((Ce,Fe)=>Fe.pre_tokenize(Ce,pe),[W])}}class ft extends Ge{constructor(W){super()}pre_tokenize_text(W,pe){return W.match(/\w+|[^\w\s]+/g)||[]}}class ht extends Ge{constructor(W){super()}pre_tokenize_text(W,pe){return B(W)}}class Tt extends Ge{constructor(W){super(),this.config=W,this.pattern=O(this.config.pattern),this.content=this.config.content}pre_tokenize_text(W,pe){return this.pattern===null?[W]:[W.replaceAll(this.pattern,this.config.content)]}}const bt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Et(Ue,W,pe,Ce){for(const Fe of Object.keys(Ue)){const Oe=W-Ue[Fe].length,rt=pe(Fe),Mt=new Array(Oe).fill(rt);Ue[Fe]=Ce==="right"?(0,a.mergeArrays)(Ue[Fe],Mt):(0,a.mergeArrays)(Mt,Ue[Fe])}}function Lt(Ue,W){for(const pe of Object.keys(Ue))Ue[pe].length=W}class at extends o.Callable{constructor(pe,Ce){super();He(this,"return_token_type_ids",!1);He(this,"padding_side","right");this._tokenizer_config=Ce,this.normalizer=X.fromConfig(pe.normalizer),this.pre_tokenizer=Ge.fromConfig(pe.pre_tokenizer),this.model=xe.fromConfig(pe.model,Ce),this.post_processor=$e.fromConfig(pe.post_processor),this.decoder=ee.fromConfig(pe.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Fe of pe.added_tokens){const Oe=new ce(Fe);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=Ce.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((Fe,Oe)=>Oe.content.length-Fe.content.length).map(Fe=>`${Fe.lstrip?"\\s*":""}(${(0,a.escapeRegExp)(Fe.content)})${Fe.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=Ce.model_max_length,this.remove_space=Ce.remove_space,this.clean_up_tokenization_spaces=Ce.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Ce.do_lowercase_and_remove_accent??!1,Ce.padding_side&&(this.padding_side=Ce.padding_side),this.legacy=!1,this.chat_template=Ce.chat_template??null,Array.isArray(this.chat_template)){const Fe=Object.create(null);for(const{name:Oe,template:rt}of this.chat_template){if(typeof Oe!="string"||typeof rt!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Fe[Oe]=rt}this.chat_template=Fe}this._compiled_template_cache=new Map}getToken(...pe){for(const Ce of pe){const Fe=this._tokenizer_config[Ce];if(Fe)if(typeof Fe=="object"){if(Fe.__type==="AddedToken")return Fe.content;throw Error(`Unknown token: ${Fe}`)}else return Fe}return null}static async from_pretrained(pe,{progress_callback:Ce=null,config:Fe=null,cache_dir:Oe=null,local_files_only:rt=!1,revision:Mt="main",legacy:St=null}={}){const kt=await E(pe,{progress_callback:Ce,config:Fe,cache_dir:Oe,local_files_only:rt,revision:Mt,legacy:St});return new this(...kt)}_call(pe,{text_pair:Ce=null,add_special_tokens:Fe=!0,padding:Oe=!1,truncation:rt=null,max_length:Mt=null,return_tensor:St=!0,return_token_type_ids:kt=null}={}){const It=Array.isArray(pe);let tr;if(It){if(pe.length===0)throw Error("text array must be non-empty");if(Ce!==null){if(Array.isArray(Ce)){if(pe.length!==Ce.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");tr=pe.map((or,qt)=>this._encode_plus(or,{text_pair:Ce[qt],add_special_tokens:Fe,return_token_type_ids:kt}))}else tr=pe.map(or=>this._encode_plus(or,{add_special_tokens:Fe,return_token_type_ids:kt}))}else{if(pe==null)throw Error("text may not be null or undefined");if(Array.isArray(Ce))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");tr=[this._encode_plus(pe,{text_pair:Ce,add_special_tokens:Fe,return_token_type_ids:kt})]}if(Mt===null?Oe==="max_length"?Mt=this.model_max_length:Mt=(0,p.max)(tr.map(or=>or.input_ids.length))[0]:rt||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."),Mt=Math.min(Mt,this.model_max_length??1/0),Oe||rt)for(let or=0;or<tr.length;++or)tr[or].input_ids.length!==Mt&&(tr[or].input_ids.length>Mt?rt&&Lt(tr[or],Mt):Oe&&Et(tr[or],Mt,qt=>qt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ar={};if(St){if(!(Oe&&rt)&&tr.some(qt=>{var _r;for(const Cn of Object.keys(qt))if(qt[Cn].length!==((_r=tr[0][Cn])==null?void 0:_r.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 or=[tr.length,tr[0].input_ids.length];for(const qt of Object.keys(tr[0]))Ar[qt]=new _.Tensor("int64",BigInt64Array.from(tr.flatMap(_r=>_r[qt]).map(BigInt)),or)}else{for(const or of Object.keys(tr[0]))Ar[or]=tr.map(qt=>qt[or]);if(!It)for(const or of Object.keys(Ar))Ar[or]=Ar[or][0]}return Ar}_encode_text(pe){return pe===null?null:(this.added_tokens_regex?pe.split(this.added_tokens_regex).filter(Oe=>Oe):[pe]).map((Oe,rt)=>{if(this.added_tokens.find(St=>St.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 St=this.pre_tokenizer!==null?this.pre_tokenizer(Oe,{section_index:rt}):[Oe];return this.model(St)}}).flat()}_encode_plus(pe,{text_pair:Ce=null,add_special_tokens:Fe=!0,return_token_type_ids:Oe=null}={}){const{tokens:rt,token_type_ids:Mt}=this._tokenize_helper(pe,{pair:Ce,add_special_tokens:Fe}),St=this.model.convert_tokens_to_ids(rt),kt={input_ids:St,attention_mask:new Array(St.length).fill(1)};return(Oe??this.return_token_type_ids)&&Mt&&(kt.token_type_ids=Mt),kt}_tokenize_helper(pe,{pair:Ce=null,add_special_tokens:Fe=!1}={}){const Oe=this._encode_text(pe),rt=this._encode_text(Ce);return this.post_processor?this.post_processor(Oe,rt,{add_special_tokens:Fe}):{tokens:(0,a.mergeArrays)(Oe??[],rt??[])}}tokenize(pe,{pair:Ce=null,add_special_tokens:Fe=!1}={}){return this._tokenize_helper(pe,{pair:Ce,add_special_tokens:Fe}).tokens}encode(pe,{text_pair:Ce=null,add_special_tokens:Fe=!0,return_token_type_ids:Oe=null}={}){return this._encode_plus(pe,{text_pair:Ce,add_special_tokens:Fe,return_token_type_ids:Oe}).input_ids}batch_decode(pe,Ce={}){return pe instanceof _.Tensor&&(pe=pe.tolist()),pe.map(Fe=>this.decode(Fe,Ce))}decode(pe,Ce={}){if(pe instanceof _.Tensor&&(pe=C(pe)),!Array.isArray(pe)||pe.length===0||!(0,a.isIntegralNumber)(pe[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(pe,Ce)}decode_single(pe,{skip_special_tokens:Ce=!1,clean_up_tokenization_spaces:Fe=null}){let Oe=this.model.convert_ids_to_tokens(pe);Ce&&(Oe=Oe.filter(Mt=>!this.special_tokens.includes(Mt)));let rt=this.decoder?this.decoder(Oe):Oe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(rt=rt.replaceAll(this.decoder.end_of_word_suffix," "),Ce&&(rt=rt.trim())),(Fe??this.clean_up_tokenization_spaces)&&(rt=w(rt)),rt}apply_chat_template(pe,{tools:Ce=null,documents:Fe=null,chat_template:Oe=null,add_generation_prompt:rt=!1,tokenize:Mt=!0,padding:St=!1,truncation:kt=!1,max_length:It=null,return_tensor:tr=!0,return_dict:Ar=!1,tokenizer_kwargs:or={},...qt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const ct=this.chat_template;if(Oe!==null&&Object.hasOwn(ct,Oe))Oe=ct[Oe];else if(Oe===null&&"default"in ct)Oe=ct.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(ct).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 _r=this._compiled_template_cache.get(Oe);_r===void 0&&(_r=new g.Template(Oe),this._compiled_template_cache.set(Oe,_r));const Cn=Object.create(null);for(const ct of bt){const Kn=this.getToken(ct);Kn&&(Cn[ct]=Kn)}const gn=_r.render({messages:pe,add_generation_prompt:rt,tools:Ce,documents:Fe,...Cn,...qt});if(Mt){const ct=this._call(gn,{add_special_tokens:!1,padding:St,truncation:kt,max_length:It,return_tensor:tr,...or});return Ar?ct:ct.input_ids}return gn}}class Ot extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Ut extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Xt extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Yt extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class rr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Ht extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Pr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Yr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class $r extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class mt extends at{}class $t extends at{}class Bt extends at{constructor(pe,Ce){super(pe,Ce);He(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 un extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Bi extends at{}class Mi extends at{}class Gr extends at{}class wn extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Ce=>this.languageRegex.test(Ce)),this.lang_to_token=Ce=>Ce}_build_translation_inputs(W,pe,Ce){return ki(this,W,pe,Ce)}}class Kr extends wn{}class pi extends at{}class Dr extends at{constructor(W,pe){var Oe,rt;const Ce=".,!?…。,、।۔،",Fe=(rt=(Oe=W.pre_tokenizer)==null?void 0:Oe.pretokenizers[0])==null?void 0:rt.pattern;Fe&&Fe.Regex===` ?[^(\\s|[${Ce}])]+`&&(Fe.Regex=` ?[^\\s${Ce}]+`),super(W,pe)}}const Ni="▁";class Ti extends at{constructor(pe,Ce){super(pe,Ce);He(this,"padding_side","left");this.legacy=Ce.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Re({replacement:Ni,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(pe){if(pe===null)return null;if(this.legacy||pe.length===0)return super._encode_text(pe);let Ce=super._encode_text(Ni+pe.replaceAll(Ni," "));return Ce.length>1&&Ce[0]===Ni&&this.special_tokens.includes(Ce[1])&&(Ce=Ce.slice(1)),Ce}}class Cs extends at{}class Lo extends at{}class Ro extends at{}class Bo extends at{}class No extends at{}class ji extends at{}class Ps extends at{}class fo extends at{}class fi extends at{}function ki(Ue,W,pe,Ce){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 Fe=Ce.src_lang,Oe=Ce.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(Fe!==void 0){if(!Ue.language_codes.includes(Fe))throw new Error(`Source language code "${Fe}" is not valid. Must be one of: {${Ue.language_codes.join(", ")}}`);for(const rt of Ue.post_processor.config.single)if("SpecialToken"in rt&&Ue.languageRegex.test(rt.SpecialToken.id)){rt.SpecialToken.id=Ue.lang_to_token(Fe);break}}return Ce.forced_bos_token_id=Ue.model.convert_tokens_to_ids([Ue.lang_to_token(Oe)])[0],Ue._call(W,pe)}class Si extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Ce=>this.languageRegex.test(Ce)),this.lang_to_token=Ce=>Ce}_build_translation_inputs(W,pe,Ce){return ki(this,W,pe,Ce)}}class Ji extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Ce=>this.languageRegex.test(Ce)).map(Ce=>Ce.slice(2,-2)),this.lang_to_token=Ce=>`__${Ce}__`}_build_translation_inputs(W,pe,Ce){return ki(this,W,pe,Ce)}}class ho extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(W,{return_timestamps:pe=!1,return_language:Ce=!1,time_precision:Fe=null,force_full_sequences:Oe=!0}={}){if(Fe===null)throw Error("Must specify time_precision");let rt=null;const Mt=pe==="word";function St(){return{language:rt,timestamp:[null,null],text:""}}const kt=[];let It=St(),tr=0;const Ar=this.timestamp_begin;let or=[],qt=[],_r=!1,Cn=null;const gn=new Set(this.all_special_ids);for(const Tr of W){const cn=Tr.tokens,On=Mt?Tr.token_timestamps:null;let Jt=null,Un=Ar;if("stride"in Tr){const[Er,At,vr]=Tr.stride;if(tr-=At,Cn=Er-vr,At&&(Un=At/Fe+Ar),vr)for(let Lr=cn.length-1;Lr>=0;--Lr){const Xr=Number(cn[Lr]);if(Xr>=Ar){if(Jt!==null&&(Xr-Ar)*Fe<Cn)break;Jt=Xr}}}let yn=[],Sr=[];for(let Er=0;Er<cn.length;++Er){const At=Number(cn[Er]);if(gn.has(At)){const vr=this.decode([At]),Lr=M.WHISPER_LANGUAGE_MAPPING.get(vr.slice(2,-2));if(Lr!==void 0){if(rt!==null&&Lr!==rt&&!pe){or.push(yn);const Xr=this.findLongestCommonSequence(or)[0],Vn=this.decode(Xr);It.text=Vn,kt.push(It),or=[],yn=[],It=St()}rt=It.language=Lr}}else if(At>=Ar){const vr=(At-Ar)*Fe+tr,Lr=(0,p.round)(vr,2);if(Jt!==null&&At>=Jt)_r=!0;else if(_r||or.length>0&&At<Un)_r=!1;else if(It.timestamp[0]===null)It.timestamp[0]=Lr;else if(Lr!==It.timestamp[0]){It.timestamp[1]=Lr,or.push(yn),Mt&&qt.push(Sr);const[Xr,Vn]=this.findLongestCommonSequence(or,qt),zt=this.decode(Xr);It.text=zt,Mt&&(It.words=this.collateWordTimestamps(Xr,Vn,rt)),kt.push(It),or=[],yn=[],qt=[],Sr=[],It=St()}}else if(yn.push(At),Mt){let vr=(0,p.round)(On[Er]+tr,2),Lr;if(Er+1<On.length){Lr=(0,p.round)(On[Er+1]+tr,2);const Xr=this.decode([At]);N.test(Xr)&&(Lr=(0,p.round)(Math.min(vr+Fe,Lr),2))}else Lr=null;Sr.push([vr,Lr])}}if("stride"in Tr){const[Er,At,vr]=Tr.stride;tr+=Er-vr}yn.length>0?(or.push(yn),Mt&&qt.push(Sr)):or.every(Er=>Er.length===0)&&(It=St(),or=[],yn=[],qt=[],Sr=[])}if(or.length>0){if(Oe&&pe)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[Tr,cn]=this.findLongestCommonSequence(or,qt),On=this.decode(Tr);It.text=On,Mt&&(It.words=this.collateWordTimestamps(Tr,cn,rt)),kt.push(It)}let ct=Object.create(null);const Kn=kt.map(Tr=>Tr.text).join("");if(pe||Ce){for(let Tr=0;Tr<kt.length;++Tr){const cn=kt[Tr];pe||delete cn.timestamp,Ce||delete cn.language}if(Mt){const Tr=[];for(const cn of kt)for(const On of cn.words)Tr.push(On);ct={chunks:Tr}}else ct={chunks:kt}}return[Kn,ct]}findLongestCommonSequence(W,pe=null){let Ce=W[0],Fe=Ce.length,Oe=[];const rt=Array.isArray(pe)&&pe.length>0;let Mt=rt?[]:null,St=rt?pe[0]:null;for(let kt=1;kt<W.length;++kt){const It=W[kt];let tr=0,Ar=[Fe,Fe,0,0];const or=It.length;for(let Tr=1;Tr<Fe+or;++Tr){const cn=Math.max(0,Fe-Tr),On=Math.min(Fe,Fe+or-Tr),Jt=Ce.slice(cn,On),Un=Math.max(0,Tr-Fe),yn=Math.min(or,Tr),Sr=It.slice(Un,yn);if(Jt.length!==Sr.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let Er;rt?Er=Jt.filter((Lr,Xr)=>Lr===Sr[Xr]&&St[cn+Xr]<=pe[kt][Un+Xr]).length:Er=Jt.filter((Lr,Xr)=>Lr===Sr[Xr]).length;const At=Tr/1e4,vr=Er/Tr+At;Er>1&&vr>tr&&(tr=vr,Ar=[cn,On,Un,yn])}const[qt,_r,Cn,gn]=Ar,ct=Math.floor((_r+qt)/2),Kn=Math.floor((gn+Cn)/2);Oe.push(...Ce.slice(0,ct)),Ce=It.slice(Kn),Fe=Ce.length,rt&&(Mt.push(...St.slice(0,ct)),St=pe[kt].slice(Kn))}return Oe.push(...Ce),rt?(Mt.push(...St),[Oe,Mt]):[Oe,[]]}collateWordTimestamps(W,pe,Ce){const[Fe,Oe,rt]=this.combineTokensIntoWords(W,Ce),Mt=[];for(let St=0;St<Fe.length;++St){const kt=rt[St];Mt.push({text:Fe[St],timestamp:[pe[kt.at(0)][0],pe[kt.at(-1)][1]]})}return Mt}combineTokensIntoWords(W,pe,Ce=`"'“¡¿([{-`,Fe=`"'.。,,!!??::”)]}、`){pe=pe??"english";let Oe,rt,Mt;return["chinese","japanese","thai","lao","myanmar"].includes(pe)?[Oe,rt,Mt]=this.splitTokensOnUnicode(W):[Oe,rt,Mt]=this.splitTokensOnSpaces(W),this.mergePunctuations(Oe,rt,Mt,Ce,Fe)}decode(W,pe){let Ce;return pe!=null&&pe.decode_with_timestamps?(W instanceof _.Tensor&&(W=C(W)),Ce=this.decodeWithTimestamps(W,pe)):Ce=super.decode(W,pe),Ce}decodeWithTimestamps(W,pe){const Ce=(pe==null?void 0:pe.time_precision)??.02,Fe=Array.from(this.all_special_ids).at(-1)+1;let Oe=[[]];for(let rt of W)if(rt=Number(rt),rt>=Fe){const Mt=((rt-Fe)*Ce).toFixed(2);Oe.push(`<|${Mt}|>`),Oe.push([])}else Oe[Oe.length-1].push(rt);return Oe=Oe.map(rt=>typeof rt=="string"?rt:super.decode(rt,pe)),Oe.join("")}splitTokensOnUnicode(W){const pe=this.decode(W,{decode_with_timestamps:!0}),Ce="�",Fe=[],Oe=[],rt=[];let Mt=[],St=[],kt=0;for(let It=0;It<W.length;++It){const tr=W[It];Mt.push(tr),St.push(It);const Ar=this.decode(Mt,{decode_with_timestamps:!0});(!Ar.includes(Ce)||pe[kt+Ar.indexOf(Ce)]===Ce)&&(Fe.push(Ar),Oe.push(Mt),rt.push(St),Mt=[],St=[],kt+=Ar.length)}return[Fe,Oe,rt]}splitTokensOnSpaces(W){const[pe,Ce,Fe]=this.splitTokensOnUnicode(W),Oe=[],rt=[],Mt=[],St=new RegExp(`^[${j}]$`,"gu");for(let kt=0;kt<pe.length;++kt){const It=pe[kt],tr=Ce[kt],Ar=Fe[kt],or=tr[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),qt=It.startsWith(" "),_r=It.trim(),Cn=St.test(_r);if(or||qt||Cn||Oe.length===0)Oe.push(It),rt.push(tr),Mt.push(Ar);else{const gn=Oe.length-1;Oe[gn]+=It,rt[gn].push(...tr),Mt[gn].push(...Ar)}}return[Oe,rt,Mt]}mergePunctuations(W,pe,Ce,Fe,Oe){const rt=structuredClone(W),Mt=structuredClone(pe),St=structuredClone(Ce);let kt=rt.length-2,It=rt.length-1;for(;kt>=0;)rt[kt].startsWith(" ")&&Fe.includes(rt[kt].trim())?(rt[It]=rt[kt]+rt[It],Mt[It]=(0,a.mergeArrays)(Mt[kt],Mt[It]),St[It]=(0,a.mergeArrays)(St[kt],St[It]),rt[kt]="",Mt[kt]=[],St[kt]=[]):It=kt,--kt;for(kt=0,It=1;It<rt.length;)!rt[kt].endsWith(" ")&&Oe.includes(rt[It])?(rt[kt]+=rt[It],Mt[kt]=(0,a.mergeArrays)(Mt[kt],Mt[It]),St[kt]=(0,a.mergeArrays)(St[kt],St[It]),rt[It]="",Mt[It]=[],St[It]=[]):kt=It,++It;return[rt.filter(tr=>tr),Mt.filter(tr=>tr.length>0),St.filter(tr=>tr.length>0)]}get_decoder_prompt_ids({language:W=null,task:pe=null,no_timestamps:Ce=!0}={}){const Fe=[];if(W){const Oe=(0,M.whisper_language_to_code)(W),rt=this.model.tokens_to_ids.get(`<|${Oe}|>`);if(rt===void 0)throw new Error(`Unable to find language "${Oe}" in model vocabulary. Please report this issue at ${y.GITHUB_ISSUE_URL}.`);Fe.push(rt)}else Fe.push(null);if(pe){if(pe=pe.toLowerCase(),pe!=="transcribe"&&pe!=="translate")throw new Error(`Task "${pe}" is not supported. Must be one of: ["transcribe", "translate"]`);const Oe=this.model.tokens_to_ids.get(`<|${pe}|>`);if(Oe===void 0)throw new Error(`Unable to find task "${pe}" in model vocabulary. Please report this issue at ${y.GITHUB_ISSUE_URL}.`);Fe.push(Oe)}else Fe.push(null);if(Ce){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 ${y.GITHUB_ISSUE_URL}.`);Fe.push(Oe)}return Fe.map((Oe,rt)=>[rt+1,Oe]).filter(Oe=>Oe[1]!==null)}}class mo extends at{}class Zt extends at{}class eo extends at{}class jo extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Ce=>this.languageRegex.test(Ce)),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[pe,...Ce]=W.trim().split(this.languageRegex);if(Ce.length===0)return super._encode_text(pe);if(Ce.length===2){const[Fe,Oe]=Ce;return this.supported_language_codes.includes(Fe)||console.warn(`Unsupported language code "${Fe}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,a.mergeArrays)([Fe],super._encode_text(Oe))}}}class Uo extends at{}class go extends at{}class Vo extends at{}class Wo extends at{}class _o extends at{}class Go extends at{constructor(W,pe){super(W,pe),this.decoder=new ve({})}}class Vr extends at{}class jn{static async from_pretrained(W,{progress_callback:pe=null,config:Ce=null,cache_dir:Fe=null,local_files_only:Oe=!1,revision:rt="main",legacy:Mt=null}={}){var Ar;const[St,kt]=await E(W,{progress_callback:pe,config:Ce,cache_dir:Fe,local_files_only:Oe,revision:rt,legacy:Mt}),It=((Ar=kt.tokenizer_class)==null?void 0:Ar.replace(/Fast$/,""))??"PreTrainedTokenizer";let tr=this.TOKENIZER_CLASS_MAPPING[It];return tr||(console.warn(`Unknown tokenizer class "${It}", attempting to construct from base class.`),tr=at),new tr(St,kt)}}He(jn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Bi,DistilBertTokenizer:mt,CamembertTokenizer:$t,DebertaTokenizer:rr,DebertaV2Tokenizer:Ht,BertTokenizer:Ot,HerbertTokenizer:Pr,ConvBertTokenizer:Yr,RoFormerTokenizer:$r,XLMTokenizer:Bt,ElectraTokenizer:un,MobileBertTokenizer:Xt,SqueezeBertTokenizer:Yt,AlbertTokenizer:Ut,GPT2Tokenizer:Mi,BartTokenizer:Gr,MBartTokenizer:wn,MBart50Tokenizer:Kr,RobertaTokenizer:pi,WhisperTokenizer:ho,CodeGenTokenizer:mo,CLIPTokenizer:Zt,SiglipTokenizer:eo,MarianTokenizer:jo,BloomTokenizer:Dr,NllbTokenizer:Si,M2M100Tokenizer:Ji,LlamaTokenizer:Ti,CodeLlamaTokenizer:Cs,XLMRobertaTokenizer:Lo,MPNetTokenizer:Ro,FalconTokenizer:Bo,GPTNeoXTokenizer:No,EsmTokenizer:ji,Wav2Vec2CTCTokenizer:Uo,BlenderbotTokenizer:go,BlenderbotSmallTokenizer:Vo,SpeechT5Tokenizer:Wo,NougatTokenizer:_o,VitsTokenizer:Go,Qwen2Tokenizer:Ps,GemmaTokenizer:fo,Grok1Tokenizer:fi,CohereTokenizer:Vr,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,t,r)=>{r.r(t),r.d(t,{hamming:()=>M,hanning:()=>g,mel_filter_bank:()=>w,read_audio:()=>_,spectrogram:()=>B,window_function:()=>j});var o=r("./src/utils/hub.js"),a=r("./src/utils/maths.js"),l=r("./src/utils/core.js"),p=r("./src/utils/tensor.js");async function _(N,ae){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 ce=await(await(0,o.getFile)(N)).arrayBuffer(),xe=new AudioContext({sampleRate:ae});typeof ae>"u"&&console.warn(`No sampling rate provided, using default of ${xe.sampleRate}Hz.`);const Y=await xe.decodeAudioData(ce);let _e;if(Y.numberOfChannels===2){const L=Math.sqrt(2),Se=Y.getChannelData(0),Xe=Y.getChannelData(1);_e=new Float32Array(Se.length);for(let me=0;me<Y.length;++me)_e[me]=L*(Se[me]+Xe[me])/2}else _e=Y.getChannelData(0);return _e}function h(N,ae){if(N<1)return new Float64Array;if(N===1)return new Float64Array([1]);const ce=1-ae,xe=2*Math.PI/(N-1),Y=new Float64Array(N);for(let _e=0;_e<N;++_e)Y[_e]=ae-ce*Math.cos(_e*xe);return Y}function g(N){return h(N,.5)}function M(N){return h(N,.54)}const y={htk:N=>2595*Math.log10(1+N/700),kaldi:N=>1127*Math.log(1+N/700),slaney:(N,ae=1e3,ce=15,xe=27/Math.log(6.4))=>N>=ae?ce+Math.log(N/ae)*xe:3*N/200};function E(N,ae="htk"){const ce=y[ae];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof N=="number"?ce(N):N.map(xe=>ce(xe))}const T={htk:N=>700*(10**(N/2595)-1),kaldi:N=>700*(Math.exp(N/1127)-1),slaney:(N,ae=1e3,ce=15,xe=Math.log(6.4)/27)=>N>=ce?ae*Math.exp(xe*(N-ce)):200*N/3};function O(N,ae="htk"){const ce=T[ae];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof N=="number"?ce(N):N.map(xe=>ce(xe))}function S(N,ae){const ce=Float64Array.from({length:ae.length-1},(L,Se)=>ae[Se+1]-ae[Se]),xe=Array.from({length:N.length},()=>new Array(ae.length));for(let L=0;L<N.length;++L){const Se=xe[L];for(let Xe=0;Xe<ae.length;++Xe)Se[Xe]=ae[Xe]-N[L]}const Y=ae.length-2,_e=Array.from({length:Y},()=>new Array(N.length));for(let L=0;L<N.length;++L){const Se=xe[L];for(let Xe=0;Xe<Y;++Xe){const me=-Se[Xe]/ce[Xe],X=Se[Xe+2]/ce[Xe+1];_e[Xe][L]=Math.max(0,Math.min(me,X))}}return _e}function C(N,ae,ce){const xe=(ae-N)/(ce-1);return Float64Array.from({length:ce},(Y,_e)=>N+xe*_e)}function w(N,ae,ce,xe,Y,_e=null,L="htk",Se=!1){if(_e!==null&&_e!=="slaney")throw new Error('norm must be one of null or "slaney"');const Xe=E(ce,L),me=E(xe,L),X=C(Xe,me,ae+2);let ie=O(X,L),Me;if(Se){const ge=Y/(N*2);Me=E(Float64Array.from({length:N},(Ke,Le)=>Le*ge),L),ie=X}else Me=C(0,Math.floor(Y/2),N);const Q=S(Me,ie);if(_e!==null&&_e==="slaney")for(let ge=0;ge<ae;++ge){const Ke=Q[ge],Le=2/(ie[ge+2]-ie[ge]);for(let Be=0;Be<N;++Be)Ke[Be]*=Le}return Q}function b(N,ae,ce){const xe=new N.constructor(N.length+ae+ce),Y=N.length-1;for(let _e=0;_e<N.length;++_e)xe[ae+_e]=N[_e];for(let _e=1;_e<=ae;++_e)xe[ae-_e]=N[(0,l.calculateReflectOffset)(_e,Y)];for(let _e=1;_e<=ce;++_e)xe[Y+ae+_e]=N[(0,l.calculateReflectOffset)(Y-_e,Y)];return xe}function I(N,ae,ce,xe,Y){if(ce<=0)throw new Error("reference must be greater than zero");if(xe<=0)throw new Error("min_value must be greater than zero");ce=Math.max(xe,ce);const _e=Math.log10(ce);for(let L=0;L<N.length;++L)N[L]=ae*Math.log10(Math.max(xe,N[L])-_e);if(Y!==null){if(Y<=0)throw new Error("db_range must be greater than zero");const L=(0,a.max)(N)[0]-Y;for(let Se=0;Se<N.length;++Se)N[Se]=Math.max(N[Se],L)}return N}function U(N,ae=1,ce=1e-5,xe=null){return I(N,20,ae,ce,xe)}function z(N,ae=1,ce=1e-10,xe=null){return I(N,10,ae,ce,xe)}async function B(N,ae,ce,xe,{fft_length:Y=null,power:_e=1,center:L=!0,pad_mode:Se="reflect",onesided:Xe=!0,preemphasis:me=null,mel_filters:X=null,mel_floor:ie=1e-10,log_mel:Me=null,reference:Q=1,min_value:ge=1e-10,db_range:Ke=null,remove_dc_offset:Le=null,min_num_frames:Be=null,max_num_frames:We=null,do_pad:st=!0,transpose:pt=!1}={}){const Ge=ae.length;if(Y===null&&(Y=ce),ce>Y)throw Error(`frame_length (${ce}) may not be larger than fft_length (${Y})`);if(Ge!==ce)throw new Error(`Length of the window (${Ge}) must equal frame_length (${ce})`);if(xe<=0)throw new Error("hop_length must be greater than zero");if(_e===null&&X!==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(L){if(Se!=="reflect")throw new Error(`pad_mode="${Se}" not implemented yet.`);const ee=Math.floor((Y-1)/2)+1;N=b(N,ee,ee)}let Te=Math.floor(1+Math.floor((N.length-ce)/xe));Be!==null&&Te<Be&&(Te=Be);const je=Xe?Math.floor(Y/2)+1:Y;let Ye=Te,et=Te;We!==null&&(We>Te?st&&(et=We):et=Ye=We);const A=new a.FFT(Y),$e=new Float64Array(Y),Pe=new Float64Array(A.outputBufferSize),se=new Float32Array(je*et);for(let ee=0;ee<Ye;++ee){const D=ee*xe,ue=Math.min(N.length-D,ce);ue!==ce&&$e.fill(0,0,ce);for(let le=0;le<ue;++le)$e[le]=N[D+le];if(Le){let le=0;for(let Ne=0;Ne<ue;++Ne)le+=$e[Ne];const ke=le/ue;for(let Ne=0;Ne<ue;++Ne)$e[Ne]-=ke}if(me!==null){for(let le=ue-1;le>=1;--le)$e[le]-=me*$e[le-1];$e[0]*=1-me}for(let le=0;le<ae.length;++le)$e[le]*=ae[le];A.realTransform(Pe,$e);for(let le=0;le<je;++le){const ke=le<<1;se[le*et+ee]=Pe[ke]**2+Pe[ke+1]**2}}if(_e!==null&&_e!==2){const ee=2/_e;for(let D=0;D<se.length;++D)se[D]**=ee}const re=X.length;let ye=await(0,p.matmul)(new p.Tensor("float32",X.flat(),[re,je]),new p.Tensor("float32",se,[je,et]));pt&&(ye=ye.transpose(1,0));const R=ye.data;for(let ee=0;ee<R.length;++ee)R[ee]=Math.max(ie,R[ee]);if(_e!==null&&Me!==null){const ee=Math.min(R.length,Ye*re);switch(Me){case"log":for(let D=0;D<ee;++D)R[D]=Math.log(R[D]);break;case"log10":for(let D=0;D<ee;++D)R[D]=Math.log10(R[D]);break;case"dB":if(_e===1)U(R,Q,ge,Ke);else if(_e===2)z(R,Q,ge,Ke);else throw new Error(`Cannot use log_mel option '${Me}' with power ${_e}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${Me}'`)}}return ye}function j(N,ae,{periodic:ce=!0,frame_length:xe=null,center:Y=!0}={}){const _e=ce?N+1:N;let L;switch(ae){case"boxcar":L=new Float64Array(_e).fill(1);break;case"hann":case"hann_window":L=g(_e);break;case"hamming":L=M(_e);break;case"povey":L=g(_e).map(Se=>Math.pow(Se,.85));break;default:throw new Error(`Unknown window type ${ae}.`)}if(ce&&(L=L.subarray(0,N)),xe===null)return L;if(N>xe)throw new Error(`Length of the window (${N}) may not be larger than frame_length (${xe})`);return L}},"./src/utils/constants.js":(e,t,r)=>{r.r(t),r.d(t,{GITHUB_ISSUE_URL:()=>o});const o="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(e,t,r)=>{r.r(t),r.d(t,{calculateDimensions:()=>h,calculateReflectOffset:()=>E,dispatchCallback:()=>o,escapeRegExp:()=>l,isIntegralNumber:()=>_,isTypedArray:()=>p,mergeArrays:()=>M,pick:()=>T,pop:()=>g,product:()=>y,reverseDictionary:()=>a});function o(O,S){O&&O(S)}function a(O){return Object.fromEntries(Object.entries(O).map(([S,C])=>[C,S]))}function l(O){return O.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p(O){var S,C,w;return((w=(C=(S=O==null?void 0:O.prototype)==null?void 0:S.__proto__)==null?void 0:C.constructor)==null?void 0:w.name)==="TypedArray"}function _(O){return Number.isInteger(O)||typeof O=="bigint"}function h(O){const S=[];let C=O;for(;Array.isArray(C);)S.push(C.length),C=C[0];return S}function g(O,S,C=void 0){const w=O[S];if(w!==void 0)return delete O[S],w;if(C===void 0)throw Error(`Key ${S} does not exist in object.`);return C}function M(...O){return Array.prototype.concat.apply([],O)}function y(...O){return O.reduce((S,C)=>S.flatMap(w=>C.map(b=>[w,b])))}function E(O,S){return Math.abs((O+S)%(2*S)-S)}function T(O,S){return Object.assign({},...S.map(C=>{if(O[C]!==void 0)return{[C]:O[C]}}))}},"./src/utils/data-structures.js":(e,t,r)=>{r.r(t),r.d(t,{CharTrie:()=>a,PriorityQueue:()=>o,TokenLattice:()=>p});class o{constructor(g=(y,E)=>y>E,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 y=this._smallest();this._comparator(M,this._heap[y])&&(this._heap[y]=M,this._siftUpFrom(y))}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 y=this._heap[g];this._heap[g]=this._heap[M],this._heap[M]=y}_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 y of g){let E=M.children.get(y);E===void 0&&(E=l.default(),M.children.set(y,E)),M=E}M.isLeaf=!0}*commonPrefixSearch(g){let M=this.root,y="";for(let E=0;E<g.length&&M!==void 0;++E){const T=g[E];y+=T,M=M.children.get(T),M!==void 0&&M.isLeaf&&(yield y)}}}class l{constructor(g,M){this.isLeaf=g,this.children=M}static default(){return new l(!1,new Map)}}class p{constructor(g,M,y){this.sentence=g,this.len=g.length,this.bosTokenId=M,this.eosTokenId=y,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},()=>[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const E=new _(this.bosTokenId,0,0,0,0),T=new _(this.eosTokenId,1,this.len,0,0);this.nodes.push(E.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(E)}insert(g,M,y,E){const T=this.nodes.length,O=new _(E,T,g,M,y);this.beginNodes[g].push(O),this.endNodes[g+M].push(O),this.nodes.push(O)}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 C=0,w=null;for(let b of this.endNodes[M]){const I=b.backtraceScore+S.score;(w===null||I>C)&&(w=b.clone(),C=I)}if(w!==null)S.prev=w,S.backtraceScore=C;else return[]}++M}const y=[],T=this.beginNodes[g][0].prev;if(T===null)return[];let O=T.clone();for(;O.prev!==null;)y.push(O.clone()),O=O.clone().prev.clone();return y.reverse(),y}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,y,E,T){this.tokenId=g,this.nodeId=M,this.pos=y,this.length=E,this.score=T,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,r)=>{r.r(t),r.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,r)=>{r.r(t),r.d(t,{DATA_TYPES:()=>p,DEFAULT_DEVICE_DTYPE_MAPPING:()=>_,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>h,isWebGpuFp16Supported:()=>l});var o=r("./src/env.js"),a=r("./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}}(),p=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_=Object.freeze({[a.DEVICE_TYPES.wasm]:p.q8}),h=Object.freeze({[p.fp32]:"",[p.fp16]:"_fp16",[p.int8]:"_int8",[p.uint8]:"_uint8",[p.q8]:"_quantized",[p.q4]:"_q4",[p.q4f16]:"_q4f16",[p.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,r)=>{r.r(t),r.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,r)=>{r.r(t),r.d(t,{getFile:()=>M,getModelFile:()=>S,getModelJSON:()=>C});var o=r("?7a2c"),a=r("?a42a"),l=r("./src/env.js"),p=r("./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 z=o.statSync(U);this.headers.set("content-length",z.size.toString()),this.updateContentType();let B=this;this.body=new ReadableStream({start(j){B.arrayBuffer().then(N=>{j.enqueue(new Uint8Array(N)),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,z=null){let B;try{B=new URL(I)}catch{return!1}return!(U&&!U.includes(B.protocol)||z&&!z.includes(B.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 z=!!(ko!=null&&ko.TESTING_REMOTELY),B=l.env.version,j=new Headers;if(j.set("User-Agent",`transformers.js/${B}; is_ci/${z};`),g(I,["http:","https:"],["huggingface.co","hf.co"])){const ae=(ko==null?void 0:ko.HF_TOKEN)??(ko==null?void 0:ko.HF_ACCESS_TOKEN);ae&&j.set("Authorization",`Bearer ${ae}`)}return fetch(I,{headers:j})}else return fetch(I)}const y={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 E(I,U,z){if(!z)return null;const B=y[I]??`Error (${I}) occurred while trying to load file`;throw Error(`${B}: "${U}".`)}class T{constructor(U){this.path=U}async match(U){let z=a.join(this.path,U),B=new h(z);if(B.exists)return B}async put(U,z){const B=Buffer.from(await z.arrayBuffer());let j=a.join(this.path,U);try{await o.promises.mkdir(a.dirname(j),{recursive:!0}),await o.promises.writeFile(j,B)}catch(N){console.warn("An error occurred while writing the file to cache:",N)}}}async function O(I,...U){for(let z of U)try{let B=await I.match(z);if(B)return B}catch{continue}}async function S(I,U,z=!0,B={}){if(!l.env.allowLocalModels){if(B.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,p.dispatchCallback)(B.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(Me){console.warn("An error occurred while opening the browser cache:",Me)}}if(!j&&l.env.useFSCache&&(j=new T(B.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 N=B.revision??"main";let ae=b(I,U),ce=b(l.env.localModelPath,ae),xe=b(l.env.remoteHost,l.env.remotePathTemplate.replaceAll("{model}",I).replaceAll("{revision}",encodeURIComponent(N)),U),Y=N==="main"?ae:b(I,N,U),_e,L=j instanceof T?Y:xe,Se=!1,Xe;j&&(Xe=await O(j,ce,L));const me=Xe!==void 0;if(Xe===void 0){if(l.env.allowLocalModels)if(g(ae,["http:","https:"])){if(B.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!l.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{Xe=await M(ce),_e=ce}catch(Q){console.warn(`Unable to load from local path "${ce}": "${Q}"`)}if(Xe===void 0||Xe.status===404){if(B.local_files_only||!l.env.allowRemoteModels){if(z)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ce}".`);return null}if(Xe=await M(xe),Xe.status!==200)return E(Xe.status,xe,z);_e=L}Se=j&&typeof Response<"u"&&Xe instanceof Response&&Xe.status===200}(0,p.dispatchCallback)(B.progress_callback,{status:"download",name:I,file:U});const X={status:"progress",name:I,file:U};let ie;return B.progress_callback?me&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ie=new Uint8Array(await Xe.arrayBuffer()),(0,p.dispatchCallback)(B.progress_callback,{...X,progress:100,loaded:ie.length,total:ie.length})):ie=await w(Xe,Me=>{(0,p.dispatchCallback)(B.progress_callback,{...X,...Me})}):ie=new Uint8Array(await Xe.arrayBuffer()),Se&&_e&&await j.match(_e)===void 0&&await j.put(_e,new Response(ie,{headers:Xe.headers})).catch(Me=>{console.warn(`Unable to add response to browser cache: ${Me}.`)}),(0,p.dispatchCallback)(B.progress_callback,{status:"done",name:I,file:U}),ie}async function C(I,U,z=!0,B={}){let j=await S(I,U,z,B);if(j===null)return{};let ae=new TextDecoder("utf-8").decode(j);return JSON.parse(ae)}async function w(I,U){const z=I.headers.get("Content-Length");z===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let B=parseInt(z??"0"),j=new Uint8Array(B),N=0;const ae=I.body.getReader();async function ce(){const{done:xe,value:Y}=await ae.read();if(xe)return;let _e=N+Y.length;if(_e>B){B=_e;let Se=new Uint8Array(B);Se.set(j),j=Se}j.set(Y,N),N=_e;const L=N/B*100;return U({progress:L,loaded:N,total:B}),ce()}return await ce(),j}function b(...I){return I=I.map((U,z)=>(z&&(U=U.replace(new RegExp("^/"),"")),z!==I.length-1&&(U=U.replace(new RegExp("/$"),"")),U)),I.join("/")}},"./src/utils/image.js":(e,t,r)=>{r.r(t),r.d(t,{RawImage:()=>O});var o=r("./src/utils/hub.js"),a=r("./src/env.js"),l=r("./src/utils/tensor.js"),p=r("?2b25");const _=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope";let g,M,y;if(_)g=(S,C)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(S,C)},y=self.createImageBitmap,M=self.ImageData;else if(p)y=async S=>{const w=(await S.metadata()).channels,{data:b,info:I}=await S.rotate().raw().toBuffer({resolveWithObject:!0}),U=new O(new Uint8ClampedArray(b),I.width,I.height,I.channels);return w!==void 0&&w!==I.channels&&U.convert(w),U};else throw new Error("Unable to load image processing library.");const E={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},T=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class O{constructor(C,w,b,I){this.data=C,this.width=w,this.height=b,this.channels=I}get size(){return[this.width,this.height]}static async read(C){if(C instanceof O)return C;if(typeof C=="string"||C instanceof URL)return await this.fromURL(C);throw new Error(`Unsupported input type: ${typeof C}`)}static fromCanvas(C){if(!_)throw new Error("fromCanvas() is only supported in browser environments.");const b=C.getContext("2d").getImageData(0,0,C.width,C.height).data;return new O(b,C.width,C.height,4)}static async fromURL(C){const w=await(0,o.getFile)(C);if(w.status!==200)throw new Error(`Unable to read image from "${C}" (${w.status} ${w.statusText})`);const b=await w.blob();return this.fromBlob(b)}static async fromBlob(C){if(_){const w=await y(C),b=g(w.width,w.height).getContext("2d");return b.drawImage(w,0,0),new this(b.getImageData(0,0,w.width,w.height).data,w.width,w.height,4)}else{const w=p(await C.arrayBuffer());return await y(w)}}static fromTensor(C,w="CHW"){if(C.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${C.dims.length} dimensions.`);if(w==="CHW")C=C.transpose(1,2,0);else if(w!=="HWC")throw new Error(`Unsupported channel format: ${w}`);if(!(C.data instanceof Uint8ClampedArray||C.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${C.type}`);switch(C.dims[2]){case 1:case 2:case 3:case 4:return new O(C.data,C.dims[1],C.dims[0],C.dims[2]);default:throw new Error(`Unsupported number of channels: ${C.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const C=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let w=0,b=0;w<this.data.length;w+=this.channels){const I=this.data[w],U=this.data[w+1],z=this.data[w+2];C[b++]=Math.round(.2989*I+.587*U+.114*z)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(C,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const C=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let w=0,b=0;w<this.data.length;++w)C[b++]=this.data[w],C[b++]=this.data[w],C[b++]=this.data[w];break;case 4:for(let w=0,b=0;w<this.data.length;w+=4)C[b++]=this.data[w],C[b++]=this.data[w+1],C[b++]=this.data[w+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(C,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const C=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let w=0,b=0;w<this.data.length;++w)C[b++]=this.data[w],C[b++]=this.data[w],C[b++]=this.data[w],C[b++]=255;break;case 3:for(let w=0,b=0;w<this.data.length;w+=3)C[b++]=this.data[w],C[b++]=this.data[w+1],C[b++]=this.data[w+2],C[b++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(C,this.width,this.height,4)}async resize(C,w,{resample:b=2}={}){let I=E[b]??b;if(_){const U=this.channels,z=this.toCanvas(),B=g(C,w).getContext("2d");return B.drawImage(z,0,0,C,w),new O(B.getImageData(0,0,C,w).data,C,w,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([C/this.width,0,0,w/this.height],{interpolator:I});break;case"lanczos":U=U.resize({width:C,height:w,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${I} is not supported.`)}return await y(U)}}async pad([C,w,b,I]){if(C=Math.max(C,0),w=Math.max(w,0),b=Math.max(b,0),I=Math.max(I,0),C===0&&w===0&&b===0&&I===0)return this;if(_){const U=this.channels,z=this.toCanvas(),B=this.width+C+w,j=this.height+b+I,N=g(B,j).getContext("2d");return N.drawImage(z,0,0,this.width,this.height,C,b,B,j),new O(N.getImageData(0,0,B,j).data,B,j,4).convert(U)}else{const U=this.toSharp().extend({left:C,right:w,top:b,bottom:I});return await y(U)}}async crop([C,w,b,I]){if(C=Math.max(C,0),w=Math.max(w,0),b=Math.min(b,this.width-1),I=Math.min(I,this.height-1),C===0&&w===0&&b===this.width-1&&I===this.height-1)return this;const U=b-C+1,z=I-w+1;if(_){const B=this.channels,j=this.toCanvas(),N=g(U,z).getContext("2d");return N.drawImage(j,C,w,U,z,0,0,U,z),new O(N.getImageData(0,0,U,z).data,U,z,4).convert(B)}else{const B=this.toSharp().extract({left:C,top:w,width:U,height:z});return await y(B)}}async center_crop(C,w){if(this.width===C&&this.height===w)return this;const b=(this.width-C)/2,I=(this.height-w)/2;if(_){const U=this.channels,z=this.toCanvas(),B=g(C,w).getContext("2d");let j=0,N=0,ae=0,ce=0;return b>=0?j=b:ae=-b,I>=0?N=I:ce=-I,B.drawImage(z,j,N,C,w,ae,ce,C,w),new O(B.getImageData(0,0,C,w).data,C,w,4).convert(U)}else{let U=this.toSharp();if(b>=0&&I>=0)U=U.extract({left:Math.floor(b),top:Math.floor(I),width:C,height:w});else if(b<=0&&I<=0){const z=Math.floor(-I),B=Math.floor(-b);U=U.extend({top:z,left:B,right:C-this.width-B,bottom:w-this.height-z})}else{let z=[0,0],B=0;I<0?(z[0]=Math.floor(-I),z[1]=w-this.height-z[0]):B=Math.floor(I);let j=[0,0],N=0;b<0?(j[0]=Math.floor(-b),j[1]=C-this.width-j[0]):N=Math.floor(b),U=U.extend({top:z[0],bottom:z[1],left:j[0],right:j[1]}).extract({left:N,top:B,width:C,height:w})}return await y(U)}}async toBlob(C="image/png",w=1){if(!_)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:C,quality:w})}toTensor(C="CHW"){let w=new l.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(C!=="HWC")if(C==="CHW")w=w.permute(2,0,1);else throw new Error(`Unsupported channel format: ${C}`);return w}toCanvas(){if(!_)throw new Error("toCanvas() is only supported in browser environments.");const C=this.clone().rgba(),w=g(C.width,C.height),b=new M(C.data,C.width,C.height);return w.getContext("2d").putImageData(b,0,0),w}_update(C,w,b,I=null){return this.data=C,this.width=w,this.height=b,I!==null&&(this.channels=I),this}clone(){return new O(this.data.slice(),this.width,this.height,this.channels)}convert(C){if(this.channels===C)return this;switch(C){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(C){if(_){if(h)throw new Error("Unable to save an image from a Web Worker.");const w=C.split(".").pop().toLowerCase(),b=T.get(w)??"image/png",I=await this.toBlob(b),U=URL.createObjectURL(I),z=document.createElement("a");z.href=U,z.download=C,z.click(),z.remove()}else{if(a.env.useFS)return await this.toSharp().toFile(C);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 p(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,t,r)=>{r.r(t),r.d(t,{FFT:()=>S,bankers_round:()=>b,cos_sim:()=>h,dot:()=>_,dynamic_time_warping:()=>I,interpolate_data:()=>o,log_softmax:()=>p,magnitude:()=>g,max:()=>y,medianFilter:()=>C,min:()=>M,permute_data:()=>a,round:()=>w,softmax:()=>l});function o(U,[z,B,j],[N,ae],ce="bilinear",xe=!1){const Y=ae/j,_e=N/B,L=new U.constructor(N*ae*z),Se=B*j,Xe=N*ae;for(let me=0;me<N;++me)for(let X=0;X<ae;++X){const ie=me*ae+X,Me=(X+.5)/Y-.5,Q=(me+.5)/_e-.5;let ge=Math.floor(Me),Ke=Math.floor(Q);const Le=Math.min(ge+1,j-1),Be=Math.min(Ke+1,B-1);ge=Math.max(ge,0),Ke=Math.max(Ke,0);const We=Me-ge,st=Q-Ke,pt=(1-We)*(1-st),Ge=We*(1-st),Te=(1-We)*st,je=We*st,Ye=Ke*j,et=Be*j,A=Ye+ge,$e=Ye+Le,Pe=et+ge,se=et+Le;for(let re=0;re<z;++re){const ye=re*Se;L[re*Xe+ie]=pt*U[ye+A]+Ge*U[ye+$e]+Te*U[ye+Pe]+je*U[ye+se]}}return L}function a(U,z,B){const j=new Array(B.length),N=new Array(B.length);for(let xe=B.length-1,Y=1;xe>=0;--xe)N[xe]=Y,j[xe]=z[B[xe]],Y*=j[xe];const ae=B.map((xe,Y)=>N[B.indexOf(Y)]),ce=new U.constructor(U.length);for(let xe=0;xe<U.length;++xe){let Y=0;for(let _e=z.length-1,L=xe;_e>=0;--_e)Y+=L%z[_e]*ae[_e],L=Math.floor(L/z[_e]);ce[Y]=U[xe]}return[ce,j]}function l(U){const z=y(U)[0],B=U.map(ae=>Math.exp(ae-z)),j=B.reduce((ae,ce)=>ae+ce,0);return B.map(ae=>ae/j)}function p(U){return l(U).map(j=>Math.log(j))}function _(U,z){let B=0;for(let j=0;j<U.length;++j)B+=U[j]*z[j];return B}function h(U,z){const B=_(U,z),j=g(U),N=g(z);return B/(j*N)}function g(U){return Math.sqrt(U.reduce((z,B)=>z+B*B,0))}function M(U){if(U.length===0)throw Error("Array must not be empty");let z=U[0],B=0;for(let j=1;j<U.length;++j)U[j]<z&&(z=U[j],B=j);return[z,B]}function y(U){if(U.length===0)throw Error("Array must not be empty");let z=U[0],B=0;for(let j=1;j<U.length;++j)U[j]>z&&(z=U[j],B=j);return[Number(z),B]}function E(U){return U>0&&(U&U-1)===0}class T{constructor(z){if(this.size=z|0,this.size<=1||!E(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=z<<1,this.table=new Float64Array(this.size*2);for(let j=0;j<this.table.length;j+=2){const N=Math.PI*j/this.size;this.table[j]=Math.cos(N),this.table[j+1]=-Math.sin(N)}let B=0;for(let j=1;this.size>j;j<<=1)++B;this._width=B%2===0?B-1:B,this._bitrev=new Int32Array(1<<this._width);for(let j=0;j<this._bitrev.length;++j){this._bitrev[j]=0;for(let N=0;N<this._width;N+=2){const ae=this._width-N-2;this._bitrev[j]|=(j>>>N&3)<<ae}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(z,B){const j=B||new Array(z.length>>>1);for(let N=0;N<z.length;N+=2)j[N>>>1]=z[N];return j}toComplexArray(z,B){const j=B||this.createComplexArray();for(let N=0;N<j.length;N+=2)j[N]=z[N>>>1],j[N+1]=0;return j}transform(z,B){if(z===B)throw new Error("Input and output buffers must be different");this._transform4(z,B,1)}realTransform(z,B){if(z===B)throw new Error("Input and output buffers must be different");this._realTransform4(z,B,1)}inverseTransform(z,B){if(z===B)throw new Error("Input and output buffers must be different");this._transform4(z,B,-1);for(let j=0;j<z.length;++j)z[j]/=this.size}_transform4(z,B,j){const N=this._csize;let ce=1<<this._width,xe=N/ce<<1,Y,_e;const L=this._bitrev;if(xe===4)for(Y=0,_e=0;Y<N;Y+=xe,++_e){const Xe=L[_e];this._singleTransform2(B,z,Y,Xe,ce)}else for(Y=0,_e=0;Y<N;Y+=xe,++_e){const Xe=L[_e];this._singleTransform4(B,z,Y,Xe,ce,j)}const Se=this.table;for(ce>>=2;ce>=2;ce>>=2){xe=N/ce<<1;const Xe=xe>>>2;for(Y=0;Y<N;Y+=xe){const me=Y+Xe-1;for(let X=Y,ie=0;X<me;X+=2,ie+=ce){const Me=X,Q=Me+Xe,ge=Q+Xe,Ke=ge+Xe,Le=z[Me],Be=z[Me+1],We=z[Q],st=z[Q+1],pt=z[ge],Ge=z[ge+1],Te=z[Ke],je=z[Ke+1],Ye=Se[ie],et=j*Se[ie+1],A=We*Ye-st*et,$e=We*et+st*Ye,Pe=Se[2*ie],se=j*Se[2*ie+1],re=pt*Pe-Ge*se,ye=pt*se+Ge*Pe,R=Se[3*ie],ee=j*Se[3*ie+1],D=Te*R-je*ee,ue=Te*ee+je*R,le=Le+re,ke=Be+ye,Ne=Le-re,dt=Be-ye,Je=A+D,Ve=$e+ue,Z=j*(A-D),ve=j*($e-ue);z[Me]=le+Je,z[Me+1]=ke+Ve,z[Q]=Ne+ve,z[Q+1]=dt-Z,z[ge]=le-Je,z[ge+1]=ke-Ve,z[Ke]=Ne-ve,z[Ke+1]=dt+Z}}}}_singleTransform2(z,B,j,N,ae){const ce=z[N],xe=z[N+1],Y=z[N+ae],_e=z[N+ae+1];B[j]=ce+Y,B[j+1]=xe+_e,B[j+2]=ce-Y,B[j+3]=xe-_e}_singleTransform4(z,B,j,N,ae,ce){const xe=ae*2,Y=ae*3,_e=z[N],L=z[N+1],Se=z[N+ae],Xe=z[N+ae+1],me=z[N+xe],X=z[N+xe+1],ie=z[N+Y],Me=z[N+Y+1],Q=_e+me,ge=L+X,Ke=_e-me,Le=L-X,Be=Se+ie,We=Xe+Me,st=ce*(Se-ie),pt=ce*(Xe-Me);B[j]=Q+Be,B[j+1]=ge+We,B[j+2]=Ke+pt,B[j+3]=Le-st,B[j+4]=Q-Be,B[j+5]=ge-We,B[j+6]=Ke-pt,B[j+7]=Le+st}_realTransform4(z,B,j){const N=this._csize;let ce=1<<this._width,xe=N/ce<<1,Y,_e;const L=this._bitrev;if(xe===4)for(Y=0,_e=0;Y<N;Y+=xe,++_e){const me=L[_e];this._singleRealTransform2(B,z,Y,me>>>1,ce>>>1)}else for(Y=0,_e=0;Y<N;Y+=xe,++_e){const me=L[_e];this._singleRealTransform4(B,z,Y,me>>>1,ce>>>1,j)}const Se=this.table;for(ce>>=2;ce>=2;ce>>=2){xe=N/ce<<1;const me=xe>>>1,X=me>>>1,ie=X>>>1;for(Y=0;Y<N;Y+=xe)for(let Me=0,Q=0;Me<=ie;Me+=2,Q+=ce){const ge=Y+Me,Ke=ge+X,Le=Ke+X,Be=Le+X,We=z[ge],st=z[ge+1],pt=z[Ke],Ge=z[Ke+1],Te=z[Le],je=z[Le+1],Ye=z[Be],et=z[Be+1],A=We,$e=st,Pe=Se[Q],se=j*Se[Q+1],re=pt*Pe-Ge*se,ye=pt*se+Ge*Pe,R=Se[2*Q],ee=j*Se[2*Q+1],D=Te*R-je*ee,ue=Te*ee+je*R,le=Se[3*Q],ke=j*Se[3*Q+1],Ne=Ye*le-et*ke,dt=Ye*ke+et*le,Je=A+D,Ve=$e+ue,Z=A-D,ve=$e-ue,Re=re+Ne,qe=ye+dt,Qe=j*(re-Ne),tt=j*(ye-dt);if(z[ge]=Je+Re,z[ge+1]=Ve+qe,z[Ke]=Z+tt,z[Ke+1]=ve-Qe,Me===0){z[Le]=Je-Re,z[Le+1]=Ve-qe;continue}if(Me===ie)continue;const ft=Y+X-Me,ht=Y+me-Me;z[ft]=Z-j*tt,z[ft+1]=-ve-j*Qe,z[ht]=Je-j*Re,z[ht+1]=-Ve+j*qe}}const Xe=N>>>1;for(let me=2;me<Xe;me+=2)z[N-me]=z[me],z[N-me+1]=-z[me+1]}_singleRealTransform2(z,B,j,N,ae){const ce=z[N],xe=z[N+ae];B[j]=ce+xe,B[j+1]=0,B[j+2]=ce-xe,B[j+3]=0}_singleRealTransform4(z,B,j,N,ae,ce){const xe=ae*2,Y=ae*3,_e=z[N],L=z[N+ae],Se=z[N+xe],Xe=z[N+Y],me=_e+Se,X=_e-Se,ie=L+Xe,Me=ce*(L-Xe);B[j]=me+ie,B[j+1]=0,B[j+2]=X,B[j+3]=-Me,B[j+4]=me-ie,B[j+5]=0,B[j+6]=X,B[j+7]=Me}}class O{constructor(z){const B=2*(z-1),j=2*(2*z-1),N=2**Math.ceil(Math.log2(j));this.bufferSize=N,this._a=B;const ae=new Float64Array(j),ce=new Float64Array(N);this._chirpBuffer=new Float64Array(N),this._buffer1=new Float64Array(N),this._buffer2=new Float64Array(N),this._outBuffer1=new Float64Array(N),this._outBuffer2=new Float64Array(N);const xe=-2*Math.PI/z,Y=Math.cos(xe),_e=Math.sin(xe);for(let L=0;L<j>>1;++L){const Se=(L+1-z)**2/2,Xe=Math.sqrt(Y**2+_e**2)**Se,me=Se*Math.atan2(_e,Y),X=2*L;ae[X]=Xe*Math.cos(me),ae[X+1]=Xe*Math.sin(me),ce[X]=ae[X],ce[X+1]=-ae[X+1]}this._slicedChirpBuffer=ae.subarray(B,j),this._f=new T(N>>1),this._f.transform(this._chirpBuffer,ce)}_transform(z,B,j){const N=this._buffer1,ae=this._buffer2,ce=this._outBuffer1,xe=this._outBuffer2,Y=this._chirpBuffer,_e=this._slicedChirpBuffer,L=this._a;if(j)for(let Se=0;Se<_e.length;Se+=2){const Xe=Se+1,me=Se>>1,X=B[me];N[Se]=X*_e[Se],N[Xe]=X*_e[Xe]}else for(let Se=0;Se<_e.length;Se+=2){const Xe=Se+1;N[Se]=B[Se]*_e[Se]-B[Xe]*_e[Xe],N[Xe]=B[Se]*_e[Xe]+B[Xe]*_e[Se]}this._f.transform(ce,N);for(let Se=0;Se<Y.length;Se+=2){const Xe=Se+1;ae[Se]=ce[Se]*Y[Se]-ce[Xe]*Y[Xe],ae[Xe]=ce[Se]*Y[Xe]+ce[Xe]*Y[Se]}this._f.inverseTransform(xe,ae);for(let Se=0;Se<xe.length;Se+=2){const Xe=xe[Se+L],me=xe[Se+L+1],X=_e[Se],ie=_e[Se+1];z[Se]=Xe*X-me*ie,z[Se+1]=Xe*ie+me*X}}transform(z,B){this._transform(z,B,!1)}realTransform(z,B){this._transform(z,B,!0)}}class S{constructor(z){this.fft_length=z,this.isPowerOfTwo=E(z),this.isPowerOfTwo?(this.fft=new T(z),this.outputBufferSize=2*z):(this.fft=new O(z),this.outputBufferSize=this.fft.bufferSize)}realTransform(z,B){this.fft.realTransform(z,B)}transform(z,B){this.fft.transform(z,B)}}function C(U,z){if(z%2===0||z<=0)throw new Error("Window size must be a positive odd number");const B=new U.constructor(U.length),j=new U.constructor(z),N=Math.floor(z/2);for(let ae=0;ae<U.length;++ae){let ce=0;for(let xe=-N;xe<=N;++xe){let Y=ae+xe;Y<0?Y=Math.abs(Y):Y>=U.length&&(Y=2*(U.length-1)-Y),j[ce++]=U[Y]}j.sort(),B[ae]=j[N]}return B}function w(U,z){const B=Math.pow(10,z);return Math.round(U*B)/B}function b(U){const z=Math.round(U);return Math.abs(U)%1===.5?z%2===0?z:z-1:z}function I(U){const z=U.length,B=U[0].length,j=[z+1,B+1],N=Array.from({length:j[0]},()=>Array(j[1]).fill(1/0));N[0][0]=0;const ae=Array.from({length:j[0]},()=>Array(j[1]).fill(-1));for(let L=1;L<j[1];++L)for(let Se=1;Se<j[0];++Se){const Xe=N[Se-1][L-1],me=N[Se-1][L],X=N[Se][L-1];let ie,Me;Xe<me&&Xe<X?(ie=Xe,Me=0):me<Xe&&me<X?(ie=me,Me=1):(ie=X,Me=2),N[Se][L]=U[Se-1][L-1]+ie,ae[Se][L]=Me}for(let L=0;L<j[1];++L)ae[0][L]=2;for(let L=0;L<j[0];++L)ae[L][0]=1;let ce=z,xe=B,Y=[],_e=[];for(;ce>0||xe>0;)switch(Y.push(ce-1),_e.push(xe-1),ae[ce][xe]){case 0:--ce,--xe;break;case 1:--ce;break;case 2:--xe;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ce}, ${xe}]. Please file a bug report.`)}return Y.reverse(),_e.reverse(),[Y,_e]}},"./src/utils/tensor.js":(e,t,r)=>{r.r(t),r.d(t,{Tensor:()=>_,cat:()=>U,full:()=>ce,full_like:()=>xe,interpolate:()=>M,interpolate_4d:()=>y,layer_norm:()=>C,matmul:()=>E,mean:()=>j,mean_pooling:()=>S,ones:()=>Y,ones_like:()=>_e,permute:()=>g,quantize_embeddings:()=>Xe,rfft:()=>T,stack:()=>z,std_mean:()=>B,topk:()=>O,zeros:()=>L,zeros_like:()=>Se});var o=r("./src/utils/maths.js"),a=r("./src/backends/onnx.js"),l=r("./src/ops/registry.js");const p=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(...X){He(this,"ort_tensor");return(0,a.isONNXTensor)(X[0])?this.ort_tensor=X[0]:this.ort_tensor=new a.Tensor(X[0],X[1],X[2]),new Proxy(this,{get:(ie,Me)=>{if(typeof Me=="string"){let Q=Number(Me);if(Number.isInteger(Q))return ie._getitem(Q)}return ie[Me]},set:(ie,Me,Q)=>ie[Me]=Q})}get dims(){return this.ort_tensor.dims}set dims(X){this.ort_tensor.dims=X}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[X,...ie]=this.dims;if(ie.length>0){const Me=ie.reduce((Q,ge)=>Q*ge);for(let Q=0;Q<X;++Q)yield this._subarray(Q,Me,ie)}else yield*this.data}_getitem(X){const[ie,...Me]=this.dims;if(X=I(X,ie),Me.length>0){const Q=Me.reduce((ge,Ke)=>ge*Ke);return this._subarray(X,Q,Me)}else return new _(this.type,[this.data[X]],Me)}indexOf(X){const ie=this.data;for(let Me=0;Me<ie.length;++Me)if(ie[Me]==X)return Me;return-1}_subarray(X,ie,Me){const Q=X*ie,ge=(X+1)*ie,Ke="subarray"in this.data?this.data.subarray(Q,ge):this.data.slice(Q,ge);return new _(this.type,Ke,Me)}item(){const X=this.data;if(X.length!==1)throw new Error(`a Tensor with ${X.length} elements cannot be converted to Scalar`);return X[0]}tolist(){return h(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const X=this.data;for(let ie=0;ie<X.length;++ie)X[ie]=1/(1+Math.exp(-X[ie]));return this}mul(X){return this.clone().mul_(X)}mul_(X){const ie=this.data;for(let Me=0;Me<ie.length;++Me)ie[Me]*=X;return this}div(X){return this.clone().div_(X)}div_(X){const ie=this.data;for(let Me=0;Me<ie.length;++Me)ie[Me]/=X;return this}add(X){return this.clone().add_(X)}add_(X){const ie=this.data;for(let Me=0;Me<ie.length;++Me)ie[Me]+=X;return this}clone(){return new _(this.type,this.data.slice(),this.dims.slice())}slice(...X){const ie=[],Me=[];for(let We=0;We<this.dims.length;++We){let st=X[We];if(st==null)Me.push([0,this.dims[We]]),ie.push(this.dims[We]);else if(typeof st=="number")st=I(st,this.dims[We],We),Me.push([st,st+1]);else if(Array.isArray(st)&&st.length===2){let[pt,Ge]=st;if(pt=pt===null?0:I(pt,this.dims[We],We,!1),Ge=Ge===null?this.dims[We]:I(Ge,this.dims[We],We,!1),pt>Ge)throw new Error(`Invalid slice: ${st}`);const Te=[Math.max(pt,0),Math.min(Ge,this.dims[We])];Me.push(Te),ie.push(Te[1]-Te[0])}else throw new Error(`Invalid slice: ${st}`)}const Q=Me.map(([We,st])=>st-We),ge=Q.reduce((We,st)=>We*st),Ke=this.data,Le=new Ke.constructor(ge),Be=this.stride();for(let We=0;We<ge;++We){let st=0;for(let pt=Q.length-1,Ge=We;pt>=0;--pt){const Te=Q[pt];st+=(Ge%Te+Me[pt][0])*Be[pt],Ge=Math.floor(Ge/Te)}Le[We]=Ke[st]}return new _(this.type,Le,ie)}permute(...X){return g(this,X)}transpose(...X){return this.permute(...X)}sum(X=null,ie=!1){return this.norm(1,X,ie)}norm(X="fro",ie=null,Me=!1){if(X==="fro")X=2;else if(typeof X=="string")throw Error(`Unsupported norm: ${X}`);const Q=this.data;if(ie===null){let Le=Q.reduce((Be,We)=>Be+We**X,0)**(1/X);return new _(this.type,[Le],[])}ie=I(ie,this.dims.length);const ge=this.dims.slice();ge[ie]=1;const Ke=new Q.constructor(Q.length/this.dims[ie]);for(let Le=0;Le<Q.length;++Le){let Be=0;for(let We=this.dims.length-1,st=Le,pt=1;We>=0;--We){const Ge=this.dims[We];if(We!==ie){const Te=st%Ge;Be+=Te*pt,pt*=ge[We]}st=Math.floor(st/Ge)}Ke[Be]+=Q[Le]**X}if(X!==1)for(let Le=0;Le<Ke.length;++Le)Ke[Le]=Ke[Le]**(1/X);return Me||ge.splice(ie,1),new _(this.type,Ke,ge)}normalize_(X=2,ie=1){ie=I(ie,this.dims.length);const Me=this.norm(X,ie,!0),Q=this.data,ge=Me.data;for(let Ke=0;Ke<Q.length;++Ke){let Le=0;for(let Be=this.dims.length-1,We=Ke,st=1;Be>=0;--Be){const pt=this.dims[Be];if(Be!==ie){const Ge=We%pt;Le+=Ge*st,st*=this.dims[Be]}We=Math.floor(We/pt)}Q[Ke]/=ge[Le]}return this}normalize(X=2,ie=1){return this.clone().normalize_(X,ie)}stride(){return N(this.dims)}squeeze(X=null){return new _(this.type,this.data,w(this.dims,X))}squeeze_(X=null){return this.dims=w(this.dims,X),this}unsqueeze(X=null){return new _(this.type,this.data,b(this.dims,X))}unsqueeze_(X=null){return this.dims=b(this.dims,X),this}flatten_(X=0,ie=-1){ie=(ie+this.dims.length)%this.dims.length;let Me=this.dims.slice(0,X),Q=this.dims.slice(X,ie+1),ge=this.dims.slice(ie+1);return this.dims=[...Me,Q.reduce((Ke,Le)=>Ke*Le,1),...ge],this}flatten(X=0,ie=-1){return this.clone().flatten_(X,ie)}view(...X){let ie=-1;for(let Q=0;Q<X.length;++Q)if(X[Q]===-1){if(ie!==-1)throw new Error("Only one dimension can be inferred");ie=Q}const Me=this.data;if(ie!==-1){const Q=X.reduce((ge,Ke,Le)=>Le!==ie?ge*Ke:ge,1);X[ie]=Me.length/Q}return new _(this.type,Me,X)}neg_(){const X=this.data;for(let ie=0;ie<X.length;++ie)X[ie]=-X[ie];return this}neg(){return this.clone().neg_()}clamp_(X,ie){const Me=this.data;for(let Q=0;Q<Me.length;++Q)Me[Q]=Math.min(Math.max(Me[Q],X),ie);return this}clamp(X,ie){return this.clone().clamp_(X,ie)}round_(){const X=this.data;for(let ie=0;ie<X.length;++ie)X[ie]=Math.round(X[ie]);return this}round(){return this.clone().round_()}mean(X=null,ie=!1){return j(this,X,ie)}to(X){if(this.type===X)return this;if(!p.hasOwnProperty(X))throw new Error(`Unsupported type: ${X}`);return new _(X,p[X].from(this.data),this.dims)}}function h(me,X){const ie=me.length,Me=X.reduce((ge,Ke)=>ge*Ke);if(ie!==Me)throw Error(`cannot reshape array of size ${ie} into shape (${X})`);let Q=me;for(let ge=X.length-1;ge>=0;ge--)Q=Q.reduce((Ke,Le)=>{let Be=Ke[Ke.length-1];return Be.length<X[ge]?Be.push(Le):Ke.push([Le]),Ke},[[]]);return Q[0]}function g(me,X){const[ie,Me]=(0,o.permute_data)(me.data,me.dims,X);return new _(me.type,ie,Me)}function M(me,[X,ie],Me="bilinear",Q=!1){const ge=me.dims.at(-3)??1,Ke=me.dims.at(-2),Le=me.dims.at(-1);let Be=(0,o.interpolate_data)(me.data,[ge,Ke,Le],[X,ie],Me,Q);return new _(me.type,Be,[ge,X,ie])}async function y(me,{size:X=null,mode:ie="bilinear"}={}){if(me.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!X)throw new Error("`interpolate_4d` requires a `size` argument.");let Me;if(X.length===2)Me=[...me.dims.slice(0,2),...X];else if(X.length===3)Me=[me.dims[0],...X];else if(X.length===4)Me=X;else throw new Error("`size` must be of length 2, 3, or 4.");let Q;if(ie==="bilinear")Q=await l.TensorOpRegistry.bilinear_interpolate_4d;else if(ie==="bicubic")Q=await l.TensorOpRegistry.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${ie}`);const ge=new _("int64",new BigInt64Array(Me.map(BigInt)),[Me.length]);return await Q({x:me,s:ge})}async function E(me,X){return await(await l.TensorOpRegistry.matmul)({a:me,b:X})}async function T(me,X){return await(await l.TensorOpRegistry.rfft)({x:me,a:X})}async function O(me,X){const ie=await l.TensorOpRegistry.top_k;return X===null?X=me.dims.at(-1):X=Math.min(X,me.dims.at(-1)),await ie({x:me,k:new _("int64",[BigInt(X)],[1])})}function S(me,X){const ie=me.data,Me=X.data,Q=[me.dims[0],me.dims[2]],ge=new ie.constructor(Q[0]*Q[1]),[Ke,Le,Be]=me.dims;let We=0;for(let st=0;st<Ke;++st){const pt=st*Be*Le;for(let Ge=0;Ge<Be;++Ge){let Te=0,je=0;const Ye=st*Le,et=pt+Ge;for(let $e=0;$e<Le;++$e){const Pe=Number(Me[Ye+$e]);je+=Pe,Te+=ie[et+$e*Be]*Pe}const A=Te/je;ge[We++]=A}}return new _(me.type,ge,Q)}function C(me,X,{eps:ie=1e-5}={}){if(me.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");const[Me,Q]=me.dims;if(X.length!==1&&X[0]!==Q)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");const[ge,Ke]=B(me,1,0,!0),Le=ge.data,Be=Ke.data,We=me.data,st=new We.constructor(We.length);for(let pt=0;pt<Me;++pt){const Ge=pt*Q;for(let Te=0;Te<Q;++Te){const je=Ge+Te;st[je]=(We[je]-Be[pt])/(Le[pt]+ie)}}return new _(me.type,st,me.dims)}function w(me,X){return me=me.slice(),X===null?me=me.filter(ie=>ie!==1):typeof X=="number"?me[X]===1&&me.splice(X,1):Array.isArray(X)&&(me=me.filter((ie,Me)=>ie!==1||!X.includes(Me))),me}function b(me,X){return X=I(X,me.length+1),me=me.slice(),me.splice(X,0,1),me}function I(me,X,ie=null,Me=!0){if(Me&&(me<-X||me>=X))throw new Error(`IndexError: index ${me} is out of bounds for dimension${ie===null?"":" "+ie} with size ${X}`);return me<0&&(me=(me%X+X)%X),me}function U(me,X=0){X=I(X,me[0].dims.length);const ie=me[0].dims.slice();ie[X]=me.reduce((Ke,Le)=>Ke+Le.dims[X],0);const Me=ie.reduce((Ke,Le)=>Ke*Le,1),Q=new me[0].data.constructor(Me),ge=me[0].type;if(X===0){let Ke=0;for(const Le of me){const Be=Le.data;Q.set(Be,Ke),Ke+=Be.length}}else{let Ke=0;for(let Le=0;Le<me.length;++Le){const{data:Be,dims:We}=me[Le];for(let st=0;st<Be.length;++st){let pt=0;for(let Ge=We.length-1,Te=st,je=1;Ge>=0;--Ge){const Ye=We[Ge];let et=Te%Ye;Ge===X&&(et+=Ke),pt+=et*je,je*=ie[Ge],Te=Math.floor(Te/Ye)}Q[pt]=Be[st]}Ke+=We[X]}}return new _(ge,Q,ie)}function z(me,X=0){return U(me.map(ie=>ie.unsqueeze(X)),X)}function B(me,X=null,ie=1,Me=!1){const Q=me.data,ge=me.dims;if(X===null){const Ge=Q.reduce((et,A)=>et+A,0)/Q.length,Te=Math.sqrt(Q.reduce((et,A)=>et+(A-Ge)**2,0)/(Q.length-ie)),je=new _(me.type,[Ge],[]);return[new _(me.type,[Te],[]),je]}X=I(X,ge.length);const Ke=j(me,X,Me),Le=Ke.data,Be=ge.slice();Be[X]=1;const We=new Q.constructor(Q.length/ge[X]);for(let pt=0;pt<Q.length;++pt){let Ge=0;for(let Te=ge.length-1,je=pt,Ye=1;Te>=0;--Te){const et=ge[Te];if(Te!==X){const A=je%et;Ge+=A*Ye,Ye*=Be[Te]}je=Math.floor(je/et)}We[Ge]+=(Q[pt]-Le[Ge])**2}for(let pt=0;pt<We.length;++pt)We[pt]=Math.sqrt(We[pt]/(ge[X]-ie));return Me||Be.splice(X,1),[new _(me.type,We,Be),Ke]}function j(me,X=null,ie=!1){const Me=me.data;if(X===null){const Le=Me.reduce((Be,We)=>Be+We,0);return new _(me.type,[Le/Me.length],[])}const Q=me.dims;X=I(X,Q.length);const ge=Q.slice();ge[X]=1;const Ke=new Me.constructor(Me.length/Q[X]);for(let Le=0;Le<Me.length;++Le){let Be=0;for(let We=Q.length-1,st=Le,pt=1;We>=0;--We){const Ge=Q[We];if(We!==X){const Te=st%Ge;Be+=Te*pt,pt*=ge[We]}st=Math.floor(st/Ge)}Ke[Be]+=Me[Le]}if(Q[X]!==1)for(let Le=0;Le<Ke.length;++Le)Ke[Le]=Ke[Le]/Q[X];return ie||ge.splice(X,1),new _(me.type,Ke,ge)}function N(me){const X=new Array(me.length);for(let ie=me.length-1,Me=1;ie>=0;--ie)X[ie]=Me,Me*=me[ie];return X}function ae(me,X,ie,Me){const Q=me.reduce((ge,Ke)=>ge*Ke,1);return new _(ie,new Me(Q).fill(X),me)}function ce(me,X){let ie,Me;if(typeof X=="number")ie="float32",Me=Float32Array;else if(typeof X=="bigint")ie="int64",Me=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof X}`);return ae(me,X,ie,Me)}function xe(me,X){return ce(me.dims,X)}function Y(me){return ae(me,1n,"int64",BigInt64Array)}function _e(me){return Y(me.dims)}function L(me){return ae(me,0n,"int64",BigInt64Array)}function Se(me){return L(me.dims)}function Xe(me,X){if(me.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(me.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(X))throw new Error("The precision must be either 'binary' or 'ubinary'");const ie=X==="binary",Me=ie?"int8":"uint8",Q=ie?Int8Array:Uint8Array,ge=me.data,Ke=new Q(ge.length/8);for(let Le=0;Le<ge.length;++Le){const Be=ge[Le]>0?1:0,We=Math.floor(Le/8),st=Le%8;Ke[We]|=Be<<7-st,ie&&st===0&&(Ke[We]-=128)}return new _(Me,Ke,[me.dims[0],me.dims[1]/8])}}},M1={};function en(e){var t=M1[e];if(t!==void 0)return t.exports;var r=M1[e]={exports:{}};return uE[e](r,r.exports,en),r.exports}(()=>{var e=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,t;en.t=function(r,o){if(o&1&&(r=this(r)),o&8||typeof r=="object"&&r&&(o&4&&r.__esModule||o&16&&typeof r.then=="function"))return r;var a=Object.create(null);en.r(a);var l={};t=t||[null,e({}),e([]),e(e)];for(var p=o&2&&r;typeof p=="object"&&!~t.indexOf(p);p=e(p))Object.getOwnPropertyNames(p).forEach(_=>l[_]=()=>r[_]);return l.default=()=>r,en.d(a,l),a}})();en.d=(e,t)=>{for(var r in t)en.o(t,r)&&!en.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})};en.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);en.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(/\/[^\/]+$/,"/"),en.p=e})();en.b=void 0;var P={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/en.r(P),en.d(P,{ASTFeatureExtractor:()=>a.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>o.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>l.AutoConfig,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>a.AutoProcessor,AutoTokenizer:()=>o.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>o.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>M.BaseStreamer,BeitFeatureExtractor:()=>a.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>o.BertTokenizer,BitImageProcessor:()=>a.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>o.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>o.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>o.BloomTokenizer,CLIPFeatureExtractor:()=>a.CLIPFeatureExtractor,CLIPImageProcessor:()=>a.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>o.CLIPTokenizer,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>o.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>a.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>a.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>o.CodeGenTokenizer,CodeLlamaTokenizer:()=>o.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>o.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>o.ConvBertTokenizer,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>a.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>a.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>o.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>o.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>a.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DetrFeatureExtractor:()=>a.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>o.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>a.DonutFeatureExtractor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>a.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>o.ElectraTokenizer,EosTokenCriteria:()=>y.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>o.EsmTokenizer,FFT:()=>g.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>o.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>a.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>a.Florence2Processor,GLPNFeatureExtractor:()=>a.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>o.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>o.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>o.GemmaTokenizer,Grok1Tokenizer:()=>o.Grok1Tokenizer,HerbertTokenizer:()=>o.HerbertTokenizer,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>a.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>y.InterruptableStoppingCriteria,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>o.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>o.M2M100Tokenizer,MBart50Tokenizer:()=>o.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>o.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>o.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>o.MarianTokenizer,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>y.MaxLengthCriteria,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>o.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>a.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>a.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>a.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>a.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>a.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>a.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>o.NllbTokenizer,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>a.NougatImageProcessor,NougatTokenizer:()=>o.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>a.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>a.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>a.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>o.PreTrainedTokenizer,PretrainedConfig:()=>l.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>a.Processor,PyAnnoteFeatureExtractor:()=>a.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>a.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>o.Qwen2Tokenizer,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>a.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>_.RawImage,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>o.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>o.RobertaTokenizer,SamImageProcessor:()=>a.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>a.SamProcessor,SeamlessM4TFeatureExtractor:()=>a.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>a.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>a.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>o.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>a.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>a.SpeechT5Processor,SpeechT5Tokenizer:()=>o.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>o.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>y.StoppingCriteria,StoppingCriteriaList:()=>y.StoppingCriteriaList,SummarizationPipeline:()=>t.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>a.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>o.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,Tensor:()=>h.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>M.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>o.TokenizerModel,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>a.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>a.ViTImageProcessor,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>a.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>o.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>o.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>a.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>a.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>a.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>a.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>a.WhisperProcessor,WhisperTextStreamer:()=>M.WhisperTextStreamer,WhisperTokenizer:()=>o.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>o.XLMRobertaTokenizer,XLMTokenizer:()=>o.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>a.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.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:()=>p.hamming,hanning:()=>p.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:()=>p.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:()=>p.read_audio,rfft:()=>h.rfft,round:()=>g.round,softmax:()=>g.softmax,spectrogram:()=>p.spectrogram,stack:()=>h.stack,std_mean:()=>h.std_mean,topk:()=>h.topk,window_function:()=>p.window_function,zeros:()=>h.zeros,zeros_like:()=>h.zeros_like});var e=en("./src/env.js"),t=en("./src/pipelines.js"),r=en("./src/models.js"),o=en("./src/tokenizers.js"),a=en("./src/processors.js"),l=en("./src/configs.js"),p=en("./src/utils/audio.js"),_=en("./src/utils/image.js"),h=en("./src/utils/tensor.js"),g=en("./src/utils/maths.js"),M=en("./src/generation/streamers.js"),y=en("./src/generation/stopping_criteria.js")})();P.ASTFeatureExtractor;P.ASTForAudioClassification;P.ASTModel;P.ASTPreTrainedModel;P.AlbertForMaskedLM;P.AlbertForQuestionAnswering;P.AlbertForSequenceClassification;P.AlbertModel;P.AlbertPreTrainedModel;P.AlbertTokenizer;P.AudioClassificationPipeline;P.AutoConfig;var cE=P.AutoModel;P.AutoModelForAudioClassification;P.AutoModelForAudioFrameClassification;P.AutoModelForCTC;P.AutoModelForCausalLM;P.AutoModelForDepthEstimation;P.AutoModelForDocumentQuestionAnswering;P.AutoModelForImageClassification;P.AutoModelForImageFeatureExtraction;P.AutoModelForImageMatting;P.AutoModelForImageSegmentation;P.AutoModelForImageToImage;P.AutoModelForMaskGeneration;P.AutoModelForMaskedLM;P.AutoModelForObjectDetection;P.AutoModelForQuestionAnswering;P.AutoModelForSemanticSegmentation;P.AutoModelForSeq2SeqLM;P.AutoModelForSequenceClassification;P.AutoModelForSpeechSeq2Seq;P.AutoModelForTextToSpectrogram;P.AutoModelForTextToWaveform;P.AutoModelForTokenClassification;P.AutoModelForVision2Seq;P.AutoModelForXVector;P.AutoModelForZeroShotObjectDetection;var dE=P.AutoProcessor;P.AutoTokenizer;P.AutomaticSpeechRecognitionPipeline;P.BartForConditionalGeneration;P.BartForSequenceClassification;P.BartModel;P.BartPretrainedModel;P.BartTokenizer;P.BaseModelOutput;P.BaseStreamer;P.BeitFeatureExtractor;P.BeitForImageClassification;P.BeitModel;P.BeitPreTrainedModel;P.BertForMaskedLM;P.BertForQuestionAnswering;P.BertForSequenceClassification;P.BertForTokenClassification;P.BertModel;P.BertPreTrainedModel;P.BertTokenizer;P.BitImageProcessor;P.BlenderbotForConditionalGeneration;P.BlenderbotModel;P.BlenderbotPreTrainedModel;P.BlenderbotSmallForConditionalGeneration;P.BlenderbotSmallModel;P.BlenderbotSmallPreTrainedModel;P.BlenderbotSmallTokenizer;P.BlenderbotTokenizer;P.BloomForCausalLM;P.BloomModel;P.BloomPreTrainedModel;P.BloomTokenizer;P.CLIPFeatureExtractor;P.CLIPImageProcessor;P.CLIPModel;P.CLIPPreTrainedModel;P.CLIPSegForImageSegmentation;P.CLIPSegModel;P.CLIPSegPreTrainedModel;P.CLIPTextModelWithProjection;P.CLIPTokenizer;P.CLIPVisionModelWithProjection;P.CamembertForMaskedLM;P.CamembertForQuestionAnswering;P.CamembertForSequenceClassification;P.CamembertForTokenClassification;P.CamembertModel;P.CamembertPreTrainedModel;P.CamembertTokenizer;P.CausalLMOutput;P.CausalLMOutputWithPast;P.ChineseCLIPFeatureExtractor;P.ChineseCLIPModel;P.ChineseCLIPPreTrainedModel;P.ClapAudioModelWithProjection;P.ClapFeatureExtractor;P.ClapModel;P.ClapPreTrainedModel;P.ClapTextModelWithProjection;P.CodeGenForCausalLM;P.CodeGenModel;P.CodeGenPreTrainedModel;P.CodeGenTokenizer;P.CodeLlamaTokenizer;P.CohereForCausalLM;P.CohereModel;P.CoherePreTrainedModel;P.CohereTokenizer;P.ConvBertForMaskedLM;P.ConvBertForQuestionAnswering;P.ConvBertForSequenceClassification;P.ConvBertForTokenClassification;P.ConvBertModel;P.ConvBertPreTrainedModel;P.ConvBertTokenizer;P.ConvNextFeatureExtractor;P.ConvNextForImageClassification;P.ConvNextImageProcessor;P.ConvNextModel;P.ConvNextPreTrainedModel;P.ConvNextV2ForImageClassification;P.ConvNextV2Model;P.ConvNextV2PreTrainedModel;P.DPTFeatureExtractor;P.DPTForDepthEstimation;P.DPTImageProcessor;P.DPTModel;P.DPTPreTrainedModel;P.DebertaForMaskedLM;P.DebertaForQuestionAnswering;P.DebertaForSequenceClassification;P.DebertaForTokenClassification;P.DebertaModel;P.DebertaPreTrainedModel;P.DebertaTokenizer;P.DebertaV2ForMaskedLM;P.DebertaV2ForQuestionAnswering;P.DebertaV2ForSequenceClassification;P.DebertaV2ForTokenClassification;P.DebertaV2Model;P.DebertaV2PreTrainedModel;P.DebertaV2Tokenizer;P.DeiTFeatureExtractor;P.DeiTForImageClassification;P.DeiTModel;P.DeiTPreTrainedModel;P.DepthAnythingForDepthEstimation;P.DepthAnythingPreTrainedModel;P.DepthEstimationPipeline;P.DetrFeatureExtractor;P.DetrForObjectDetection;P.DetrForSegmentation;P.DetrModel;P.DetrObjectDetectionOutput;P.DetrPreTrainedModel;P.DetrSegmentationOutput;P.Dinov2ForImageClassification;P.Dinov2Model;P.Dinov2PreTrainedModel;P.DistilBertForMaskedLM;P.DistilBertForQuestionAnswering;P.DistilBertForSequenceClassification;P.DistilBertForTokenClassification;P.DistilBertModel;P.DistilBertPreTrainedModel;P.DistilBertTokenizer;P.DocumentQuestionAnsweringPipeline;P.DonutFeatureExtractor;P.DonutSwinModel;P.DonutSwinPreTrainedModel;P.EfficientNetForImageClassification;P.EfficientNetImageProcessor;P.EfficientNetModel;P.EfficientNetPreTrainedModel;P.ElectraForMaskedLM;P.ElectraForQuestionAnswering;P.ElectraForSequenceClassification;P.ElectraForTokenClassification;P.ElectraModel;P.ElectraPreTrainedModel;P.ElectraTokenizer;P.EosTokenCriteria;P.EsmForMaskedLM;P.EsmForSequenceClassification;P.EsmForTokenClassification;P.EsmModel;P.EsmPreTrainedModel;P.EsmTokenizer;P.FFT;P.FalconForCausalLM;P.FalconModel;P.FalconPreTrainedModel;P.FalconTokenizer;P.FastViTForImageClassification;P.FastViTModel;P.FastViTPreTrainedModel;P.FeatureExtractionPipeline;P.FeatureExtractor;P.FillMaskPipeline;P.Florence2ForConditionalGeneration;P.Florence2PreTrainedModel;P.Florence2Processor;P.GLPNFeatureExtractor;P.GLPNForDepthEstimation;P.GLPNModel;P.GLPNPreTrainedModel;P.GPT2LMHeadModel;P.GPT2Model;P.GPT2PreTrainedModel;P.GPT2Tokenizer;P.GPTBigCodeForCausalLM;P.GPTBigCodeModel;P.GPTBigCodePreTrainedModel;P.GPTJForCausalLM;P.GPTJModel;P.GPTJPreTrainedModel;P.GPTNeoForCausalLM;P.GPTNeoModel;P.GPTNeoPreTrainedModel;P.GPTNeoXForCausalLM;P.GPTNeoXModel;P.GPTNeoXPreTrainedModel;P.GPTNeoXTokenizer;P.Gemma2ForCausalLM;P.Gemma2Model;P.Gemma2PreTrainedModel;P.GemmaForCausalLM;P.GemmaModel;P.GemmaPreTrainedModel;P.GemmaTokenizer;P.Grok1Tokenizer;P.HerbertTokenizer;P.HubertForCTC;P.HubertForSequenceClassification;P.HubertModel;P.HubertPreTrainedModel;P.ImageClassificationPipeline;P.ImageFeatureExtractionPipeline;P.ImageFeatureExtractor;P.ImageMattingOutput;P.ImageSegmentationPipeline;P.ImageToImagePipeline;P.ImageToTextPipeline;P.InterruptableStoppingCriteria;P.LlamaForCausalLM;P.LlamaModel;P.LlamaPreTrainedModel;P.LlamaTokenizer;P.LlavaForConditionalGeneration;P.LlavaPreTrainedModel;P.LongT5ForConditionalGeneration;P.LongT5Model;P.LongT5PreTrainedModel;P.M2M100ForConditionalGeneration;P.M2M100Model;P.M2M100PreTrainedModel;P.M2M100Tokenizer;P.MBart50Tokenizer;P.MBartForCausalLM;P.MBartForConditionalGeneration;P.MBartForSequenceClassification;P.MBartModel;P.MBartPreTrainedModel;P.MBartTokenizer;P.MPNetForMaskedLM;P.MPNetForQuestionAnswering;P.MPNetForSequenceClassification;P.MPNetForTokenClassification;P.MPNetModel;P.MPNetPreTrainedModel;P.MPNetTokenizer;P.MT5ForConditionalGeneration;P.MT5Model;P.MT5PreTrainedModel;P.MarianMTModel;P.MarianModel;P.MarianPreTrainedModel;P.MarianTokenizer;P.MaskedLMOutput;P.MaxLengthCriteria;P.MistralForCausalLM;P.MistralModel;P.MistralPreTrainedModel;P.MobileBertForMaskedLM;P.MobileBertForQuestionAnswering;P.MobileBertForSequenceClassification;P.MobileBertModel;P.MobileBertPreTrainedModel;P.MobileBertTokenizer;P.MobileNetV1FeatureExtractor;P.MobileNetV1ForImageClassification;P.MobileNetV1Model;P.MobileNetV1PreTrainedModel;P.MobileNetV2FeatureExtractor;P.MobileNetV2ForImageClassification;P.MobileNetV2Model;P.MobileNetV2PreTrainedModel;P.MobileNetV3FeatureExtractor;P.MobileNetV3ForImageClassification;P.MobileNetV3Model;P.MobileNetV3PreTrainedModel;P.MobileNetV4FeatureExtractor;P.MobileNetV4ForImageClassification;P.MobileNetV4Model;P.MobileNetV4PreTrainedModel;P.MobileViTFeatureExtractor;P.MobileViTForImageClassification;P.MobileViTImageProcessor;P.MobileViTModel;P.MobileViTPreTrainedModel;P.MobileViTV2ForImageClassification;P.MobileViTV2Model;P.MobileViTV2PreTrainedModel;P.ModelOutput;P.Moondream1ForConditionalGeneration;P.MptForCausalLM;P.MptModel;P.MptPreTrainedModel;P.MusicgenForCausalLM;P.MusicgenForConditionalGeneration;P.MusicgenModel;P.MusicgenPreTrainedModel;P.NllbTokenizer;P.NomicBertModel;P.NomicBertPreTrainedModel;P.NougatImageProcessor;P.NougatTokenizer;P.OPTForCausalLM;P.OPTModel;P.OPTPreTrainedModel;P.ObjectDetectionPipeline;P.OpenELMForCausalLM;P.OpenELMModel;P.OpenELMPreTrainedModel;P.OwlViTFeatureExtractor;P.OwlViTForObjectDetection;P.OwlViTModel;P.OwlViTPreTrainedModel;P.OwlViTProcessor;P.Owlv2ForObjectDetection;P.Owlv2ImageProcessor;P.Owlv2Model;P.Owlv2PreTrainedModel;P.Phi3ForCausalLM;P.Phi3Model;P.Phi3PreTrainedModel;P.PhiForCausalLM;P.PhiModel;P.PhiPreTrainedModel;P.Pipeline;P.PreTrainedModel;P.PreTrainedTokenizer;P.PretrainedConfig;P.PretrainedMixin;P.Processor;P.PyAnnoteFeatureExtractor;P.PyAnnoteForAudioFrameClassification;P.PyAnnoteModel;P.PyAnnotePreTrainedModel;P.PyAnnoteProcessor;P.QuestionAnsweringModelOutput;P.QuestionAnsweringPipeline;P.Qwen2ForCausalLM;P.Qwen2Model;P.Qwen2PreTrainedModel;P.Qwen2Tokenizer;P.RTDetrForObjectDetection;P.RTDetrImageProcessor;P.RTDetrModel;P.RTDetrObjectDetectionOutput;P.RTDetrPreTrainedModel;var T1=P.RawImage;P.ResNetForImageClassification;P.ResNetModel;P.ResNetPreTrainedModel;P.RoFormerForMaskedLM;P.RoFormerForQuestionAnswering;P.RoFormerForSequenceClassification;P.RoFormerForTokenClassification;P.RoFormerModel;P.RoFormerPreTrainedModel;P.RoFormerTokenizer;P.RobertaForMaskedLM;P.RobertaForQuestionAnswering;P.RobertaForSequenceClassification;P.RobertaForTokenClassification;P.RobertaModel;P.RobertaPreTrainedModel;P.RobertaTokenizer;P.SamImageProcessor;P.SamImageSegmentationOutput;P.SamModel;P.SamPreTrainedModel;P.SamProcessor;P.SeamlessM4TFeatureExtractor;P.SegformerFeatureExtractor;P.SegformerForImageClassification;P.SegformerForSemanticSegmentation;P.SegformerModel;P.SegformerPreTrainedModel;P.Seq2SeqLMOutput;P.SequenceClassifierOutput;P.SiglipImageProcessor;P.SiglipModel;P.SiglipPreTrainedModel;P.SiglipTextModel;P.SiglipTokenizer;P.SiglipVisionModel;P.SpeechT5FeatureExtractor;P.SpeechT5ForSpeechToText;P.SpeechT5ForTextToSpeech;P.SpeechT5HifiGan;P.SpeechT5Model;P.SpeechT5PreTrainedModel;P.SpeechT5Processor;P.SpeechT5Tokenizer;P.SqueezeBertForMaskedLM;P.SqueezeBertForQuestionAnswering;P.SqueezeBertForSequenceClassification;P.SqueezeBertModel;P.SqueezeBertPreTrainedModel;P.SqueezeBertTokenizer;P.StableLmForCausalLM;P.StableLmModel;P.StableLmPreTrainedModel;P.Starcoder2ForCausalLM;P.Starcoder2Model;P.Starcoder2PreTrainedModel;P.StoppingCriteria;P.StoppingCriteriaList;P.SummarizationPipeline;P.Swin2SRForImageSuperResolution;P.Swin2SRImageProcessor;P.Swin2SRModel;P.Swin2SRPreTrainedModel;P.SwinForImageClassification;P.SwinModel;P.SwinPreTrainedModel;P.T5ForConditionalGeneration;P.T5Model;P.T5PreTrainedModel;P.T5Tokenizer;P.TableTransformerForObjectDetection;P.TableTransformerModel;P.TableTransformerObjectDetectionOutput;P.TableTransformerPreTrainedModel;P.Tensor;P.Text2TextGenerationPipeline;P.TextClassificationPipeline;P.TextGenerationPipeline;P.TextStreamer;P.TextToAudioPipeline;P.TokenClassificationPipeline;P.TokenClassifierOutput;P.TokenizerModel;P.TrOCRForCausalLM;P.TrOCRPreTrainedModel;P.TranslationPipeline;P.UniSpeechForCTC;P.UniSpeechForSequenceClassification;P.UniSpeechModel;P.UniSpeechPreTrainedModel;P.UniSpeechSatForAudioFrameClassification;P.UniSpeechSatForCTC;P.UniSpeechSatForSequenceClassification;P.UniSpeechSatModel;P.UniSpeechSatPreTrainedModel;P.ViTFeatureExtractor;P.ViTForImageClassification;P.ViTImageProcessor;P.ViTModel;P.ViTPreTrainedModel;P.VisionEncoderDecoderModel;P.VitMatteForImageMatting;P.VitMatteImageProcessor;P.VitMattePreTrainedModel;P.VitsModel;P.VitsModelOutput;P.VitsPreTrainedModel;P.VitsTokenizer;P.Wav2Vec2BertForCTC;P.Wav2Vec2BertForSequenceClassification;P.Wav2Vec2BertModel;P.Wav2Vec2BertPreTrainedModel;P.Wav2Vec2CTCTokenizer;P.Wav2Vec2FeatureExtractor;P.Wav2Vec2ForAudioFrameClassification;P.Wav2Vec2ForCTC;P.Wav2Vec2ForSequenceClassification;P.Wav2Vec2Model;P.Wav2Vec2PreTrainedModel;P.Wav2Vec2ProcessorWithLM;P.WavLMForAudioFrameClassification;P.WavLMForCTC;P.WavLMForSequenceClassification;P.WavLMForXVector;P.WavLMModel;P.WavLMPreTrainedModel;P.WeSpeakerFeatureExtractor;P.WeSpeakerResNetModel;P.WeSpeakerResNetPreTrainedModel;P.WhisperFeatureExtractor;P.WhisperForConditionalGeneration;P.WhisperModel;P.WhisperPreTrainedModel;P.WhisperProcessor;P.WhisperTextStreamer;P.WhisperTokenizer;P.XLMForQuestionAnswering;P.XLMForSequenceClassification;P.XLMForTokenClassification;P.XLMModel;P.XLMPreTrainedModel;P.XLMRobertaForMaskedLM;P.XLMRobertaForQuestionAnswering;P.XLMRobertaForSequenceClassification;P.XLMRobertaForTokenClassification;P.XLMRobertaModel;P.XLMRobertaPreTrainedModel;P.XLMRobertaTokenizer;P.XLMTokenizer;P.XLMWithLMHeadModel;P.XVectorOutput;P.YolosFeatureExtractor;P.YolosForObjectDetection;P.YolosModel;P.YolosObjectDetectionOutput;P.YolosPreTrainedModel;P.ZeroShotAudioClassificationPipeline;P.ZeroShotClassificationPipeline;P.ZeroShotImageClassificationPipeline;P.ZeroShotObjectDetectionPipeline;P.bankers_round;P.cat;P.cos_sim;P.dot;P.dynamic_time_warping;var pE=P.env;P.full;P.full_like;P.getKeyValueShapes;P.hamming;P.hanning;P.interpolate;P.interpolate_4d;P.interpolate_data;P.is_chinese_char;P.layer_norm;P.log_softmax;P.magnitude;P.matmul;P.max;P.mean;P.mean_pooling;P.medianFilter;P.mel_filter_bank;P.min;P.ones;P.ones_like;P.permute;P.permute_data;P.pipeline;P.quantize_embeddings;P.read_audio;P.rfft;P.round;P.softmax;P.spectrogram;P.stack;P.std_mean;P.topk;P.window_function;P.zeros;P.zeros_like;function ph(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 tx={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(r){e.exports=r()})(function(){return function r(o,a,l){function p(g,M){if(!a[g]){if(!o[g]){var y=typeof ph=="function"&&ph;if(!M&&y)return y(g,!0);if(_)return _(g,!0);var E=new Error("Cannot find module '"+g+"'");throw E.code="MODULE_NOT_FOUND",E}var T=a[g]={exports:{}};o[g][0].call(T.exports,function(O){var S=o[g][1][O];return p(S||O)},T,T.exports,r,o,a,l)}return a[g].exports}for(var _=typeof ph=="function"&&ph,h=0;h<l.length;h++)p(l[h]);return p}({1:[function(r,o,a){var l=r("./utils"),p=r("./support"),_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";a.encode=function(h){for(var g,M,y,E,T,O,S,C=[],w=0,b=h.length,I=b,U=l.getTypeOf(h)!=="string";w<h.length;)I=b-w,y=U?(g=h[w++],M=w<b?h[w++]:0,w<b?h[w++]:0):(g=h.charCodeAt(w++),M=w<b?h.charCodeAt(w++):0,w<b?h.charCodeAt(w++):0),E=g>>2,T=(3&g)<<4|M>>4,O=1<I?(15&M)<<2|y>>6:64,S=2<I?63&y:64,C.push(_.charAt(E)+_.charAt(T)+_.charAt(O)+_.charAt(S));return C.join("")},a.decode=function(h){var g,M,y,E,T,O,S=0,C=0,w="data:";if(h.substr(0,w.length)===w)throw new Error("Invalid base64 input, it looks like a data url.");var b,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(b=p.uint8array?new Uint8Array(0|I):new Array(0|I);S<h.length;)g=_.indexOf(h.charAt(S++))<<2|(E=_.indexOf(h.charAt(S++)))>>4,M=(15&E)<<4|(T=_.indexOf(h.charAt(S++)))>>2,y=(3&T)<<6|(O=_.indexOf(h.charAt(S++))),b[C++]=g,T!==64&&(b[C++]=M),O!==64&&(b[C++]=y);return b}},{"./support":30,"./utils":32}],2:[function(r,o,a){var l=r("./external"),p=r("./stream/DataWorker"),_=r("./stream/Crc32Probe"),h=r("./stream/DataLengthProbe");function g(M,y,E,T,O){this.compressedSize=M,this.uncompressedSize=y,this.crc32=E,this.compression=T,this.compressedContent=O}g.prototype={getContentWorker:function(){var M=new p(l.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new h("data_length")),y=this;return M.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),M},getCompressedWorker:function(){return new p(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,y,E){return M.pipe(new _).pipe(new h("uncompressedSize")).pipe(y.compressWorker(E)).pipe(new h("compressedSize")).withStreamInfo("compression",y)},o.exports=g},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,o,a){var l=r("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new l("STORE compression")},uncompressWorker:function(){return new l("STORE decompression")}},a.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,o,a){var l=r("./utils"),p=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,y,E){var T=p,O=E+y;g^=-1;for(var S=E;S<O;S++)g=g>>>8^T[255&(g^M[S])];return-1^g}(0|h,_,_.length,0):function(g,M,y,E){var T=p,O=E+y;g^=-1;for(var S=E;S<O;S++)g=g>>>8^T[255&(g^M.charCodeAt(S))];return-1^g}(0|h,_,_.length,0):0}},{"./utils":32}],5:[function(r,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(r,o,a){var l=null;l=typeof Promise<"u"?Promise:r("lie"),o.exports={Promise:l}},{lie:37}],7:[function(r,o,a){var l=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",p=r("pako"),_=r("./utils"),h=r("./stream/GenericWorker"),g=l?"uint8array":"array";function M(y,E){h.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=E,this.meta={}}a.magic="\b\0",_.inherits(M,h),M.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(_.transformTo(g,y.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 p[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(E){y.push({data:E,meta:y.meta})}},a.compressWorker=function(y){return new M("Deflate",y)},a.uncompressWorker=function(){return new M("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,o,a){function l(T,O){var S,C="";for(S=0;S<O;S++)C+=String.fromCharCode(255&T),T>>>=8;return C}function p(T,O,S,C,w,b){var I,U,z=T.file,B=T.compression,j=b!==g.utf8encode,N=_.transformTo("string",b(z.name)),ae=_.transformTo("string",g.utf8encode(z.name)),ce=z.comment,xe=_.transformTo("string",b(ce)),Y=_.transformTo("string",g.utf8encode(ce)),_e=ae.length!==z.name.length,L=Y.length!==ce.length,Se="",Xe="",me="",X=z.dir,ie=z.date,Me={crc32:0,compressedSize:0,uncompressedSize:0};O&&!S||(Me.crc32=T.crc32,Me.compressedSize=T.compressedSize,Me.uncompressedSize=T.uncompressedSize);var Q=0;O&&(Q|=8),j||!_e&&!L||(Q|=2048);var ge=0,Ke=0;X&&(ge|=16),w==="UNIX"?(Ke=798,ge|=function(Be,We){var st=Be;return Be||(st=We?16893:33204),(65535&st)<<16}(z.unixPermissions,X)):(Ke=20,ge|=function(Be){return 63&(Be||0)}(z.dosPermissions)),I=ie.getUTCHours(),I<<=6,I|=ie.getUTCMinutes(),I<<=5,I|=ie.getUTCSeconds()/2,U=ie.getUTCFullYear()-1980,U<<=4,U|=ie.getUTCMonth()+1,U<<=5,U|=ie.getUTCDate(),_e&&(Xe=l(1,1)+l(M(N),4)+ae,Se+="up"+l(Xe.length,2)+Xe),L&&(me=l(1,1)+l(M(xe),4)+Y,Se+="uc"+l(me.length,2)+me);var Le="";return Le+=` \0`,Le+=l(Q,2),Le+=B.magic,Le+=l(I,2),Le+=l(U,2),Le+=l(Me.crc32,4),Le+=l(Me.compressedSize,4),Le+=l(Me.uncompressedSize,4),Le+=l(N.length,2),Le+=l(Se.length,2),{fileRecord:y.LOCAL_FILE_HEADER+Le+N+Se,dirRecord:y.CENTRAL_FILE_HEADER+l(Ke,2)+Le+l(xe.length,2)+"\0\0\0\0"+l(ge,4)+l(C,4)+N+Se+xe}}var _=r("../utils"),h=r("../stream/GenericWorker"),g=r("../utf8"),M=r("../crc32"),y=r("../signature");function E(T,O,S,C){h.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=O,this.zipPlatform=S,this.encodeFileName=C,this.streamFiles=T,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}_.inherits(E,h),E.prototype.push=function(T){var O=T.meta.percent||0,S=this.entriesCount,C=this._sources.length;this.accumulate?this.contentBuffer.push(T):(this.bytesWritten+=T.data.length,h.prototype.push.call(this,{data:T.data,meta:{currentFile:this.currentFile,percent:S?(O+100*(S-C-1))/S:100}}))},E.prototype.openedSource=function(T){this.currentSourceOffset=this.bytesWritten,this.currentFile=T.file.name;var O=this.streamFiles&&!T.file.dir;if(O){var S=p(T,O,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:S.fileRecord,meta:{percent:0}})}else this.accumulate=!0},E.prototype.closedSource=function(T){this.accumulate=!1;var O=this.streamFiles&&!T.file.dir,S=p(T,O,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(S.dirRecord),O)this.push({data:function(C){return y.DATA_DESCRIPTOR+l(C.crc32,4)+l(C.compressedSize,4)+l(C.uncompressedSize,4)}(T),meta:{percent:100}});else for(this.push({data:S.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},E.prototype.flush=function(){for(var T=this.bytesWritten,O=0;O<this.dirRecords.length;O++)this.push({data:this.dirRecords[O],meta:{percent:100}});var S=this.bytesWritten-T,C=function(w,b,I,U,z){var B=_.transformTo("string",z(U));return y.CENTRAL_DIRECTORY_END+"\0\0\0\0"+l(w,2)+l(w,2)+l(b,4)+l(I,4)+l(B.length,2)+B}(this.dirRecords.length,S,T,this.zipComment,this.encodeFileName);this.push({data:C,meta:{percent:100}})},E.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},E.prototype.registerPrevious=function(T){this._sources.push(T);var O=this;return T.on("data",function(S){O.processChunk(S)}),T.on("end",function(){O.closedSource(O.previous.streamInfo),O._sources.length?O.prepareNextSource():O.end()}),T.on("error",function(S){O.error(S)}),this},E.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))},E.prototype.error=function(T){var O=this._sources;if(!h.prototype.error.call(this,T))return!1;for(var S=0;S<O.length;S++)try{O[S].error(T)}catch{}return!0},E.prototype.lock=function(){h.prototype.lock.call(this);for(var T=this._sources,O=0;O<T.length;O++)T[O].lock()},o.exports=E},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(r,o,a){var l=r("../compressions"),p=r("./ZipFileWorker");a.generateWorker=function(_,h,g){var M=new p(h.streamFiles,g,h.platform,h.encodeFileName),y=0;try{_.forEach(function(E,T){y++;var O=function(b,I){var U=b||I,z=l[U];if(!z)throw new Error(U+" is not a valid compression method !");return z}(T.options.compression,h.compression),S=T.options.compressionOptions||h.compressionOptions||{},C=T.dir,w=T.date;T._compressWorker(O,S).withStreamInfo("file",{name:E,dir:C,date:w,comment:T.comment||"",unixPermissions:T.unixPermissions,dosPermissions:T.dosPermissions}).pipe(M)}),M.entriesCount=y}catch(E){M.error(E)}return M}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(r,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 p=new l;for(var _ in this)typeof this[_]!="function"&&(p[_]=this[_]);return p}}(l.prototype=r("./object")).loadAsync=r("./load"),l.support=r("./support"),l.defaults=r("./defaults"),l.version="3.10.1",l.loadAsync=function(p,_){return new l().loadAsync(p,_)},l.external=r("./external"),o.exports=l},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(r,o,a){var l=r("./utils"),p=r("./external"),_=r("./utf8"),h=r("./zipEntries"),g=r("./stream/Crc32Probe"),M=r("./nodejsUtils");function y(E){return new p.Promise(function(T,O){var S=E.decompressed.getContentWorker().pipe(new g);S.on("error",function(C){O(C)}).on("end",function(){S.streamInfo.crc32!==E.decompressed.crc32?O(new Error("Corrupted zip : CRC32 mismatch")):T()}).resume()})}o.exports=function(E,T){var O=this;return T=l.extend(T||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:_.utf8decode}),M.isNode&&M.isStream(E)?p.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):l.prepareContent("the loaded zip file",E,!0,T.optimizedBinaryString,T.base64).then(function(S){var C=new h(T);return C.load(S),C}).then(function(S){var C=[p.Promise.resolve(S)],w=S.files;if(T.checkCRC32)for(var b=0;b<w.length;b++)C.push(y(w[b]));return p.Promise.all(C)}).then(function(S){for(var C=S.shift(),w=C.files,b=0;b<w.length;b++){var I=w[b],U=I.fileNameStr,z=l.resolve(I.fileNameStr);O.file(z,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:T.createFolders}),I.dir||(O.file(z).unsafeOriginalName=U)}return C.zipComment.length&&(O.comment=C.zipComment),O})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(r,o,a){var l=r("../utils"),p=r("../stream/GenericWorker");function _(h,g){p.call(this,"Nodejs stream input adapter for "+h),this._upstreamEnded=!1,this._bindStream(g)}l.inherits(_,p),_.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!!p.prototype.pause.call(this)&&(this._stream.pause(),!0)},_.prototype.resume=function(){return!!p.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},o.exports=_},{"../stream/GenericWorker":28,"../utils":32}],13:[function(r,o,a){var l=r("readable-stream").Readable;function p(_,h,g){l.call(this,h),this._helper=_;var M=this;_.on("data",function(y,E){M.push(y)||M._helper.pause(),g&&g(E)}).on("error",function(y){M.emit("error",y)}).on("end",function(){M.push(null)})}r("../utils").inherits(p,l),p.prototype._read=function(){this._helper.resume()},o.exports=p},{"../utils":32,"readable-stream":16}],14:[function(r,o,a){o.exports={isNode:typeof Buffer<"u",newBufferFrom:function(l,p){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(l,p);if(typeof l=="number")throw new Error('The "data" argument must not be a number');return new Buffer(l,p)},allocBuffer:function(l){if(Buffer.alloc)return Buffer.alloc(l);var p=new Buffer(l);return p.fill(0),p},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(r,o,a){function l(z,B,j){var N,ae=_.getTypeOf(B),ce=_.extend(j||{},M);ce.date=ce.date||new Date,ce.compression!==null&&(ce.compression=ce.compression.toUpperCase()),typeof ce.unixPermissions=="string"&&(ce.unixPermissions=parseInt(ce.unixPermissions,8)),ce.unixPermissions&&16384&ce.unixPermissions&&(ce.dir=!0),ce.dosPermissions&&16&ce.dosPermissions&&(ce.dir=!0),ce.dir&&(z=w(z)),ce.createFolders&&(N=C(z))&&b.call(this,N,!0);var xe=ae==="string"&&ce.binary===!1&&ce.base64===!1;j&&j.binary!==void 0||(ce.binary=!xe),(B instanceof y&&B.uncompressedSize===0||ce.dir||!B||B.length===0)&&(ce.base64=!1,ce.binary=!0,B="",ce.compression="STORE",ae="string");var Y=null;Y=B instanceof y||B instanceof h?B:O.isNode&&O.isStream(B)?new S(z,B):_.prepareContent(z,B,ce.binary,ce.optimizedBinaryString,ce.base64);var _e=new E(z,Y,ce);this.files[z]=_e}var p=r("./utf8"),_=r("./utils"),h=r("./stream/GenericWorker"),g=r("./stream/StreamHelper"),M=r("./defaults"),y=r("./compressedObject"),E=r("./zipObject"),T=r("./generate"),O=r("./nodejsUtils"),S=r("./nodejs/NodejsStreamInputAdapter"),C=function(z){z.slice(-1)==="/"&&(z=z.substring(0,z.length-1));var B=z.lastIndexOf("/");return 0<B?z.substring(0,B):""},w=function(z){return z.slice(-1)!=="/"&&(z+="/"),z},b=function(z,B){return B=B!==void 0?B:M.createFolders,z=w(z),this.files[z]||l.call(this,z,null,{dir:!0,createFolders:B}),this.files[z]};function I(z){return Object.prototype.toString.call(z)==="[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(z){var B,j,N;for(B in this.files)N=this.files[B],(j=B.slice(this.root.length,B.length))&&B.slice(0,this.root.length)===this.root&&z(j,N)},filter:function(z){var B=[];return this.forEach(function(j,N){z(j,N)&&B.push(N)}),B},file:function(z,B,j){if(arguments.length!==1)return z=this.root+z,l.call(this,z,B,j),this;if(I(z)){var N=z;return this.filter(function(ce,xe){return!xe.dir&&N.test(ce)})}var ae=this.files[this.root+z];return ae&&!ae.dir?ae:null},folder:function(z){if(!z)return this;if(I(z))return this.filter(function(ae,ce){return ce.dir&&z.test(ae)});var B=this.root+z,j=b.call(this,B),N=this.clone();return N.root=j.name,N},remove:function(z){z=this.root+z;var B=this.files[z];if(B||(z.slice(-1)!=="/"&&(z+="/"),B=this.files[z]),B&&!B.dir)delete this.files[z];else for(var j=this.filter(function(ae,ce){return ce.name.slice(0,z.length)===z}),N=0;N<j.length;N++)delete this.files[j[N].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(z){var B,j={};try{if((j=_.extend(z||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:p.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 N=j.comment||this.comment||"";B=T.generateWorker(this,j,N)}catch(ae){(B=new h("error")).error(ae)}return new g(B,j.type||"string",j.mimeType)},generateAsync:function(z,B){return this.generateInternalStream(z).accumulate(B)},generateNodeStream:function(z,B){return(z=z||{}).type||(z.type="nodebuffer"),this.generateInternalStream(z).toNodejsStream(B)}};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(r,o,a){o.exports=r("stream")},{stream:void 0}],17:[function(r,o,a){var l=r("./DataReader");function p(_){l.call(this,_);for(var h=0;h<this.data.length;h++)_[h]=255&_[h]}r("../utils").inherits(p,l),p.prototype.byteAt=function(_){return this.data[this.zero+_]},p.prototype.lastIndexOfSignature=function(_){for(var h=_.charCodeAt(0),g=_.charCodeAt(1),M=_.charCodeAt(2),y=_.charCodeAt(3),E=this.length-4;0<=E;--E)if(this.data[E]===h&&this.data[E+1]===g&&this.data[E+2]===M&&this.data[E+3]===y)return E-this.zero;return-1},p.prototype.readAndCheckSignature=function(_){var h=_.charCodeAt(0),g=_.charCodeAt(1),M=_.charCodeAt(2),y=_.charCodeAt(3),E=this.readData(4);return h===E[0]&&g===E[1]&&M===E[2]&&y===E[3]},p.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=p},{"../utils":32,"./DataReader":18}],18:[function(r,o,a){var l=r("../utils");function p(_){this.data=_,this.length=_.length,this.index=0,this.zero=0}p.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=p},{"../utils":32}],19:[function(r,o,a){var l=r("./Uint8ArrayReader");function p(_){l.call(this,_)}r("../utils").inherits(p,l),p.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=p},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,o,a){var l=r("./DataReader");function p(_){l.call(this,_)}r("../utils").inherits(p,l),p.prototype.byteAt=function(_){return this.data.charCodeAt(this.zero+_)},p.prototype.lastIndexOfSignature=function(_){return this.data.lastIndexOf(_)-this.zero},p.prototype.readAndCheckSignature=function(_){return _===this.readData(4)},p.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=p},{"../utils":32,"./DataReader":18}],21:[function(r,o,a){var l=r("./ArrayReader");function p(_){l.call(this,_)}r("../utils").inherits(p,l),p.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=p},{"../utils":32,"./ArrayReader":17}],22:[function(r,o,a){var l=r("../utils"),p=r("../support"),_=r("./ArrayReader"),h=r("./StringReader"),g=r("./NodeBufferReader"),M=r("./Uint8ArrayReader");o.exports=function(y){var E=l.getTypeOf(y);return l.checkSupport(E),E!=="string"||p.uint8array?E==="nodebuffer"?new g(y):p.uint8array?new M(l.transformTo("uint8array",y)):new _(l.transformTo("array",y)):new h(y)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,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(r,o,a){var l=r("./GenericWorker"),p=r("../utils");function _(h){l.call(this,"ConvertWorker to "+h),this.destType=h}p.inherits(_,l),_.prototype.processChunk=function(h){this.push({data:p.transformTo(this.destType,h.data),meta:h.meta})},o.exports=_},{"../utils":32,"./GenericWorker":28}],25:[function(r,o,a){var l=r("./GenericWorker"),p=r("../crc32");function _(){l.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(_,l),_.prototype.processChunk=function(h){this.streamInfo.crc32=p(h.data,this.streamInfo.crc32||0),this.push(h)},o.exports=_},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,o,a){var l=r("../utils"),p=r("./GenericWorker");function _(h){p.call(this,"DataLengthProbe for "+h),this.propName=h,this.withStreamInfo(h,0)}l.inherits(_,p),_.prototype.processChunk=function(h){if(h){var g=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=g+h.data.length}p.prototype.processChunk.call(this,h)},o.exports=_},{"../utils":32,"./GenericWorker":28}],27:[function(r,o,a){var l=r("../utils"),p=r("./GenericWorker");function _(h){p.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(_,p),_.prototype.cleanUp=function(){p.prototype.cleanUp.call(this),this.data=null},_.prototype.resume=function(){return!!p.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(r,o,a){function l(p){this.name=p||"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(p){this.emit("data",p)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(p){this.emit("error",p)}return!0},error:function(p){return!this.isFinished&&(this.isPaused?this.generatedError=p:(this.isFinished=!0,this.emit("error",p),this.previous&&this.previous.error(p),this.cleanUp()),!0)},on:function(p,_){return this._listeners[p].push(_),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(p,_){if(this._listeners[p])for(var h=0;h<this._listeners[p].length;h++)this._listeners[p][h].call(this,_)},pipe:function(p){return p.registerPrevious(this)},registerPrevious:function(p){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=p.streamInfo,this.mergeStreamInfo(),this.previous=p;var _=this;return p.on("data",function(h){_.processChunk(h)}),p.on("end",function(){_.end()}),p.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 p=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),p=!0),this.previous&&this.previous.resume(),!p},flush:function(){},processChunk:function(p){this.push(p)},withStreamInfo:function(p,_){return this.extraStreamInfo[p]=_,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var p in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,p)&&(this.streamInfo[p]=this.extraStreamInfo[p])},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 p="Worker "+this.name;return this.previous?this.previous+" -> "+p:p}},o.exports=l},{}],29:[function(r,o,a){var l=r("../utils"),p=r("./ConvertWorker"),_=r("./GenericWorker"),h=r("../base64"),g=r("../support"),M=r("../external"),y=null;if(g.nodestream)try{y=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function E(O,S){return new M.Promise(function(C,w){var b=[],I=O._internalType,U=O._outputType,z=O._mimeType;O.on("data",function(B,j){b.push(B),S&&S(j)}).on("error",function(B){b=[],w(B)}).on("end",function(){try{var B=function(j,N,ae){switch(j){case"blob":return l.newBlob(l.transformTo("arraybuffer",N),ae);case"base64":return h.encode(N);default:return l.transformTo(j,N)}}(U,function(j,N){var ae,ce=0,xe=null,Y=0;for(ae=0;ae<N.length;ae++)Y+=N[ae].length;switch(j){case"string":return N.join("");case"array":return Array.prototype.concat.apply([],N);case"uint8array":for(xe=new Uint8Array(Y),ae=0;ae<N.length;ae++)xe.set(N[ae],ce),ce+=N[ae].length;return xe;case"nodebuffer":return Buffer.concat(N);default:throw new Error("concat : unsupported type '"+j+"'")}}(I,b),z);C(B)}catch(j){w(j)}b=[]}).resume()})}function T(O,S,C){var w=S;switch(S){case"blob":case"arraybuffer":w="uint8array";break;case"base64":w="string"}try{this._internalType=w,this._outputType=S,this._mimeType=C,l.checkSupport(w),this._worker=O.pipe(new p(w)),O.lock()}catch(b){this._worker=new _("error"),this._worker.error(b)}}T.prototype={accumulate:function(O){return E(this,O)},on:function(O,S){var C=this;return O==="data"?this._worker.on(O,function(w){S.call(C,w.data,w.meta)}):this._worker.on(O,function(){l.delay(S,arguments,C)}),this},resume:function(){return l.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(O){if(l.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new y(this,{objectMode:this._outputType!=="nodebuffer"},O)}},o.exports=T},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(r,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 p=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);p.append(l),a.blob=p.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,o,a){for(var l=r("./utils"),p=r("./support"),_=r("./nodejsUtils"),h=r("./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 y(){h.call(this,"utf-8 decode"),this.leftOver=null}function E(){h.call(this,"utf-8 encode")}a.utf8encode=function(T){return p.nodebuffer?_.newBufferFrom(T,"utf-8"):function(O){var S,C,w,b,I,U=O.length,z=0;for(b=0;b<U;b++)(64512&(C=O.charCodeAt(b)))==55296&&b+1<U&&(64512&(w=O.charCodeAt(b+1)))==56320&&(C=65536+(C-55296<<10)+(w-56320),b++),z+=C<128?1:C<2048?2:C<65536?3:4;for(S=p.uint8array?new Uint8Array(z):new Array(z),b=I=0;I<z;b++)(64512&(C=O.charCodeAt(b)))==55296&&b+1<U&&(64512&(w=O.charCodeAt(b+1)))==56320&&(C=65536+(C-55296<<10)+(w-56320),b++),C<128?S[I++]=C:(C<2048?S[I++]=192|C>>>6:(C<65536?S[I++]=224|C>>>12:(S[I++]=240|C>>>18,S[I++]=128|C>>>12&63),S[I++]=128|C>>>6&63),S[I++]=128|63&C);return S}(T)},a.utf8decode=function(T){return p.nodebuffer?l.transformTo("nodebuffer",T).toString("utf-8"):function(O){var S,C,w,b,I=O.length,U=new Array(2*I);for(S=C=0;S<I;)if((w=O[S++])<128)U[C++]=w;else if(4<(b=g[w]))U[C++]=65533,S+=b-1;else{for(w&=b===2?31:b===3?15:7;1<b&&S<I;)w=w<<6|63&O[S++],b--;1<b?U[C++]=65533:w<65536?U[C++]=w:(w-=65536,U[C++]=55296|w>>10&1023,U[C++]=56320|1023&w)}return U.length!==C&&(U.subarray?U=U.subarray(0,C):U.length=C),l.applyFromCharCode(U)}(T=l.transformTo(p.uint8array?"uint8array":"array",T))},l.inherits(y,h),y.prototype.processChunk=function(T){var O=l.transformTo(p.uint8array?"uint8array":"array",T.data);if(this.leftOver&&this.leftOver.length){if(p.uint8array){var S=O;(O=new Uint8Array(S.length+this.leftOver.length)).set(this.leftOver,0),O.set(S,this.leftOver.length)}else O=this.leftOver.concat(O);this.leftOver=null}var C=function(b,I){var U;for((I=I||b.length)>b.length&&(I=b.length),U=I-1;0<=U&&(192&b[U])==128;)U--;return U<0||U===0?I:U+g[b[U]]>I?U:I}(O),w=O;C!==O.length&&(p.uint8array?(w=O.subarray(0,C),this.leftOver=O.subarray(C,O.length)):(w=O.slice(0,C),this.leftOver=O.slice(C,O.length))),this.push({data:a.utf8decode(w),meta:T.meta})},y.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=y,l.inherits(E,h),E.prototype.processChunk=function(T){this.push({data:a.utf8encode(T.data),meta:T.meta})},a.Utf8EncodeWorker=E},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,o,a){var l=r("./support"),p=r("./base64"),_=r("./nodejsUtils"),h=r("./external");function g(S){return S}function M(S,C){for(var w=0;w<S.length;++w)C[w]=255&S.charCodeAt(w);return C}r("setimmediate"),a.newBlob=function(S,C){a.checkSupport("blob");try{return new Blob([S],{type:C})}catch{try{var w=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return w.append(S),w.getBlob(C)}catch{throw new Error("Bug : can't construct the Blob.")}}};var y={stringifyByChunk:function(S,C,w){var b=[],I=0,U=S.length;if(U<=w)return String.fromCharCode.apply(null,S);for(;I<U;)C==="array"||C==="nodebuffer"?b.push(String.fromCharCode.apply(null,S.slice(I,Math.min(I+w,U)))):b.push(String.fromCharCode.apply(null,S.subarray(I,Math.min(I+w,U)))),I+=w;return b.join("")},stringifyByChar:function(S){for(var C="",w=0;w<S.length;w++)C+=String.fromCharCode(S[w]);return C},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 E(S){var C=65536,w=a.getTypeOf(S),b=!0;if(w==="uint8array"?b=y.applyCanBeUsed.uint8array:w==="nodebuffer"&&(b=y.applyCanBeUsed.nodebuffer),b)for(;1<C;)try{return y.stringifyByChunk(S,w,C)}catch{C=Math.floor(C/2)}return y.stringifyByChar(S)}function T(S,C){for(var w=0;w<S.length;w++)C[w]=S[w];return C}a.applyFromCharCode=E;var O={};O.string={string:g,array:function(S){return M(S,new Array(S.length))},arraybuffer:function(S){return O.string.uint8array(S).buffer},uint8array:function(S){return M(S,new Uint8Array(S.length))},nodebuffer:function(S){return M(S,_.allocBuffer(S.length))}},O.array={string:E,array:g,arraybuffer:function(S){return new Uint8Array(S).buffer},uint8array:function(S){return new Uint8Array(S)},nodebuffer:function(S){return _.newBufferFrom(S)}},O.arraybuffer={string:function(S){return E(new Uint8Array(S))},array:function(S){return T(new Uint8Array(S),new Array(S.byteLength))},arraybuffer:g,uint8array:function(S){return new Uint8Array(S)},nodebuffer:function(S){return _.newBufferFrom(new Uint8Array(S))}},O.uint8array={string:E,array:function(S){return T(S,new Array(S.length))},arraybuffer:function(S){return S.buffer},uint8array:g,nodebuffer:function(S){return _.newBufferFrom(S)}},O.nodebuffer={string:E,array:function(S){return T(S,new Array(S.length))},arraybuffer:function(S){return O.nodebuffer.uint8array(S).buffer},uint8array:function(S){return T(S,new Uint8Array(S.length))},nodebuffer:g},a.transformTo=function(S,C){if(C=C||"",!S)return C;a.checkSupport(S);var w=a.getTypeOf(C);return O[w][S](C)},a.resolve=function(S){for(var C=S.split("/"),w=[],b=0;b<C.length;b++){var I=C[b];I==="."||I===""&&b!==0&&b!==C.length-1||(I===".."?w.pop():w.push(I))}return w.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 C,w,b="";for(w=0;w<(S||"").length;w++)b+="\\x"+((C=S.charCodeAt(w))<16?"0":"")+C.toString(16).toUpperCase();return b},a.delay=function(S,C,w){setImmediate(function(){S.apply(w||null,C||[])})},a.inherits=function(S,C){function w(){}w.prototype=C.prototype,S.prototype=new w},a.extend=function(){var S,C,w={};for(S=0;S<arguments.length;S++)for(C in arguments[S])Object.prototype.hasOwnProperty.call(arguments[S],C)&&w[C]===void 0&&(w[C]=arguments[S][C]);return w},a.prepareContent=function(S,C,w,b,I){return h.Promise.resolve(C).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(z,B){var j=new FileReader;j.onload=function(N){z(N.target.result)},j.onerror=function(N){B(N.target.error)},j.readAsArrayBuffer(U)}):U}).then(function(U){var z=a.getTypeOf(U);return z?(z==="arraybuffer"?U=a.transformTo("uint8array",U):z==="string"&&(I?U=p.decode(U):w&&b!==!0&&(U=function(B){return M(B,l.uint8array?new Uint8Array(B.length):new Array(B.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(r,o,a){var l=r("./reader/readerFor"),p=r("./utils"),_=r("./signature"),h=r("./zipEntry"),g=r("./support");function M(y){this.files=[],this.loadOptions=y}M.prototype={checkSignature:function(y){if(!this.reader.readAndCheckSignature(y)){this.reader.index-=4;var E=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+p.pretty(E)+", expected "+p.pretty(y)+")")}},isSignature:function(y,E){var T=this.reader.index;this.reader.setIndex(y);var O=this.reader.readString(4)===E;return this.reader.setIndex(T),O},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 y=this.reader.readData(this.zipCommentLength),E=g.uint8array?"uint8array":"array",T=p.transformTo(E,y);this.zipComment=this.loadOptions.decodeFileName(T)},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 y,E,T,O=this.zip64EndOfCentralSize-44;0<O;)y=this.reader.readInt(2),E=this.reader.readInt(4),T=this.reader.readData(E),this.zip64ExtensibleData[y]={id:y,length:E,value:T}},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 y,E;for(y=0;y<this.files.length;y++)E=this.files[y],this.reader.setIndex(E.localHeaderOffset),this.checkSignature(_.LOCAL_FILE_HEADER),E.readLocalPart(this.reader),E.handleUTF8(),E.processAttributes()},readCentralDir:function(){var y;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(_.CENTRAL_FILE_HEADER);)(y=new h({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(y);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 y=this.reader.lastIndexOfSignature(_.CENTRAL_DIRECTORY_END);if(y<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(y);var E=y;if(this.checkSignature(_.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===p.MAX_VALUE_16BITS||this.diskWithCentralDirStart===p.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===p.MAX_VALUE_16BITS||this.centralDirRecords===p.MAX_VALUE_16BITS||this.centralDirSize===p.MAX_VALUE_32BITS||this.centralDirOffset===p.MAX_VALUE_32BITS){if(this.zip64=!0,(y=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(y),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 T=this.centralDirOffset+this.centralDirSize;this.zip64&&(T+=20,T+=12+this.zip64EndOfCentralSize);var O=E-T;if(0<O)this.isSignature(E,_.CENTRAL_FILE_HEADER)||(this.reader.zero=O);else if(O<0)throw new Error("Corrupted zip: missing "+Math.abs(O)+" bytes.")},prepareReader:function(y){this.reader=l(y)},load:function(y){this.prepareReader(y),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},o.exports=M},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(r,o,a){var l=r("./reader/readerFor"),p=r("./utils"),_=r("./compressedObject"),h=r("./crc32"),g=r("./utf8"),M=r("./compressions"),y=r("./support");function E(T,O){this.options=T,this.loadOptions=O}E.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(T){var O,S;if(T.skip(22),this.fileNameLength=T.readInt(2),S=T.readInt(2),this.fileName=T.readData(this.fileNameLength),T.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((O=function(C){for(var w in M)if(Object.prototype.hasOwnProperty.call(M,w)&&M[w].magic===C)return M[w];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+p.pretty(this.compressionMethod)+" unknown (inner file : "+p.transformTo("string",this.fileName)+")");this.decompressed=new _(this.compressedSize,this.uncompressedSize,this.crc32,O,T.readData(this.compressedSize))},readCentralPart:function(T){this.versionMadeBy=T.readInt(2),T.skip(2),this.bitFlag=T.readInt(2),this.compressionMethod=T.readString(2),this.date=T.readDate(),this.crc32=T.readInt(4),this.compressedSize=T.readInt(4),this.uncompressedSize=T.readInt(4);var O=T.readInt(2);if(this.extraFieldsLength=T.readInt(2),this.fileCommentLength=T.readInt(2),this.diskNumberStart=T.readInt(2),this.internalFileAttributes=T.readInt(2),this.externalFileAttributes=T.readInt(4),this.localHeaderOffset=T.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");T.skip(O),this.readExtraFields(T),this.parseZIP64ExtraField(T),this.fileComment=T.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var T=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),T==0&&(this.dosPermissions=63&this.externalFileAttributes),T==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var T=l(this.extraFields[1].value);this.uncompressedSize===p.MAX_VALUE_32BITS&&(this.uncompressedSize=T.readInt(8)),this.compressedSize===p.MAX_VALUE_32BITS&&(this.compressedSize=T.readInt(8)),this.localHeaderOffset===p.MAX_VALUE_32BITS&&(this.localHeaderOffset=T.readInt(8)),this.diskNumberStart===p.MAX_VALUE_32BITS&&(this.diskNumberStart=T.readInt(4))}},readExtraFields:function(T){var O,S,C,w=T.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});T.index+4<w;)O=T.readInt(2),S=T.readInt(2),C=T.readData(S),this.extraFields[O]={id:O,length:S,value:C};T.setIndex(w)},handleUTF8:function(){var T=y.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=g.utf8decode(this.fileName),this.fileCommentStr=g.utf8decode(this.fileComment);else{var O=this.findExtraFieldUnicodePath();if(O!==null)this.fileNameStr=O;else{var S=p.transformTo(T,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(S)}var C=this.findExtraFieldUnicodeComment();if(C!==null)this.fileCommentStr=C;else{var w=p.transformTo(T,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(w)}}},findExtraFieldUnicodePath:function(){var T=this.extraFields[28789];if(T){var O=l(T.value);return O.readInt(1)!==1||h(this.fileName)!==O.readInt(4)?null:g.utf8decode(O.readData(T.length-5))}return null},findExtraFieldUnicodeComment:function(){var T=this.extraFields[25461];if(T){var O=l(T.value);return O.readInt(1)!==1||h(this.fileComment)!==O.readInt(4)?null:g.utf8decode(O.readData(T.length-5))}return null}},o.exports=E},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(r,o,a){function l(O,S,C){this.name=O,this.dir=C.dir,this.date=C.date,this.comment=C.comment,this.unixPermissions=C.unixPermissions,this.dosPermissions=C.dosPermissions,this._data=S,this._dataBinary=C.binary,this.options={compression:C.compression,compressionOptions:C.compressionOptions}}var p=r("./stream/StreamHelper"),_=r("./stream/DataWorker"),h=r("./utf8"),g=r("./compressedObject"),M=r("./stream/GenericWorker");l.prototype={internalStream:function(O){var S=null,C="string";try{if(!O)throw new Error("No output type specified.");var w=(C=O.toLowerCase())==="string"||C==="text";C!=="binarystring"&&C!=="text"||(C="string"),S=this._decompressWorker();var b=!this._dataBinary;b&&!w&&(S=S.pipe(new h.Utf8EncodeWorker)),!b&&w&&(S=S.pipe(new h.Utf8DecodeWorker))}catch(I){(S=new M("error")).error(I)}return new p(S,C,"")},async:function(O,S){return this.internalStream(O).accumulate(S)},nodeStream:function(O,S){return this.internalStream(O||"nodebuffer").toNodejsStream(S)},_compressWorker:function(O,S){if(this._data instanceof g&&this._data.compression.magic===O.magic)return this._data.getCompressedWorker();var C=this._decompressWorker();return this._dataBinary||(C=C.pipe(new h.Utf8EncodeWorker)),g.createWorkerFrom(C,O,S)},_decompressWorker:function(){return this._data instanceof g?this._data.getContentWorker():this._data instanceof M?this._data:new _(this._data)}};for(var y=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],E=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},T=0;T<y.length;T++)l.prototype[y[T]]=E;o.exports=l},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(r,o,a){(function(l){var p,_,h=l.MutationObserver||l.WebKitMutationObserver;if(h){var g=0,M=new h(O),y=l.document.createTextNode("");M.observe(y,{characterData:!0}),p=function(){y.data=g=++g%2}}else if(l.setImmediate||l.MessageChannel===void 0)p="document"in l&&"onreadystatechange"in l.document.createElement("script")?function(){var S=l.document.createElement("script");S.onreadystatechange=function(){O(),S.onreadystatechange=null,S.parentNode.removeChild(S),S=null},l.document.documentElement.appendChild(S)}:function(){setTimeout(O,0)};else{var E=new l.MessageChannel;E.port1.onmessage=O,p=function(){E.port2.postMessage(0)}}var T=[];function O(){var S,C;_=!0;for(var w=T.length;w;){for(C=T,T=[],S=-1;++S<w;)C[S]();w=T.length}_=!1}o.exports=function(S){T.push(S)!==1||_||p()}}).call(this,typeof Co<"u"?Co:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(r,o,a){var l=r("immediate");function p(){}var _={},h=["REJECTED"],g=["FULFILLED"],M=["PENDING"];function y(w){if(typeof w!="function")throw new TypeError("resolver must be a function");this.state=M,this.queue=[],this.outcome=void 0,w!==p&&S(this,w)}function E(w,b,I){this.promise=w,typeof b=="function"&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),typeof I=="function"&&(this.onRejected=I,this.callRejected=this.otherCallRejected)}function T(w,b,I){l(function(){var U;try{U=b(I)}catch(z){return _.reject(w,z)}U===w?_.reject(w,new TypeError("Cannot resolve promise with itself")):_.resolve(w,U)})}function O(w){var b=w&&w.then;if(w&&(typeof w=="object"||typeof w=="function")&&typeof b=="function")return function(){b.apply(w,arguments)}}function S(w,b){var I=!1;function U(j){I||(I=!0,_.reject(w,j))}function z(j){I||(I=!0,_.resolve(w,j))}var B=C(function(){b(z,U)});B.status==="error"&&U(B.value)}function C(w,b){var I={};try{I.value=w(b),I.status="success"}catch(U){I.status="error",I.value=U}return I}(o.exports=y).prototype.finally=function(w){if(typeof w!="function")return this;var b=this.constructor;return this.then(function(I){return b.resolve(w()).then(function(){return I})},function(I){return b.resolve(w()).then(function(){throw I})})},y.prototype.catch=function(w){return this.then(null,w)},y.prototype.then=function(w,b){if(typeof w!="function"&&this.state===g||typeof b!="function"&&this.state===h)return this;var I=new this.constructor(p);return this.state!==M?T(I,this.state===g?w:b,this.outcome):this.queue.push(new E(I,w,b)),I},E.prototype.callFulfilled=function(w){_.resolve(this.promise,w)},E.prototype.otherCallFulfilled=function(w){T(this.promise,this.onFulfilled,w)},E.prototype.callRejected=function(w){_.reject(this.promise,w)},E.prototype.otherCallRejected=function(w){T(this.promise,this.onRejected,w)},_.resolve=function(w,b){var I=C(O,b);if(I.status==="error")return _.reject(w,I.value);var U=I.value;if(U)S(w,U);else{w.state=g,w.outcome=b;for(var z=-1,B=w.queue.length;++z<B;)w.queue[z].callFulfilled(b)}return w},_.reject=function(w,b){w.state=h,w.outcome=b;for(var I=-1,U=w.queue.length;++I<U;)w.queue[I].callRejected(b);return w},y.resolve=function(w){return w instanceof this?w:_.resolve(new this(p),w)},y.reject=function(w){var b=new this(p);return _.reject(b,w)},y.all=function(w){var b=this;if(Object.prototype.toString.call(w)!=="[object Array]")return this.reject(new TypeError("must be an array"));var I=w.length,U=!1;if(!I)return this.resolve([]);for(var z=new Array(I),B=0,j=-1,N=new this(p);++j<I;)ae(w[j],j);return N;function ae(ce,xe){b.resolve(ce).then(function(Y){z[xe]=Y,++B!==I||U||(U=!0,_.resolve(N,z))},function(Y){U||(U=!0,_.reject(N,Y))})}},y.race=function(w){var b=this;if(Object.prototype.toString.call(w)!=="[object Array]")return this.reject(new TypeError("must be an array"));var I=w.length,U=!1;if(!I)return this.resolve([]);for(var z=-1,B=new this(p);++z<I;)j=w[z],b.resolve(j).then(function(N){U||(U=!0,_.resolve(B,N))},function(N){U||(U=!0,_.reject(B,N))});var j;return B}},{immediate:36}],38:[function(r,o,a){var l={};(0,r("./lib/utils/common").assign)(l,r("./lib/deflate"),r("./lib/inflate"),r("./lib/zlib/constants")),o.exports=l},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(r,o,a){var l=r("./zlib/deflate"),p=r("./utils/common"),_=r("./utils/strings"),h=r("./zlib/messages"),g=r("./zlib/zstream"),M=Object.prototype.toString,y=0,E=-1,T=0,O=8;function S(w){if(!(this instanceof S))return new S(w);this.options=p.assign({level:E,method:O,chunkSize:16384,windowBits:15,memLevel:8,strategy:T,to:""},w||{});var b=this.options;b.raw&&0<b.windowBits?b.windowBits=-b.windowBits:b.gzip&&0<b.windowBits&&b.windowBits<16&&(b.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,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(I!==y)throw new Error(h[I]);if(b.header&&l.deflateSetHeader(this.strm,b.header),b.dictionary){var U;if(U=typeof b.dictionary=="string"?_.string2buf(b.dictionary):M.call(b.dictionary)==="[object ArrayBuffer]"?new Uint8Array(b.dictionary):b.dictionary,(I=l.deflateSetDictionary(this.strm,U))!==y)throw new Error(h[I]);this._dict_set=!0}}function C(w,b){var I=new S(b);if(I.push(w,!0),I.err)throw I.msg||h[I.err];return I.result}S.prototype.push=function(w,b){var I,U,z=this.strm,B=this.options.chunkSize;if(this.ended)return!1;U=b===~~b?b:b===!0?4:0,typeof w=="string"?z.input=_.string2buf(w):M.call(w)==="[object ArrayBuffer]"?z.input=new Uint8Array(w):z.input=w,z.next_in=0,z.avail_in=z.input.length;do{if(z.avail_out===0&&(z.output=new p.Buf8(B),z.next_out=0,z.avail_out=B),(I=l.deflate(z,U))!==1&&I!==y)return this.onEnd(I),!(this.ended=!0);z.avail_out!==0&&(z.avail_in!==0||U!==4&&U!==2)||(this.options.to==="string"?this.onData(_.buf2binstring(p.shrinkBuf(z.output,z.next_out))):this.onData(p.shrinkBuf(z.output,z.next_out)))}while((0<z.avail_in||z.avail_out===0)&&I!==1);return U===4?(I=l.deflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===y):U!==2||(this.onEnd(y),!(z.avail_out=0))},S.prototype.onData=function(w){this.chunks.push(w)},S.prototype.onEnd=function(w){w===y&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=p.flattenChunks(this.chunks)),this.chunks=[],this.err=w,this.msg=this.strm.msg},a.Deflate=S,a.deflate=C,a.deflateRaw=function(w,b){return(b=b||{}).raw=!0,C(w,b)},a.gzip=function(w,b){return(b=b||{}).gzip=!0,C(w,b)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(r,o,a){var l=r("./zlib/inflate"),p=r("./utils/common"),_=r("./utils/strings"),h=r("./zlib/constants"),g=r("./zlib/messages"),M=r("./zlib/zstream"),y=r("./zlib/gzheader"),E=Object.prototype.toString;function T(S){if(!(this instanceof T))return new T(S);this.options=p.assign({chunkSize:16384,windowBits:0,to:""},S||{});var C=this.options;C.raw&&0<=C.windowBits&&C.windowBits<16&&(C.windowBits=-C.windowBits,C.windowBits===0&&(C.windowBits=-15)),!(0<=C.windowBits&&C.windowBits<16)||S&&S.windowBits||(C.windowBits+=32),15<C.windowBits&&C.windowBits<48&&!(15&C.windowBits)&&(C.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new M,this.strm.avail_out=0;var w=l.inflateInit2(this.strm,C.windowBits);if(w!==h.Z_OK)throw new Error(g[w]);this.header=new y,l.inflateGetHeader(this.strm,this.header)}function O(S,C){var w=new T(C);if(w.push(S,!0),w.err)throw w.msg||g[w.err];return w.result}T.prototype.push=function(S,C){var w,b,I,U,z,B,j=this.strm,N=this.options.chunkSize,ae=this.options.dictionary,ce=!1;if(this.ended)return!1;b=C===~~C?C:C===!0?h.Z_FINISH:h.Z_NO_FLUSH,typeof S=="string"?j.input=_.binstring2buf(S):E.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 p.Buf8(N),j.next_out=0,j.avail_out=N),(w=l.inflate(j,h.Z_NO_FLUSH))===h.Z_NEED_DICT&&ae&&(B=typeof ae=="string"?_.string2buf(ae):E.call(ae)==="[object ArrayBuffer]"?new Uint8Array(ae):ae,w=l.inflateSetDictionary(this.strm,B)),w===h.Z_BUF_ERROR&&ce===!0&&(w=h.Z_OK,ce=!1),w!==h.Z_STREAM_END&&w!==h.Z_OK)return this.onEnd(w),!(this.ended=!0);j.next_out&&(j.avail_out!==0&&w!==h.Z_STREAM_END&&(j.avail_in!==0||b!==h.Z_FINISH&&b!==h.Z_SYNC_FLUSH)||(this.options.to==="string"?(I=_.utf8border(j.output,j.next_out),U=j.next_out-I,z=_.buf2string(j.output,I),j.next_out=U,j.avail_out=N-U,U&&p.arraySet(j.output,j.output,I,U,0),this.onData(z)):this.onData(p.shrinkBuf(j.output,j.next_out)))),j.avail_in===0&&j.avail_out===0&&(ce=!0)}while((0<j.avail_in||j.avail_out===0)&&w!==h.Z_STREAM_END);return w===h.Z_STREAM_END&&(b=h.Z_FINISH),b===h.Z_FINISH?(w=l.inflateEnd(this.strm),this.onEnd(w),this.ended=!0,w===h.Z_OK):b!==h.Z_SYNC_FLUSH||(this.onEnd(h.Z_OK),!(j.avail_out=0))},T.prototype.onData=function(S){this.chunks.push(S)},T.prototype.onEnd=function(S){S===h.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=p.flattenChunks(this.chunks)),this.chunks=[],this.err=S,this.msg=this.strm.msg},a.Inflate=T,a.inflate=O,a.inflateRaw=function(S,C){return(C=C||{}).raw=!0,O(S,C)},a.ungzip=O},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(r,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 y in M)M.hasOwnProperty(y)&&(h[y]=M[y])}}return h},a.shrinkBuf=function(h,g){return h.length===g?h:h.subarray?h.subarray(0,g):(h.length=g,h)};var p={arraySet:function(h,g,M,y,E){if(g.subarray&&h.subarray)h.set(g.subarray(M,M+y),E);else for(var T=0;T<y;T++)h[E+T]=g[M+T]},flattenChunks:function(h){var g,M,y,E,T,O;for(g=y=0,M=h.length;g<M;g++)y+=h[g].length;for(O=new Uint8Array(y),g=E=0,M=h.length;g<M;g++)T=h[g],O.set(T,E),E+=T.length;return O}},_={arraySet:function(h,g,M,y,E){for(var T=0;T<y;T++)h[E+T]=g[M+T]},flattenChunks:function(h){return[].concat.apply([],h)}};a.setTyped=function(h){h?(a.Buf8=Uint8Array,a.Buf16=Uint16Array,a.Buf32=Int32Array,a.assign(a,p)):(a.Buf8=Array,a.Buf16=Array,a.Buf32=Array,a.assign(a,_))},a.setTyped(l)},{}],42:[function(r,o,a){var l=r("./common"),p=!0,_=!0;try{String.fromCharCode.apply(null,[0])}catch{p=!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(y,E){if(E<65537&&(y.subarray&&_||!y.subarray&&p))return String.fromCharCode.apply(null,l.shrinkBuf(y,E));for(var T="",O=0;O<E;O++)T+=String.fromCharCode(y[O]);return T}h[254]=h[254]=1,a.string2buf=function(y){var E,T,O,S,C,w=y.length,b=0;for(S=0;S<w;S++)(64512&(T=y.charCodeAt(S)))==55296&&S+1<w&&(64512&(O=y.charCodeAt(S+1)))==56320&&(T=65536+(T-55296<<10)+(O-56320),S++),b+=T<128?1:T<2048?2:T<65536?3:4;for(E=new l.Buf8(b),S=C=0;C<b;S++)(64512&(T=y.charCodeAt(S)))==55296&&S+1<w&&(64512&(O=y.charCodeAt(S+1)))==56320&&(T=65536+(T-55296<<10)+(O-56320),S++),T<128?E[C++]=T:(T<2048?E[C++]=192|T>>>6:(T<65536?E[C++]=224|T>>>12:(E[C++]=240|T>>>18,E[C++]=128|T>>>12&63),E[C++]=128|T>>>6&63),E[C++]=128|63&T);return E},a.buf2binstring=function(y){return M(y,y.length)},a.binstring2buf=function(y){for(var E=new l.Buf8(y.length),T=0,O=E.length;T<O;T++)E[T]=y.charCodeAt(T);return E},a.buf2string=function(y,E){var T,O,S,C,w=E||y.length,b=new Array(2*w);for(T=O=0;T<w;)if((S=y[T++])<128)b[O++]=S;else if(4<(C=h[S]))b[O++]=65533,T+=C-1;else{for(S&=C===2?31:C===3?15:7;1<C&&T<w;)S=S<<6|63&y[T++],C--;1<C?b[O++]=65533:S<65536?b[O++]=S:(S-=65536,b[O++]=55296|S>>10&1023,b[O++]=56320|1023&S)}return M(b,O)},a.utf8border=function(y,E){var T;for((E=E||y.length)>y.length&&(E=y.length),T=E-1;0<=T&&(192&y[T])==128;)T--;return T<0||T===0?E:T+h[y[T]]>E?T:E}},{"./common":41}],43:[function(r,o,a){o.exports=function(l,p,_,h){for(var g=65535&l|0,M=l>>>16&65535|0,y=0;_!==0;){for(_-=y=2e3<_?2e3:_;M=M+(g=g+p[h++]|0)|0,--y;);g%=65521,M%=65521}return g|M<<16|0}},{}],44:[function(r,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(r,o,a){var l=function(){for(var p,_=[],h=0;h<256;h++){p=h;for(var g=0;g<8;g++)p=1&p?3988292384^p>>>1:p>>>1;_[h]=p}return _}();o.exports=function(p,_,h,g){var M=l,y=g+h;p^=-1;for(var E=g;E<y;E++)p=p>>>8^M[255&(p^_[E])];return-1^p}},{}],46:[function(r,o,a){var l,p=r("../utils/common"),_=r("./trees"),h=r("./adler32"),g=r("./crc32"),M=r("./messages"),y=0,E=4,T=0,O=-2,S=-1,C=4,w=2,b=8,I=9,U=286,z=30,B=19,j=2*U+1,N=15,ae=3,ce=258,xe=ce+ae+1,Y=42,_e=113,L=1,Se=2,Xe=3,me=4;function X(A,$e){return A.msg=M[$e],$e}function ie(A){return(A<<1)-(4<A?9:0)}function Me(A){for(var $e=A.length;0<=--$e;)A[$e]=0}function Q(A){var $e=A.state,Pe=$e.pending;Pe>A.avail_out&&(Pe=A.avail_out),Pe!==0&&(p.arraySet(A.output,$e.pending_buf,$e.pending_out,Pe,A.next_out),A.next_out+=Pe,$e.pending_out+=Pe,A.total_out+=Pe,A.avail_out-=Pe,$e.pending-=Pe,$e.pending===0&&($e.pending_out=0))}function ge(A,$e){_._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,$e),A.block_start=A.strstart,Q(A.strm)}function Ke(A,$e){A.pending_buf[A.pending++]=$e}function Le(A,$e){A.pending_buf[A.pending++]=$e>>>8&255,A.pending_buf[A.pending++]=255&$e}function Be(A,$e){var Pe,se,re=A.max_chain_length,ye=A.strstart,R=A.prev_length,ee=A.nice_match,D=A.strstart>A.w_size-xe?A.strstart-(A.w_size-xe):0,ue=A.window,le=A.w_mask,ke=A.prev,Ne=A.strstart+ce,dt=ue[ye+R-1],Je=ue[ye+R];A.prev_length>=A.good_match&&(re>>=2),ee>A.lookahead&&(ee=A.lookahead);do if(ue[(Pe=$e)+R]===Je&&ue[Pe+R-1]===dt&&ue[Pe]===ue[ye]&&ue[++Pe]===ue[ye+1]){ye+=2,Pe++;do;while(ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ye<Ne);if(se=ce-(Ne-ye),ye=Ne-ce,R<se){if(A.match_start=$e,ee<=(R=se))break;dt=ue[ye+R-1],Je=ue[ye+R]}}while(($e=ke[$e&le])>D&&--re!=0);return R<=A.lookahead?R:A.lookahead}function We(A){var $e,Pe,se,re,ye,R,ee,D,ue,le,ke=A.w_size;do{if(re=A.window_size-A.lookahead-A.strstart,A.strstart>=ke+(ke-xe)){for(p.arraySet(A.window,A.window,ke,ke,0),A.match_start-=ke,A.strstart-=ke,A.block_start-=ke,$e=Pe=A.hash_size;se=A.head[--$e],A.head[$e]=ke<=se?se-ke:0,--Pe;);for($e=Pe=ke;se=A.prev[--$e],A.prev[$e]=ke<=se?se-ke:0,--Pe;);re+=ke}if(A.strm.avail_in===0)break;if(R=A.strm,ee=A.window,D=A.strstart+A.lookahead,ue=re,le=void 0,le=R.avail_in,ue<le&&(le=ue),Pe=le===0?0:(R.avail_in-=le,p.arraySet(ee,R.input,R.next_in,le,D),R.state.wrap===1?R.adler=h(R.adler,ee,le,D):R.state.wrap===2&&(R.adler=g(R.adler,ee,le,D)),R.next_in+=le,R.total_in+=le,le),A.lookahead+=Pe,A.lookahead+A.insert>=ae)for(ye=A.strstart-A.insert,A.ins_h=A.window[ye],A.ins_h=(A.ins_h<<A.hash_shift^A.window[ye+1])&A.hash_mask;A.insert&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[ye+ae-1])&A.hash_mask,A.prev[ye&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=ye,ye++,A.insert--,!(A.lookahead+A.insert<ae)););}while(A.lookahead<xe&&A.strm.avail_in!==0)}function st(A,$e){for(var Pe,se;;){if(A.lookahead<xe){if(We(A),A.lookahead<xe&&$e===y)return L;if(A.lookahead===0)break}if(Pe=0,A.lookahead>=ae&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+ae-1])&A.hash_mask,Pe=A.prev[A.strstart&A.w_mask]=A.head[A.ins_h],A.head[A.ins_h]=A.strstart),Pe!==0&&A.strstart-Pe<=A.w_size-xe&&(A.match_length=Be(A,Pe)),A.match_length>=ae)if(se=_._tr_tally(A,A.strstart-A.match_start,A.match_length-ae),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=ae){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+ae-1])&A.hash_mask,Pe=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&&(ge(A,!1),A.strm.avail_out===0))return L}return A.insert=A.strstart<ae-1?A.strstart:ae-1,$e===E?(ge(A,!0),A.strm.avail_out===0?Xe:me):A.last_lit&&(ge(A,!1),A.strm.avail_out===0)?L:Se}function pt(A,$e){for(var Pe,se,re;;){if(A.lookahead<xe){if(We(A),A.lookahead<xe&&$e===y)return L;if(A.lookahead===0)break}if(Pe=0,A.lookahead>=ae&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+ae-1])&A.hash_mask,Pe=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=ae-1,Pe!==0&&A.prev_length<A.max_lazy_match&&A.strstart-Pe<=A.w_size-xe&&(A.match_length=Be(A,Pe),A.match_length<=5&&(A.strategy===1||A.match_length===ae&&4096<A.strstart-A.match_start)&&(A.match_length=ae-1)),A.prev_length>=ae&&A.match_length<=A.prev_length){for(re=A.strstart+A.lookahead-ae,se=_._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-ae),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=re&&(A.ins_h=(A.ins_h<<A.hash_shift^A.window[A.strstart+ae-1])&A.hash_mask,Pe=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=ae-1,A.strstart++,se&&(ge(A,!1),A.strm.avail_out===0))return L}else if(A.match_available){if((se=_._tr_tally(A,0,A.window[A.strstart-1]))&&ge(A,!1),A.strstart++,A.lookahead--,A.strm.avail_out===0)return L}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<ae-1?A.strstart:ae-1,$e===E?(ge(A,!0),A.strm.avail_out===0?Xe:me):A.last_lit&&(ge(A,!1),A.strm.avail_out===0)?L:Se}function Ge(A,$e,Pe,se,re){this.good_length=A,this.max_lazy=$e,this.nice_length=Pe,this.max_chain=se,this.func=re}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=b,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 p.Buf16(2*j),this.dyn_dtree=new p.Buf16(2*(2*z+1)),this.bl_tree=new p.Buf16(2*(2*B+1)),Me(this.dyn_ltree),Me(this.dyn_dtree),Me(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new p.Buf16(N+1),this.heap=new p.Buf16(2*U+1),Me(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new p.Buf16(2*U+1),Me(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 $e;return A&&A.state?(A.total_in=A.total_out=0,A.data_type=w,($e=A.state).pending=0,$e.pending_out=0,$e.wrap<0&&($e.wrap=-$e.wrap),$e.status=$e.wrap?Y:_e,A.adler=$e.wrap===2?0:1,$e.last_flush=y,_._tr_init($e),T):X(A,O)}function Ye(A){var $e=je(A);return $e===T&&function(Pe){Pe.window_size=2*Pe.w_size,Me(Pe.head),Pe.max_lazy_match=l[Pe.level].max_lazy,Pe.good_match=l[Pe.level].good_length,Pe.nice_match=l[Pe.level].nice_length,Pe.max_chain_length=l[Pe.level].max_chain,Pe.strstart=0,Pe.block_start=0,Pe.lookahead=0,Pe.insert=0,Pe.match_length=Pe.prev_length=ae-1,Pe.match_available=0,Pe.ins_h=0}(A.state),$e}function et(A,$e,Pe,se,re,ye){if(!A)return O;var R=1;if($e===S&&($e=6),se<0?(R=0,se=-se):15<se&&(R=2,se-=16),re<1||I<re||Pe!==b||se<8||15<se||$e<0||9<$e||ye<0||C<ye)return X(A,O);se===8&&(se=9);var ee=new Te;return(A.state=ee).strm=A,ee.wrap=R,ee.gzhead=null,ee.w_bits=se,ee.w_size=1<<ee.w_bits,ee.w_mask=ee.w_size-1,ee.hash_bits=re+7,ee.hash_size=1<<ee.hash_bits,ee.hash_mask=ee.hash_size-1,ee.hash_shift=~~((ee.hash_bits+ae-1)/ae),ee.window=new p.Buf8(2*ee.w_size),ee.head=new p.Buf16(ee.hash_size),ee.prev=new p.Buf16(ee.w_size),ee.lit_bufsize=1<<re+6,ee.pending_buf_size=4*ee.lit_bufsize,ee.pending_buf=new p.Buf8(ee.pending_buf_size),ee.d_buf=1*ee.lit_bufsize,ee.l_buf=3*ee.lit_bufsize,ee.level=$e,ee.strategy=ye,ee.method=Pe,Ye(A)}l=[new Ge(0,0,0,0,function(A,$e){var Pe=65535;for(Pe>A.pending_buf_size-5&&(Pe=A.pending_buf_size-5);;){if(A.lookahead<=1){if(We(A),A.lookahead===0&&$e===y)return L;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var se=A.block_start+Pe;if((A.strstart===0||A.strstart>=se)&&(A.lookahead=A.strstart-se,A.strstart=se,ge(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-xe&&(ge(A,!1),A.strm.avail_out===0))return L}return A.insert=0,$e===E?(ge(A,!0),A.strm.avail_out===0?Xe:me):(A.strstart>A.block_start&&(ge(A,!1),A.strm.avail_out),L)}),new Ge(4,4,8,4,st),new Ge(4,5,16,8,st),new Ge(4,6,32,32,st),new Ge(4,4,16,16,pt),new Ge(8,16,32,32,pt),new Ge(8,16,128,128,pt),new Ge(8,32,128,256,pt),new Ge(32,128,258,1024,pt),new Ge(32,258,258,4096,pt)],a.deflateInit=function(A,$e){return et(A,$e,b,15,8,0)},a.deflateInit2=et,a.deflateReset=Ye,a.deflateResetKeep=je,a.deflateSetHeader=function(A,$e){return A&&A.state?A.state.wrap!==2?O:(A.state.gzhead=$e,T):O},a.deflate=function(A,$e){var Pe,se,re,ye;if(!A||!A.state||5<$e||$e<0)return A?X(A,O):O;if(se=A.state,!A.output||!A.input&&A.avail_in!==0||se.status===666&&$e!==E)return X(A,A.avail_out===0?-5:O);if(se.strm=A,Pe=se.last_flush,se.last_flush=$e,se.status===Y)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=_e);else{var R=b+(se.w_bits-8<<4)<<8;R|=(2<=se.strategy||se.level<2?0:se.level<6?1:se.level===6?2:3)<<6,se.strstart!==0&&(R|=32),R+=31-R%31,se.status=_e,Le(se,R),se.strstart!==0&&(Le(se,A.adler>>>16),Le(se,65535&A.adler)),A.adler=1}if(se.status===69)if(se.gzhead.extra){for(re=se.pending;se.gzindex<(65535&se.gzhead.extra.length)&&(se.pending!==se.pending_buf_size||(se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),Q(A),re=se.pending,se.pending!==se.pending_buf_size));)Ke(se,255&se.gzhead.extra[se.gzindex]),se.gzindex++;se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),se.gzindex===se.gzhead.extra.length&&(se.gzindex=0,se.status=73)}else se.status=73;if(se.status===73)if(se.gzhead.name){re=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),Q(A),re=se.pending,se.pending===se.pending_buf_size)){ye=1;break}ye=se.gzindex<se.gzhead.name.length?255&se.gzhead.name.charCodeAt(se.gzindex++):0,Ke(se,ye)}while(ye!==0);se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),ye===0&&(se.gzindex=0,se.status=91)}else se.status=91;if(se.status===91)if(se.gzhead.comment){re=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),Q(A),re=se.pending,se.pending===se.pending_buf_size)){ye=1;break}ye=se.gzindex<se.gzhead.comment.length?255&se.gzhead.comment.charCodeAt(se.gzindex++):0,Ke(se,ye)}while(ye!==0);se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),ye===0&&(se.status=103)}else se.status=103;if(se.status===103&&(se.gzhead.hcrc?(se.pending+2>se.pending_buf_size&&Q(A),se.pending+2<=se.pending_buf_size&&(Ke(se,255&A.adler),Ke(se,A.adler>>8&255),A.adler=0,se.status=_e)):se.status=_e),se.pending!==0){if(Q(A),A.avail_out===0)return se.last_flush=-1,T}else if(A.avail_in===0&&ie($e)<=ie(Pe)&&$e!==E)return X(A,-5);if(se.status===666&&A.avail_in!==0)return X(A,-5);if(A.avail_in!==0||se.lookahead!==0||$e!==y&&se.status!==666){var ee=se.strategy===2?function(D,ue){for(var le;;){if(D.lookahead===0&&(We(D),D.lookahead===0)){if(ue===y)return L;break}if(D.match_length=0,le=_._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++,le&&(ge(D,!1),D.strm.avail_out===0))return L}return D.insert=0,ue===E?(ge(D,!0),D.strm.avail_out===0?Xe:me):D.last_lit&&(ge(D,!1),D.strm.avail_out===0)?L:Se}(se,$e):se.strategy===3?function(D,ue){for(var le,ke,Ne,dt,Je=D.window;;){if(D.lookahead<=ce){if(We(D),D.lookahead<=ce&&ue===y)return L;if(D.lookahead===0)break}if(D.match_length=0,D.lookahead>=ae&&0<D.strstart&&(ke=Je[Ne=D.strstart-1])===Je[++Ne]&&ke===Je[++Ne]&&ke===Je[++Ne]){dt=D.strstart+ce;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<dt);D.match_length=ce-(dt-Ne),D.match_length>D.lookahead&&(D.match_length=D.lookahead)}if(D.match_length>=ae?(le=_._tr_tally(D,1,D.match_length-ae),D.lookahead-=D.match_length,D.strstart+=D.match_length,D.match_length=0):(le=_._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++),le&&(ge(D,!1),D.strm.avail_out===0))return L}return D.insert=0,ue===E?(ge(D,!0),D.strm.avail_out===0?Xe:me):D.last_lit&&(ge(D,!1),D.strm.avail_out===0)?L:Se}(se,$e):l[se.level].func(se,$e);if(ee!==Xe&&ee!==me||(se.status=666),ee===L||ee===Xe)return A.avail_out===0&&(se.last_flush=-1),T;if(ee===Se&&($e===1?_._tr_align(se):$e!==5&&(_._tr_stored_block(se,0,0,!1),$e===3&&(Me(se.head),se.lookahead===0&&(se.strstart=0,se.block_start=0,se.insert=0))),Q(A),A.avail_out===0))return se.last_flush=-1,T}return $e!==E?T: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)):(Le(se,A.adler>>>16),Le(se,65535&A.adler)),Q(A),0<se.wrap&&(se.wrap=-se.wrap),se.pending!==0?T:1)},a.deflateEnd=function(A){var $e;return A&&A.state?($e=A.state.status)!==Y&&$e!==69&&$e!==73&&$e!==91&&$e!==103&&$e!==_e&&$e!==666?X(A,O):(A.state=null,$e===_e?X(A,-3):T):O},a.deflateSetDictionary=function(A,$e){var Pe,se,re,ye,R,ee,D,ue,le=$e.length;if(!A||!A.state||(ye=(Pe=A.state).wrap)===2||ye===1&&Pe.status!==Y||Pe.lookahead)return O;for(ye===1&&(A.adler=h(A.adler,$e,le,0)),Pe.wrap=0,le>=Pe.w_size&&(ye===0&&(Me(Pe.head),Pe.strstart=0,Pe.block_start=0,Pe.insert=0),ue=new p.Buf8(Pe.w_size),p.arraySet(ue,$e,le-Pe.w_size,Pe.w_size,0),$e=ue,le=Pe.w_size),R=A.avail_in,ee=A.next_in,D=A.input,A.avail_in=le,A.next_in=0,A.input=$e,We(Pe);Pe.lookahead>=ae;){for(se=Pe.strstart,re=Pe.lookahead-(ae-1);Pe.ins_h=(Pe.ins_h<<Pe.hash_shift^Pe.window[se+ae-1])&Pe.hash_mask,Pe.prev[se&Pe.w_mask]=Pe.head[Pe.ins_h],Pe.head[Pe.ins_h]=se,se++,--re;);Pe.strstart=se,Pe.lookahead=ae-1,We(Pe)}return Pe.strstart+=Pe.lookahead,Pe.block_start=Pe.strstart,Pe.insert=Pe.lookahead,Pe.lookahead=0,Pe.match_length=Pe.prev_length=ae-1,Pe.match_available=0,A.next_in=ee,A.input=D,A.avail_in=R,Pe.wrap=ye,T},a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(r,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(r,o,a){o.exports=function(l,p){var _,h,g,M,y,E,T,O,S,C,w,b,I,U,z,B,j,N,ae,ce,xe,Y,_e,L,Se;_=l.state,h=l.next_in,L=l.input,g=h+(l.avail_in-5),M=l.next_out,Se=l.output,y=M-(p-l.avail_out),E=M+(l.avail_out-257),T=_.dmax,O=_.wsize,S=_.whave,C=_.wnext,w=_.window,b=_.hold,I=_.bits,U=_.lencode,z=_.distcode,B=(1<<_.lenbits)-1,j=(1<<_.distbits)-1;e:do{I<15&&(b+=L[h++]<<I,I+=8,b+=L[h++]<<I,I+=8),N=U[b&B];t:for(;;){if(b>>>=ae=N>>>24,I-=ae,(ae=N>>>16&255)===0)Se[M++]=65535&N;else{if(!(16&ae)){if(!(64&ae)){N=U[(65535&N)+(b&(1<<ae)-1)];continue t}if(32&ae){_.mode=12;break e}l.msg="invalid literal/length code",_.mode=30;break e}ce=65535&N,(ae&=15)&&(I<ae&&(b+=L[h++]<<I,I+=8),ce+=b&(1<<ae)-1,b>>>=ae,I-=ae),I<15&&(b+=L[h++]<<I,I+=8,b+=L[h++]<<I,I+=8),N=z[b&j];r:for(;;){if(b>>>=ae=N>>>24,I-=ae,!(16&(ae=N>>>16&255))){if(!(64&ae)){N=z[(65535&N)+(b&(1<<ae)-1)];continue r}l.msg="invalid distance code",_.mode=30;break e}if(xe=65535&N,I<(ae&=15)&&(b+=L[h++]<<I,(I+=8)<ae&&(b+=L[h++]<<I,I+=8)),T<(xe+=b&(1<<ae)-1)){l.msg="invalid distance too far back",_.mode=30;break e}if(b>>>=ae,I-=ae,(ae=M-y)<xe){if(S<(ae=xe-ae)&&_.sane){l.msg="invalid distance too far back",_.mode=30;break e}if(_e=w,(Y=0)===C){if(Y+=O-ae,ae<ce){for(ce-=ae;Se[M++]=w[Y++],--ae;);Y=M-xe,_e=Se}}else if(C<ae){if(Y+=O+C-ae,(ae-=C)<ce){for(ce-=ae;Se[M++]=w[Y++],--ae;);if(Y=0,C<ce){for(ce-=ae=C;Se[M++]=w[Y++],--ae;);Y=M-xe,_e=Se}}}else if(Y+=C-ae,ae<ce){for(ce-=ae;Se[M++]=w[Y++],--ae;);Y=M-xe,_e=Se}for(;2<ce;)Se[M++]=_e[Y++],Se[M++]=_e[Y++],Se[M++]=_e[Y++],ce-=3;ce&&(Se[M++]=_e[Y++],1<ce&&(Se[M++]=_e[Y++]))}else{for(Y=M-xe;Se[M++]=Se[Y++],Se[M++]=Se[Y++],Se[M++]=Se[Y++],2<(ce-=3););ce&&(Se[M++]=Se[Y++],1<ce&&(Se[M++]=Se[Y++]))}break}}break}}while(h<g&&M<E);h-=ce=I>>3,b&=(1<<(I-=ce<<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<E?E-M+257:257-(M-E),_.hold=b,_.bits=I}},{}],49:[function(r,o,a){var l=r("../utils/common"),p=r("./adler32"),_=r("./crc32"),h=r("./inffast"),g=r("./inftrees"),M=1,y=2,E=0,T=-2,O=1,S=852,C=592;function w(Y){return(Y>>>24&255)+(Y>>>8&65280)+((65280&Y)<<8)+((255&Y)<<24)}function b(){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(Y){var _e;return Y&&Y.state?(_e=Y.state,Y.total_in=Y.total_out=_e.total=0,Y.msg="",_e.wrap&&(Y.adler=1&_e.wrap),_e.mode=O,_e.last=0,_e.havedict=0,_e.dmax=32768,_e.head=null,_e.hold=0,_e.bits=0,_e.lencode=_e.lendyn=new l.Buf32(S),_e.distcode=_e.distdyn=new l.Buf32(C),_e.sane=1,_e.back=-1,E):T}function U(Y){var _e;return Y&&Y.state?((_e=Y.state).wsize=0,_e.whave=0,_e.wnext=0,I(Y)):T}function z(Y,_e){var L,Se;return Y&&Y.state?(Se=Y.state,_e<0?(L=0,_e=-_e):(L=1+(_e>>4),_e<48&&(_e&=15)),_e&&(_e<8||15<_e)?T:(Se.window!==null&&Se.wbits!==_e&&(Se.window=null),Se.wrap=L,Se.wbits=_e,U(Y))):T}function B(Y,_e){var L,Se;return Y?(Se=new b,(Y.state=Se).window=null,(L=z(Y,_e))!==E&&(Y.state=null),L):T}var j,N,ae=!0;function ce(Y){if(ae){var _e;for(j=new l.Buf32(512),N=new l.Buf32(32),_e=0;_e<144;)Y.lens[_e++]=8;for(;_e<256;)Y.lens[_e++]=9;for(;_e<280;)Y.lens[_e++]=7;for(;_e<288;)Y.lens[_e++]=8;for(g(M,Y.lens,0,288,j,0,Y.work,{bits:9}),_e=0;_e<32;)Y.lens[_e++]=5;g(y,Y.lens,0,32,N,0,Y.work,{bits:5}),ae=!1}Y.lencode=j,Y.lenbits=9,Y.distcode=N,Y.distbits=5}function xe(Y,_e,L,Se){var Xe,me=Y.state;return me.window===null&&(me.wsize=1<<me.wbits,me.wnext=0,me.whave=0,me.window=new l.Buf8(me.wsize)),Se>=me.wsize?(l.arraySet(me.window,_e,L-me.wsize,me.wsize,0),me.wnext=0,me.whave=me.wsize):(Se<(Xe=me.wsize-me.wnext)&&(Xe=Se),l.arraySet(me.window,_e,L-Se,Xe,me.wnext),(Se-=Xe)?(l.arraySet(me.window,_e,L-Se,Se,0),me.wnext=Se,me.whave=me.wsize):(me.wnext+=Xe,me.wnext===me.wsize&&(me.wnext=0),me.whave<me.wsize&&(me.whave+=Xe))),0}a.inflateReset=U,a.inflateReset2=z,a.inflateResetKeep=I,a.inflateInit=function(Y){return B(Y,15)},a.inflateInit2=B,a.inflate=function(Y,_e){var L,Se,Xe,me,X,ie,Me,Q,ge,Ke,Le,Be,We,st,pt,Ge,Te,je,Ye,et,A,$e,Pe,se,re=0,ye=new l.Buf8(4),R=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!Y||!Y.state||!Y.output||!Y.input&&Y.avail_in!==0)return T;(L=Y.state).mode===12&&(L.mode=13),X=Y.next_out,Xe=Y.output,Me=Y.avail_out,me=Y.next_in,Se=Y.input,ie=Y.avail_in,Q=L.hold,ge=L.bits,Ke=ie,Le=Me,$e=E;e:for(;;)switch(L.mode){case O:if(L.wrap===0){L.mode=13;break}for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(2&L.wrap&&Q===35615){ye[L.check=0]=255&Q,ye[1]=Q>>>8&255,L.check=_(L.check,ye,2,0),ge=Q=0,L.mode=2;break}if(L.flags=0,L.head&&(L.head.done=!1),!(1&L.wrap)||(((255&Q)<<8)+(Q>>8))%31){Y.msg="incorrect header check",L.mode=30;break}if((15&Q)!=8){Y.msg="unknown compression method",L.mode=30;break}if(ge-=4,A=8+(15&(Q>>>=4)),L.wbits===0)L.wbits=A;else if(A>L.wbits){Y.msg="invalid window size",L.mode=30;break}L.dmax=1<<A,Y.adler=L.check=1,L.mode=512&Q?10:12,ge=Q=0;break;case 2:for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(L.flags=Q,(255&L.flags)!=8){Y.msg="unknown compression method",L.mode=30;break}if(57344&L.flags){Y.msg="unknown header flags set",L.mode=30;break}L.head&&(L.head.text=Q>>8&1),512&L.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,L.check=_(L.check,ye,2,0)),ge=Q=0,L.mode=3;case 3:for(;ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}L.head&&(L.head.time=Q),512&L.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,ye[2]=Q>>>16&255,ye[3]=Q>>>24&255,L.check=_(L.check,ye,4,0)),ge=Q=0,L.mode=4;case 4:for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}L.head&&(L.head.xflags=255&Q,L.head.os=Q>>8),512&L.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,L.check=_(L.check,ye,2,0)),ge=Q=0,L.mode=5;case 5:if(1024&L.flags){for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}L.length=Q,L.head&&(L.head.extra_len=Q),512&L.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,L.check=_(L.check,ye,2,0)),ge=Q=0}else L.head&&(L.head.extra=null);L.mode=6;case 6:if(1024&L.flags&&(ie<(Be=L.length)&&(Be=ie),Be&&(L.head&&(A=L.head.extra_len-L.length,L.head.extra||(L.head.extra=new Array(L.head.extra_len)),l.arraySet(L.head.extra,Se,me,Be,A)),512&L.flags&&(L.check=_(L.check,Se,Be,me)),ie-=Be,me+=Be,L.length-=Be),L.length))break e;L.length=0,L.mode=7;case 7:if(2048&L.flags){if(ie===0)break e;for(Be=0;A=Se[me+Be++],L.head&&A&&L.length<65536&&(L.head.name+=String.fromCharCode(A)),A&&Be<ie;);if(512&L.flags&&(L.check=_(L.check,Se,Be,me)),ie-=Be,me+=Be,A)break e}else L.head&&(L.head.name=null);L.length=0,L.mode=8;case 8:if(4096&L.flags){if(ie===0)break e;for(Be=0;A=Se[me+Be++],L.head&&A&&L.length<65536&&(L.head.comment+=String.fromCharCode(A)),A&&Be<ie;);if(512&L.flags&&(L.check=_(L.check,Se,Be,me)),ie-=Be,me+=Be,A)break e}else L.head&&(L.head.comment=null);L.mode=9;case 9:if(512&L.flags){for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(Q!==(65535&L.check)){Y.msg="header crc mismatch",L.mode=30;break}ge=Q=0}L.head&&(L.head.hcrc=L.flags>>9&1,L.head.done=!0),Y.adler=L.check=0,L.mode=12;break;case 10:for(;ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}Y.adler=L.check=w(Q),ge=Q=0,L.mode=11;case 11:if(L.havedict===0)return Y.next_out=X,Y.avail_out=Me,Y.next_in=me,Y.avail_in=ie,L.hold=Q,L.bits=ge,2;Y.adler=L.check=1,L.mode=12;case 12:if(_e===5||_e===6)break e;case 13:if(L.last){Q>>>=7&ge,ge-=7&ge,L.mode=27;break}for(;ge<3;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}switch(L.last=1&Q,ge-=1,3&(Q>>>=1)){case 0:L.mode=14;break;case 1:if(ce(L),L.mode=20,_e!==6)break;Q>>>=2,ge-=2;break e;case 2:L.mode=17;break;case 3:Y.msg="invalid block type",L.mode=30}Q>>>=2,ge-=2;break;case 14:for(Q>>>=7&ge,ge-=7≥ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if((65535&Q)!=(Q>>>16^65535)){Y.msg="invalid stored block lengths",L.mode=30;break}if(L.length=65535&Q,ge=Q=0,L.mode=15,_e===6)break e;case 15:L.mode=16;case 16:if(Be=L.length){if(ie<Be&&(Be=ie),Me<Be&&(Be=Me),Be===0)break e;l.arraySet(Xe,Se,me,Be,X),ie-=Be,me+=Be,Me-=Be,X+=Be,L.length-=Be;break}L.mode=12;break;case 17:for(;ge<14;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(L.nlen=257+(31&Q),Q>>>=5,ge-=5,L.ndist=1+(31&Q),Q>>>=5,ge-=5,L.ncode=4+(15&Q),Q>>>=4,ge-=4,286<L.nlen||30<L.ndist){Y.msg="too many length or distance symbols",L.mode=30;break}L.have=0,L.mode=18;case 18:for(;L.have<L.ncode;){for(;ge<3;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}L.lens[R[L.have++]]=7&Q,Q>>>=3,ge-=3}for(;L.have<19;)L.lens[R[L.have++]]=0;if(L.lencode=L.lendyn,L.lenbits=7,Pe={bits:L.lenbits},$e=g(0,L.lens,0,19,L.lencode,0,L.work,Pe),L.lenbits=Pe.bits,$e){Y.msg="invalid code lengths set",L.mode=30;break}L.have=0,L.mode=19;case 19:for(;L.have<L.nlen+L.ndist;){for(;Ge=(re=L.lencode[Q&(1<<L.lenbits)-1])>>>16&255,Te=65535&re,!((pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(Te<16)Q>>>=pt,ge-=pt,L.lens[L.have++]=Te;else{if(Te===16){for(se=pt+2;ge<se;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(Q>>>=pt,ge-=pt,L.have===0){Y.msg="invalid bit length repeat",L.mode=30;break}A=L.lens[L.have-1],Be=3+(3&Q),Q>>>=2,ge-=2}else if(Te===17){for(se=pt+3;ge<se;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}ge-=pt,A=0,Be=3+(7&(Q>>>=pt)),Q>>>=3,ge-=3}else{for(se=pt+7;ge<se;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}ge-=pt,A=0,Be=11+(127&(Q>>>=pt)),Q>>>=7,ge-=7}if(L.have+Be>L.nlen+L.ndist){Y.msg="invalid bit length repeat",L.mode=30;break}for(;Be--;)L.lens[L.have++]=A}}if(L.mode===30)break;if(L.lens[256]===0){Y.msg="invalid code -- missing end-of-block",L.mode=30;break}if(L.lenbits=9,Pe={bits:L.lenbits},$e=g(M,L.lens,0,L.nlen,L.lencode,0,L.work,Pe),L.lenbits=Pe.bits,$e){Y.msg="invalid literal/lengths set",L.mode=30;break}if(L.distbits=6,L.distcode=L.distdyn,Pe={bits:L.distbits},$e=g(y,L.lens,L.nlen,L.ndist,L.distcode,0,L.work,Pe),L.distbits=Pe.bits,$e){Y.msg="invalid distances set",L.mode=30;break}if(L.mode=20,_e===6)break e;case 20:L.mode=21;case 21:if(6<=ie&&258<=Me){Y.next_out=X,Y.avail_out=Me,Y.next_in=me,Y.avail_in=ie,L.hold=Q,L.bits=ge,h(Y,Le),X=Y.next_out,Xe=Y.output,Me=Y.avail_out,me=Y.next_in,Se=Y.input,ie=Y.avail_in,Q=L.hold,ge=L.bits,L.mode===12&&(L.back=-1);break}for(L.back=0;Ge=(re=L.lencode[Q&(1<<L.lenbits)-1])>>>16&255,Te=65535&re,!((pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(Ge&&!(240&Ge)){for(je=pt,Ye=Ge,et=Te;Ge=(re=L.lencode[et+((Q&(1<<je+Ye)-1)>>je)])>>>16&255,Te=65535&re,!(je+(pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}Q>>>=je,ge-=je,L.back+=je}if(Q>>>=pt,ge-=pt,L.back+=pt,L.length=Te,Ge===0){L.mode=26;break}if(32&Ge){L.back=-1,L.mode=12;break}if(64&Ge){Y.msg="invalid literal/length code",L.mode=30;break}L.extra=15&Ge,L.mode=22;case 22:if(L.extra){for(se=L.extra;ge<se;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}L.length+=Q&(1<<L.extra)-1,Q>>>=L.extra,ge-=L.extra,L.back+=L.extra}L.was=L.length,L.mode=23;case 23:for(;Ge=(re=L.distcode[Q&(1<<L.distbits)-1])>>>16&255,Te=65535&re,!((pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(!(240&Ge)){for(je=pt,Ye=Ge,et=Te;Ge=(re=L.distcode[et+((Q&(1<<je+Ye)-1)>>je)])>>>16&255,Te=65535&re,!(je+(pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}Q>>>=je,ge-=je,L.back+=je}if(Q>>>=pt,ge-=pt,L.back+=pt,64&Ge){Y.msg="invalid distance code",L.mode=30;break}L.offset=Te,L.extra=15&Ge,L.mode=24;case 24:if(L.extra){for(se=L.extra;ge<se;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}L.offset+=Q&(1<<L.extra)-1,Q>>>=L.extra,ge-=L.extra,L.back+=L.extra}if(L.offset>L.dmax){Y.msg="invalid distance too far back",L.mode=30;break}L.mode=25;case 25:if(Me===0)break e;if(Be=Le-Me,L.offset>Be){if((Be=L.offset-Be)>L.whave&&L.sane){Y.msg="invalid distance too far back",L.mode=30;break}We=Be>L.wnext?(Be-=L.wnext,L.wsize-Be):L.wnext-Be,Be>L.length&&(Be=L.length),st=L.window}else st=Xe,We=X-L.offset,Be=L.length;for(Me<Be&&(Be=Me),Me-=Be,L.length-=Be;Xe[X++]=st[We++],--Be;);L.length===0&&(L.mode=21);break;case 26:if(Me===0)break e;Xe[X++]=L.length,Me--,L.mode=21;break;case 27:if(L.wrap){for(;ge<32;){if(ie===0)break e;ie--,Q|=Se[me++]<<ge,ge+=8}if(Le-=Me,Y.total_out+=Le,L.total+=Le,Le&&(Y.adler=L.check=L.flags?_(L.check,Xe,Le,X-Le):p(L.check,Xe,Le,X-Le)),Le=Me,(L.flags?Q:w(Q))!==L.check){Y.msg="incorrect data check",L.mode=30;break}ge=Q=0}L.mode=28;case 28:if(L.wrap&&L.flags){for(;ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<<ge,ge+=8}if(Q!==(4294967295&L.total)){Y.msg="incorrect length check",L.mode=30;break}ge=Q=0}L.mode=29;case 29:$e=1;break e;case 30:$e=-3;break e;case 31:return-4;case 32:default:return T}return Y.next_out=X,Y.avail_out=Me,Y.next_in=me,Y.avail_in=ie,L.hold=Q,L.bits=ge,(L.wsize||Le!==Y.avail_out&&L.mode<30&&(L.mode<27||_e!==4))&&xe(Y,Y.output,Y.next_out,Le-Y.avail_out)?(L.mode=31,-4):(Ke-=Y.avail_in,Le-=Y.avail_out,Y.total_in+=Ke,Y.total_out+=Le,L.total+=Le,L.wrap&&Le&&(Y.adler=L.check=L.flags?_(L.check,Xe,Le,Y.next_out-Le):p(L.check,Xe,Le,Y.next_out-Le)),Y.data_type=L.bits+(L.last?64:0)+(L.mode===12?128:0)+(L.mode===20||L.mode===15?256:0),(Ke==0&&Le===0||_e===4)&&$e===E&&($e=-5),$e)},a.inflateEnd=function(Y){if(!Y||!Y.state)return T;var _e=Y.state;return _e.window&&(_e.window=null),Y.state=null,E},a.inflateGetHeader=function(Y,_e){var L;return Y&&Y.state&&2&(L=Y.state).wrap?((L.head=_e).done=!1,E):T},a.inflateSetDictionary=function(Y,_e){var L,Se=_e.length;return Y&&Y.state?(L=Y.state).wrap!==0&&L.mode!==11?T:L.mode===11&&p(1,_e,Se,0)!==L.check?-3:xe(Y,_e,Se,Se)?(L.mode=31,-4):(L.havedict=1,E):T},a.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(r,o,a){var l=r("../utils/common"),p=[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,y,E,T,O,S,C,w){var b,I,U,z,B,j,N,ae,ce,xe=w.bits,Y=0,_e=0,L=0,Se=0,Xe=0,me=0,X=0,ie=0,Me=0,Q=0,ge=null,Ke=0,Le=new l.Buf16(16),Be=new l.Buf16(16),We=null,st=0;for(Y=0;Y<=15;Y++)Le[Y]=0;for(_e=0;_e<T;_e++)Le[y[E+_e]]++;for(Xe=xe,Se=15;1<=Se&&Le[Se]===0;Se--);if(Se<Xe&&(Xe=Se),Se===0)return O[S++]=20971520,O[S++]=20971520,w.bits=1,0;for(L=1;L<Se&&Le[L]===0;L++);for(Xe<L&&(Xe=L),Y=ie=1;Y<=15;Y++)if(ie<<=1,(ie-=Le[Y])<0)return-1;if(0<ie&&(M===0||Se!==1))return-1;for(Be[1]=0,Y=1;Y<15;Y++)Be[Y+1]=Be[Y]+Le[Y];for(_e=0;_e<T;_e++)y[E+_e]!==0&&(C[Be[y[E+_e]]++]=_e);if(j=M===0?(ge=We=C,19):M===1?(ge=p,Ke-=257,We=_,st-=257,256):(ge=h,We=g,-1),Y=L,B=S,X=_e=Q=0,U=-1,z=(Me=1<<(me=Xe))-1,M===1&&852<Me||M===2&&592<Me)return 1;for(;;){for(N=Y-X,ce=C[_e]<j?(ae=0,C[_e]):C[_e]>j?(ae=We[st+C[_e]],ge[Ke+C[_e]]):(ae=96,0),b=1<<Y-X,L=I=1<<me;O[B+(Q>>X)+(I-=b)]=N<<24|ae<<16|ce|0,I!==0;);for(b=1<<Y-1;Q&b;)b>>=1;if(b!==0?(Q&=b-1,Q+=b):Q=0,_e++,--Le[Y]==0){if(Y===Se)break;Y=y[E+C[_e]]}if(Xe<Y&&(Q&z)!==U){for(X===0&&(X=Xe),B+=L,ie=1<<(me=Y-X);me+X<Se&&!((ie-=Le[me+X])<=0);)me++,ie<<=1;if(Me+=1<<me,M===1&&852<Me||M===2&&592<Me)return 1;O[U=Q&z]=Xe<<24|me<<16|B-S|0}}return Q!==0&&(O[B+Q]=Y-X<<24|64<<16|0),w.bits=Xe,0}},{"../utils/common":41}],51:[function(r,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(r,o,a){var l=r("../utils/common"),p=0,_=1;function h(re){for(var ye=re.length;0<=--ye;)re[ye]=0}var g=0,M=29,y=256,E=y+1+M,T=30,O=19,S=2*E+1,C=15,w=16,b=7,I=256,U=16,z=17,B=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],N=[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],ae=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ce=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],xe=new Array(2*(E+2));h(xe);var Y=new Array(2*T);h(Y);var _e=new Array(512);h(_e);var L=new Array(256);h(L);var Se=new Array(M);h(Se);var Xe,me,X,ie=new Array(T);function Me(re,ye,R,ee,D){this.static_tree=re,this.extra_bits=ye,this.extra_base=R,this.elems=ee,this.max_length=D,this.has_stree=re&&re.length}function Q(re,ye){this.dyn_tree=re,this.max_code=0,this.stat_desc=ye}function ge(re){return re<256?_e[re]:_e[256+(re>>>7)]}function Ke(re,ye){re.pending_buf[re.pending++]=255&ye,re.pending_buf[re.pending++]=ye>>>8&255}function Le(re,ye,R){re.bi_valid>w-R?(re.bi_buf|=ye<<re.bi_valid&65535,Ke(re,re.bi_buf),re.bi_buf=ye>>w-re.bi_valid,re.bi_valid+=R-w):(re.bi_buf|=ye<<re.bi_valid&65535,re.bi_valid+=R)}function Be(re,ye,R){Le(re,R[2*ye],R[2*ye+1])}function We(re,ye){for(var R=0;R|=1&re,re>>>=1,R<<=1,0<--ye;);return R>>>1}function st(re,ye,R){var ee,D,ue=new Array(C+1),le=0;for(ee=1;ee<=C;ee++)ue[ee]=le=le+R[ee-1]<<1;for(D=0;D<=ye;D++){var ke=re[2*D+1];ke!==0&&(re[2*D]=We(ue[ke]++,ke))}}function pt(re){var ye;for(ye=0;ye<E;ye++)re.dyn_ltree[2*ye]=0;for(ye=0;ye<T;ye++)re.dyn_dtree[2*ye]=0;for(ye=0;ye<O;ye++)re.bl_tree[2*ye]=0;re.dyn_ltree[2*I]=1,re.opt_len=re.static_len=0,re.last_lit=re.matches=0}function Ge(re){8<re.bi_valid?Ke(re,re.bi_buf):0<re.bi_valid&&(re.pending_buf[re.pending++]=re.bi_buf),re.bi_buf=0,re.bi_valid=0}function Te(re,ye,R,ee){var D=2*ye,ue=2*R;return re[D]<re[ue]||re[D]===re[ue]&&ee[ye]<=ee[R]}function je(re,ye,R){for(var ee=re.heap[R],D=R<<1;D<=re.heap_len&&(D<re.heap_len&&Te(ye,re.heap[D+1],re.heap[D],re.depth)&&D++,!Te(ye,ee,re.heap[D],re.depth));)re.heap[R]=re.heap[D],R=D,D<<=1;re.heap[R]=ee}function Ye(re,ye,R){var ee,D,ue,le,ke=0;if(re.last_lit!==0)for(;ee=re.pending_buf[re.d_buf+2*ke]<<8|re.pending_buf[re.d_buf+2*ke+1],D=re.pending_buf[re.l_buf+ke],ke++,ee===0?Be(re,D,ye):(Be(re,(ue=L[D])+y+1,ye),(le=j[ue])!==0&&Le(re,D-=Se[ue],le),Be(re,ue=ge(--ee),R),(le=N[ue])!==0&&Le(re,ee-=ie[ue],le)),ke<re.last_lit;);Be(re,I,ye)}function et(re,ye){var R,ee,D,ue=ye.dyn_tree,le=ye.stat_desc.static_tree,ke=ye.stat_desc.has_stree,Ne=ye.stat_desc.elems,dt=-1;for(re.heap_len=0,re.heap_max=S,R=0;R<Ne;R++)ue[2*R]!==0?(re.heap[++re.heap_len]=dt=R,re.depth[R]=0):ue[2*R+1]=0;for(;re.heap_len<2;)ue[2*(D=re.heap[++re.heap_len]=dt<2?++dt:0)]=1,re.depth[D]=0,re.opt_len--,ke&&(re.static_len-=le[2*D+1]);for(ye.max_code=dt,R=re.heap_len>>1;1<=R;R--)je(re,ue,R);for(D=Ne;R=re.heap[1],re.heap[1]=re.heap[re.heap_len--],je(re,ue,1),ee=re.heap[1],re.heap[--re.heap_max]=R,re.heap[--re.heap_max]=ee,ue[2*D]=ue[2*R]+ue[2*ee],re.depth[D]=(re.depth[R]>=re.depth[ee]?re.depth[R]:re.depth[ee])+1,ue[2*R+1]=ue[2*ee+1]=D,re.heap[1]=D++,je(re,ue,1),2<=re.heap_len;);re.heap[--re.heap_max]=re.heap[1],function(Je,Ve){var Z,ve,Re,qe,Qe,tt,ft=Ve.dyn_tree,ht=Ve.max_code,Tt=Ve.stat_desc.static_tree,bt=Ve.stat_desc.has_stree,Et=Ve.stat_desc.extra_bits,Lt=Ve.stat_desc.extra_base,at=Ve.stat_desc.max_length,Ot=0;for(qe=0;qe<=C;qe++)Je.bl_count[qe]=0;for(ft[2*Je.heap[Je.heap_max]+1]=0,Z=Je.heap_max+1;Z<S;Z++)at<(qe=ft[2*ft[2*(ve=Je.heap[Z])+1]+1]+1)&&(qe=at,Ot++),ft[2*ve+1]=qe,ht<ve||(Je.bl_count[qe]++,Qe=0,Lt<=ve&&(Qe=Et[ve-Lt]),tt=ft[2*ve],Je.opt_len+=tt*(qe+Qe),bt&&(Je.static_len+=tt*(Tt[2*ve+1]+Qe)));if(Ot!==0){do{for(qe=at-1;Je.bl_count[qe]===0;)qe--;Je.bl_count[qe]--,Je.bl_count[qe+1]+=2,Je.bl_count[at]--,Ot-=2}while(0<Ot);for(qe=at;qe!==0;qe--)for(ve=Je.bl_count[qe];ve!==0;)ht<(Re=Je.heap[--Z])||(ft[2*Re+1]!==qe&&(Je.opt_len+=(qe-ft[2*Re+1])*ft[2*Re],ft[2*Re+1]=qe),ve--)}}(re,ye),st(ue,dt,re.bl_count)}function A(re,ye,R){var ee,D,ue=-1,le=ye[1],ke=0,Ne=7,dt=4;for(le===0&&(Ne=138,dt=3),ye[2*(R+1)+1]=65535,ee=0;ee<=R;ee++)D=le,le=ye[2*(ee+1)+1],++ke<Ne&&D===le||(ke<dt?re.bl_tree[2*D]+=ke:D!==0?(D!==ue&&re.bl_tree[2*D]++,re.bl_tree[2*U]++):ke<=10?re.bl_tree[2*z]++:re.bl_tree[2*B]++,ue=D,dt=(ke=0)===le?(Ne=138,3):D===le?(Ne=6,3):(Ne=7,4))}function $e(re,ye,R){var ee,D,ue=-1,le=ye[1],ke=0,Ne=7,dt=4;for(le===0&&(Ne=138,dt=3),ee=0;ee<=R;ee++)if(D=le,le=ye[2*(ee+1)+1],!(++ke<Ne&&D===le)){if(ke<dt)for(;Be(re,D,re.bl_tree),--ke!=0;);else D!==0?(D!==ue&&(Be(re,D,re.bl_tree),ke--),Be(re,U,re.bl_tree),Le(re,ke-3,2)):ke<=10?(Be(re,z,re.bl_tree),Le(re,ke-3,3)):(Be(re,B,re.bl_tree),Le(re,ke-11,7));ue=D,dt=(ke=0)===le?(Ne=138,3):D===le?(Ne=6,3):(Ne=7,4)}}h(ie);var Pe=!1;function se(re,ye,R,ee){Le(re,(g<<1)+(ee?1:0),3),function(D,ue,le,ke){Ge(D),Ke(D,le),Ke(D,~le),l.arraySet(D.pending_buf,D.window,ue,le,D.pending),D.pending+=le}(re,ye,R)}a._tr_init=function(re){Pe||(function(){var ye,R,ee,D,ue,le=new Array(C+1);for(D=ee=0;D<M-1;D++)for(Se[D]=ee,ye=0;ye<1<<j[D];ye++)L[ee++]=D;for(L[ee-1]=D,D=ue=0;D<16;D++)for(ie[D]=ue,ye=0;ye<1<<N[D];ye++)_e[ue++]=D;for(ue>>=7;D<T;D++)for(ie[D]=ue<<7,ye=0;ye<1<<N[D]-7;ye++)_e[256+ue++]=D;for(R=0;R<=C;R++)le[R]=0;for(ye=0;ye<=143;)xe[2*ye+1]=8,ye++,le[8]++;for(;ye<=255;)xe[2*ye+1]=9,ye++,le[9]++;for(;ye<=279;)xe[2*ye+1]=7,ye++,le[7]++;for(;ye<=287;)xe[2*ye+1]=8,ye++,le[8]++;for(st(xe,E+1,le),ye=0;ye<T;ye++)Y[2*ye+1]=5,Y[2*ye]=We(ye,5);Xe=new Me(xe,j,y+1,E,C),me=new Me(Y,N,0,T,C),X=new Me(new Array(0),ae,0,O,b)}(),Pe=!0),re.l_desc=new Q(re.dyn_ltree,Xe),re.d_desc=new Q(re.dyn_dtree,me),re.bl_desc=new Q(re.bl_tree,X),re.bi_buf=0,re.bi_valid=0,pt(re)},a._tr_stored_block=se,a._tr_flush_block=function(re,ye,R,ee){var D,ue,le=0;0<re.level?(re.strm.data_type===2&&(re.strm.data_type=function(ke){var Ne,dt=4093624447;for(Ne=0;Ne<=31;Ne++,dt>>>=1)if(1&dt&&ke.dyn_ltree[2*Ne]!==0)return p;if(ke.dyn_ltree[18]!==0||ke.dyn_ltree[20]!==0||ke.dyn_ltree[26]!==0)return _;for(Ne=32;Ne<y;Ne++)if(ke.dyn_ltree[2*Ne]!==0)return _;return p}(re)),et(re,re.l_desc),et(re,re.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),et(ke,ke.bl_desc),Ne=O-1;3<=Ne&&ke.bl_tree[2*ce[Ne]+1]===0;Ne--);return ke.opt_len+=3*(Ne+1)+5+5+4,Ne}(re),D=re.opt_len+3+7>>>3,(ue=re.static_len+3+7>>>3)<=D&&(D=ue)):D=ue=R+5,R+4<=D&&ye!==-1?se(re,ye,R,ee):re.strategy===4||ue===D?(Le(re,2+(ee?1:0),3),Ye(re,xe,Y)):(Le(re,4+(ee?1:0),3),function(ke,Ne,dt,Je){var Ve;for(Le(ke,Ne-257,5),Le(ke,dt-1,5),Le(ke,Je-4,4),Ve=0;Ve<Je;Ve++)Le(ke,ke.bl_tree[2*ce[Ve]+1],3);$e(ke,ke.dyn_ltree,Ne-1),$e(ke,ke.dyn_dtree,dt-1)}(re,re.l_desc.max_code+1,re.d_desc.max_code+1,le+1),Ye(re,re.dyn_ltree,re.dyn_dtree)),pt(re),ee&&Ge(re)},a._tr_tally=function(re,ye,R){return re.pending_buf[re.d_buf+2*re.last_lit]=ye>>>8&255,re.pending_buf[re.d_buf+2*re.last_lit+1]=255&ye,re.pending_buf[re.l_buf+re.last_lit]=255&R,re.last_lit++,ye===0?re.dyn_ltree[2*R]++:(re.matches++,ye--,re.dyn_ltree[2*(L[R]+y+1)]++,re.dyn_dtree[2*ge(ye)]++),re.last_lit===re.lit_bufsize-1},a._tr_align=function(re){Le(re,2,3),Be(re,I,xe),function(ye){ye.bi_valid===16?(Ke(ye,ye.bi_buf),ye.bi_buf=0,ye.bi_valid=0):8<=ye.bi_valid&&(ye.pending_buf[ye.pending++]=255&ye.bi_buf,ye.bi_buf>>=8,ye.bi_valid-=8)}(re)}},{"../utils/common":41}],53:[function(r,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(r,o,a){(function(l){(function(p,_){if(!p.setImmediate){var h,g,M,y,E=1,T={},O=!1,S=p.document,C=Object.getPrototypeOf&&Object.getPrototypeOf(p);C=C&&C.setTimeout?C:p,h={}.toString.call(p.process)==="[object process]"?function(U){process.nextTick(function(){b(U)})}:function(){if(p.postMessage&&!p.importScripts){var U=!0,z=p.onmessage;return p.onmessage=function(){U=!1},p.postMessage("","*"),p.onmessage=z,U}}()?(y="setImmediate$"+Math.random()+"$",p.addEventListener?p.addEventListener("message",I,!1):p.attachEvent("onmessage",I),function(U){p.postMessage(y+U,"*")}):p.MessageChannel?((M=new MessageChannel).port1.onmessage=function(U){b(U.data)},function(U){M.port2.postMessage(U)}):S&&"onreadystatechange"in S.createElement("script")?(g=S.documentElement,function(U){var z=S.createElement("script");z.onreadystatechange=function(){b(U),z.onreadystatechange=null,g.removeChild(z),z=null},g.appendChild(z)}):function(U){setTimeout(b,0,U)},C.setImmediate=function(U){typeof U!="function"&&(U=new Function(""+U));for(var z=new Array(arguments.length-1),B=0;B<z.length;B++)z[B]=arguments[B+1];var j={callback:U,args:z};return T[E]=j,h(E),E++},C.clearImmediate=w}function w(U){delete T[U]}function b(U){if(O)setTimeout(b,0,U);else{var z=T[U];if(z){O=!0;try{(function(B){var j=B.callback,N=B.args;switch(N.length){case 0:j();break;case 1:j(N[0]);break;case 2:j(N[0],N[1]);break;case 3:j(N[0],N[1],N[2]);break;default:j.apply(_,N)}})(z)}finally{w(U),O=!1}}}}function I(U){U.source===p&&typeof U.data=="string"&&U.data.indexOf(y)===0&&b(+U.data.slice(y.length))}})(typeof self>"u"?l===void 0?this:l:self)}).call(this,typeof Co<"u"?Co:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(tx);var fE=tx.exports;const hE=k_(fE);var rx={exports:{}};(function(e,t){(function(r,o){o()})(Co,function(){function r(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,y){var E=new XMLHttpRequest;E.open("GET",g),E.responseType="blob",E.onload=function(){h(E.response,M,y)},E.onerror=function(){console.error("could not download file")},E.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 p=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Co=="object"&&Co.global===Co?Co:void 0,_=p.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),h=p.saveAs||(typeof window!="object"||window!==p?function(){}:"download"in HTMLAnchorElement.prototype&&!_?function(g,M,y){var E=p.URL||p.webkitURL,T=document.createElement("a");M=M||g.name||"download",T.download=M,T.rel="noopener",typeof g=="string"?(T.href=g,T.origin===location.origin?l(T):a(T.href)?o(g,M,y):l(T,T.target="_blank")):(T.href=E.createObjectURL(g),setTimeout(function(){E.revokeObjectURL(T.href)},4e4),setTimeout(function(){l(T)},0))}:"msSaveOrOpenBlob"in navigator?function(g,M,y){if(M=M||g.name||"download",typeof g!="string")navigator.msSaveOrOpenBlob(r(g,y),M);else if(a(g))o(g,M,y);else{var E=document.createElement("a");E.href=g,E.target="_blank",setTimeout(function(){l(E)})}}:function(g,M,y,E){if(E=E||open("","_blank"),E&&(E.document.title=E.document.body.innerText="downloading..."),typeof g=="string")return o(g,M,y);var T=g.type==="application/octet-stream",O=/constructor/i.test(p.HTMLElement)||p.safari,S=/CriOS\/[\d]+/.test(navigator.userAgent);if((S||T&&O||_)&&typeof FileReader<"u"){var C=new FileReader;C.onloadend=function(){var I=C.result;I=S?I:I.replace(/^data:[^;]*;/,"data:attachment/file;"),E?E.location.href=I:location=I,E=null},C.readAsDataURL(g)}else{var w=p.URL||p.webkitURL,b=w.createObjectURL(g);E?E.location=b:location.href=b,E=null,setTimeout(function(){w.revokeObjectURL(b)},4e4)}});p.saveAs=h.saveAs=h,e.exports=h})})(rx);var mE=rx.exports;function gE(){const[e,t]=fr.useState([]),[r,o]=fr.useState([]),[a,l]=fr.useState(!1),[p,_]=fr.useState(!1),[h,g]=fr.useState(!0),[M,y]=fr.useState(null),E=fr.useRef(null),T=fr.useRef(null);fr.useEffect(()=>{(async()=>{try{if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser.");const ce="Xenova/modnet";pE.backends.onnx.wasm.proxy=!1,E.current??(E.current=await cE.from_pretrained(ce,{device:"webgpu"})),T.current??(T.current=await dE.from_pretrained(ce))}catch(ce){y(ce)}g(!1)})()},[]);const O=fr.useCallback(ce=>{t(xe=>[...xe,...ce.map(Y=>URL.createObjectURL(Y))])},[]),{getRootProps:S,getInputProps:C,isDragActive:w,isDragAccept:b,isDragReject:I}=Y2({onDrop:O,accept:{"image/*":[".jpeg",".jpg",".png"]}}),U=ce=>{t(xe=>xe.filter((Y,_e)=>_e!==ce)),o(xe=>xe.filter((Y,_e)=>_e!==ce))},z=async()=>{l(!0),o([]);const ce=E.current,xe=T.current;for(let Y=0;Y<e.length;++Y){const _e=await T1.fromURL(e[Y]),{pixel_values:L}=await xe(_e),{output:Se}=await ce({input:L}),Xe=(await T1.fromTensor(Se[0].mul(255).to("uint8")).resize(_e.width,_e.height)).data,me=document.createElement("canvas");me.width=_e.width,me.height=_e.height;const X=me.getContext("2d");X.drawImage(_e.toCanvas(),0,0);const ie=X.getImageData(0,0,_e.width,_e.height);for(let Me=0;Me<Xe.length;++Me)ie.data[4*Me+3]=Xe[Me];X.putImageData(ie,0,0),o(Me=>[...Me,me.toDataURL("image/png")])}l(!1),_(!0)},B=async()=>{const ce=new hE,xe=e.map((_e,L)=>new Promise(Se=>{const Xe=document.createElement("canvas"),me=Xe.getContext("2d"),X=new Image;X.src=r[L]||_e,X.onload=()=>{Xe.width=X.width,Xe.height=X.height,me.drawImage(X,0,0),Xe.toBlob(ie=>{ie&&ce.file(`image-${L+1}.png`,ie),Se(null)},"image/png")}}));await Promise.all(xe);const Y=await ce.generateAsync({type:"blob"});mE.saveAs(Y,"images.zip")},j=()=>{t([]),o([]),_(!1)},N=async ce=>{try{const Y=await(await fetch(ce)).blob(),_e=new ClipboardItem({[Y.type]:Y});await navigator.clipboard.write([_e]),console.log("Image copied to clipboard")}catch(xe){console.error("Failed to copy image: ",xe)}},ae=ce=>{const xe=document.createElement("a");xe.href=ce,xe.download="image.png",document.body.appendChild(xe),xe.click(),document.body.removeChild(xe)};return M?Cr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:Cr.jsxs("div",{className:"text-center",children:[Cr.jsx("h2",{className:"text-4xl mb-2",children:"ERROR"}),Cr.jsx("p",{className:"text-xl max-w-[500px]",children:M.message})]})}):h?Cr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:Cr.jsxs("div",{className:"text-center",children:[Cr.jsx("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-white mb-4"}),Cr.jsx("p",{className:"text-lg",children:"Loading background removal model..."})]})}):Cr.jsx("div",{className:"min-h-screen bg-black text-white p-8",children:Cr.jsxs("div",{className:"max-w-4xl mx-auto",children:[Cr.jsx("h1",{className:"text-4xl font-bold mb-2 text-center",children:"Remove Background WebGPU"}),Cr.jsxs("h2",{className:"text-lg font-semibold mb-2 text-center",children:["In-browser background removal, powered by"," ",Cr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),Cr.jsxs("div",{className:"flex justify-center mb-8 gap-8",children:[Cr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/huggingface/transformers.js-examples/blob/main/LICENSE",children:"License (Apache 2.0)"}),Cr.jsx("a",{className:"underline",target:"_blank",href:"https://huggingface.co/Xenova/modnet",children:"Model (MODNet)"}),Cr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/huggingface/transformers.js-examples/pull/4",children:"Code (GitHub)"})]}),Cr.jsxs("div",{...S(),className:`p-8 mb-8 border-2 border-dashed rounded-lg text-center cursor-pointer transition-colors duration-300 ease-in-out ${b?"border-green-500 bg-green-900/20":""} ${I?"border-red-500 bg-red-900/20":""} ${w?"border-blue-500 bg-blue-900/20":"border-gray-700 hover:border-blue-500 hover:bg-blue-900/10"} `,children:[Cr.jsx("input",{...C(),className:"hidden"}),Cr.jsx("p",{className:"text-lg mb-2",children:w?"Drop the images here...":"Drag and drop some images here"}),Cr.jsx("p",{className:"text-sm text-gray-400",children:"or click to select files"})]}),Cr.jsxs("div",{className:"flex flex-col items-center gap-4 mb-8",children:[Cr.jsx("button",{onClick:z,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"}),Cr.jsxs("div",{className:"flex gap-4",children:[Cr.jsx("button",{onClick:B,disabled:!p,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"}),Cr.jsx("button",{onClick:j,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"})]})]}),Cr.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6",children:e.map((ce,xe)=>Cr.jsxs("div",{className:"relative group",children:[Cr.jsx("img",{src:r[xe]||ce,alt:`Image ${xe+1}`,className:"rounded-lg object-cover w-full h-48"}),r[xe]&&Cr.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:[Cr.jsx("button",{onClick:()=>N(r[xe]||ce),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 ${xe+1} to clipboard`,children:"Copy"}),Cr.jsx("button",{onClick:()=>ae(r[xe]||ce),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 ${xe+1}`,children:"Download"})]}),Cr.jsx("button",{onClick:()=>U(xe),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 ${xe+1}`,children:"✕"})]},xe))})]})})}L2(document.getElementById("root")).render(Cr.jsx(fr.StrictMode,{children:Cr.jsx(gE,{})}));